From 1d84b2b76a3136f20623dbe131d56feb3507aaaf Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Mon, 7 Nov 2022 16:13:29 +0400 Subject: [PATCH] Merge `rustfmt.toml`s --- crates/teloxide-core/examples/erased.rs | 7 +- crates/teloxide-core/examples/self_info.rs | 10 +- crates/teloxide-core/rustfmt.toml | 6 - crates/teloxide-core/src/adaptors/cache_me.rs | 5 +- crates/teloxide-core/src/adaptors/erased.rs | 12 +- .../teloxide-core/src/adaptors/parse_mode.rs | 5 +- crates/teloxide-core/src/adaptors/throttle.rs | 21 +-- .../src/adaptors/throttle/worker.rs | 17 +- crates/teloxide-core/src/adaptors/trace.rs | 16 +- crates/teloxide-core/src/bot.rs | 10 +- crates/teloxide-core/src/bot/api.rs | 40 +---- crates/teloxide-core/src/codegen.rs | 26 +-- crates/teloxide-core/src/codegen/patch.rs | 60 ++----- crates/teloxide-core/src/errors.rs | 35 ++-- crates/teloxide-core/src/lib.rs | 6 +- crates/teloxide-core/src/local_macros.rs | 15 +- crates/teloxide-core/src/net.rs | 16 +- crates/teloxide-core/src/net/download.rs | 27 ++- crates/teloxide-core/src/net/request.rs | 5 +- .../src/net/telegram_response.rs | 10 +- crates/teloxide-core/src/payloads.rs | 5 +- crates/teloxide-core/src/payloads/codegen.rs | 38 +---- .../src/requests/multipart_payload.rs | 10 +- .../teloxide-core/src/requests/requester.rs | 19 +-- .../teloxide-core/src/serde_multipart/mod.rs | 28 +--- .../src/serde_multipart/serializers.rs | 20 +-- crates/teloxide-core/src/types.rs | 10 +- crates/teloxide-core/src/types/animation.rs | 12 +- crates/teloxide-core/src/types/audio.rs | 12 +- crates/teloxide-core/src/types/bot_command.rs | 5 +- .../src/types/bot_command_scope.rs | 5 +- crates/teloxide-core/src/types/chat.rs | 21 +-- crates/teloxide-core/src/types/chat_id.rs | 24 +-- crates/teloxide-core/src/types/chat_member.rs | 79 ++++----- crates/teloxide-core/src/types/file.rs | 6 +- crates/teloxide-core/src/types/force_reply.rs | 6 +- .../src/types/inline_keyboard_button.rs | 15 +- .../src/types/inline_keyboard_markup.rs | 18 +- .../src/types/inline_query_result_game.rs | 6 +- crates/teloxide-core/src/types/input_file.rs | 16 +- crates/teloxide-core/src/types/input_media.rs | 7 +- .../src/types/keyboard_button.rs | 61 ++----- crates/teloxide-core/src/types/label_price.rs | 10 +- .../teloxide-core/src/types/mask_position.rs | 7 +- crates/teloxide-core/src/types/me.rs | 10 +- crates/teloxide-core/src/types/message.rs | 84 +++------- .../teloxide-core/src/types/message_entity.rs | 155 +++--------------- .../src/types/passport_element_error.rs | 51 ++---- crates/teloxide-core/src/types/photo_size.rs | 6 +- .../src/types/reply_keyboard_markup.rs | 6 +- .../src/types/reply_keyboard_remove.rs | 5 +- .../src/types/shipping_option.rs | 11 +- crates/teloxide-core/src/types/sticker.rs | 20 +-- crates/teloxide-core/src/types/update.rs | 12 +- crates/teloxide-core/src/types/user.rs | 21 +-- crates/teloxide-core/src/types/user_id.rs | 4 +- crates/teloxide-macros/rustfmt.toml | 7 - crates/teloxide-macros/src/attr.rs | 29 +--- crates/teloxide-macros/src/bot_commands.rs | 31 ++-- crates/teloxide-macros/src/command.rs | 12 +- crates/teloxide-macros/src/command_attr.rs | 22 +-- crates/teloxide-macros/src/command_enum.rs | 21 +-- crates/teloxide-macros/src/error.rs | 4 +- crates/teloxide-macros/src/fields_parse.rs | 38 ++--- crates/teloxide-macros/src/rename_rules.rs | 10 +- crates/teloxide-macros/tests/command.rs | 99 +++-------- rustfmt.toml | 1 + 67 files changed, 341 insertions(+), 1107 deletions(-) delete mode 100644 crates/teloxide-core/rustfmt.toml delete mode 100644 crates/teloxide-macros/rustfmt.toml diff --git a/crates/teloxide-core/examples/erased.rs b/crates/teloxide-core/examples/erased.rs index 2c54123c..feeffbdc 100644 --- a/crates/teloxide-core/examples/erased.rs +++ b/crates/teloxide-core/examples/erased.rs @@ -6,11 +6,8 @@ use teloxide_core::{adaptors::trace, prelude::*, types::ChatAction}; async fn main() -> Result<(), Box> { pretty_env_logger::init(); - let chat_id = ChatId( - std::env::var("CHAT_ID") - .expect("Expected CHAT_ID env var") - .parse::()?, - ); + let chat_id = + ChatId(std::env::var("CHAT_ID").expect("Expected CHAT_ID env var").parse::()?); let trace_settings = match std::env::var("TRACE").as_deref() { Ok("EVERYTHING_VERBOSE") => trace::Settings::TRACE_EVERYTHING_VERBOSE, diff --git a/crates/teloxide-core/examples/self_info.rs b/crates/teloxide-core/examples/self_info.rs index e3747671..6ea7cb24 100644 --- a/crates/teloxide-core/examples/self_info.rs +++ b/crates/teloxide-core/examples/self_info.rs @@ -7,19 +7,15 @@ use teloxide_core::{ async fn main() -> Result<(), Box> { pretty_env_logger::init(); - let chat_id = ChatId( - std::env::var("CHAT_ID") - .expect("Expected CHAT_ID env var") - .parse::()?, - ); + let chat_id = + ChatId(std::env::var("CHAT_ID").expect("Expected CHAT_ID env var").parse::()?); let bot = Bot::from_env().parse_mode(ParseMode::MarkdownV2); let Me { user: me, .. } = bot.get_me().await?; bot.send_dice(chat_id).emoji(DiceEmoji::Dice).await?; - bot.send_message(chat_id, format!("Hi, my name is **{}** 👋", me.first_name)) - .await?; + bot.send_message(chat_id, format!("Hi, my name is **{}** 👋", me.first_name)).await?; Ok(()) } diff --git a/crates/teloxide-core/rustfmt.toml b/crates/teloxide-core/rustfmt.toml deleted file mode 100644 index 16746573..00000000 --- a/crates/teloxide-core/rustfmt.toml +++ /dev/null @@ -1,6 +0,0 @@ -format_code_in_doc_comments = true -wrap_comments = true -format_strings = true -imports_granularity = "Crate" -use_field_init_shorthand = true -merge_derives = false diff --git a/crates/teloxide-core/src/adaptors/cache_me.rs b/crates/teloxide-core/src/adaptors/cache_me.rs index 30365693..86ee8118 100644 --- a/crates/teloxide-core/src/adaptors/cache_me.rs +++ b/crates/teloxide-core/src/adaptors/cache_me.rs @@ -32,10 +32,7 @@ impl CacheMe { /// /// [`RequesterExt::cache_me`]: crate::requests::RequesterExt::cache_me pub fn new(bot: B) -> CacheMe { - Self { - bot, - me: Arc::new(OnceCell::new()), - } + Self { bot, me: Arc::new(OnceCell::new()) } } /// Allows to access inner bot diff --git a/crates/teloxide-core/src/adaptors/erased.rs b/crates/teloxide-core/src/adaptors/erased.rs index 1cac5f5c..f5d2d6bf 100644 --- a/crates/teloxide-core/src/adaptors/erased.rs +++ b/crates/teloxide-core/src/adaptors/erased.rs @@ -24,9 +24,7 @@ impl<'a, E> ErasedRequester<'a, E> { where B: Requester + 'a, { - Self { - inner: Arc::new(requester), - } + Self { inner: Arc::new(requester) } } } @@ -39,9 +37,7 @@ impl std::fmt::Debug for ErasedRequester<'_, E> { // NB. hand-written impl to avoid `E: Clone` bound impl Clone for ErasedRequester<'_, E> { fn clone(&self) -> Self { - Self { - inner: Arc::clone(&self.inner), - } + Self { inner: Arc::clone(&self.inner) } } } @@ -54,9 +50,7 @@ pub struct ErasedRequest<'a, T, E> { // `T: Payload` required b/c of impl<'a, T: Payload, E> ErasedRequest<'a, T, E> { pub(crate) fn erase(request: impl Request + 'a) -> Self { - Self { - inner: Box::new(request), - } + Self { inner: Box::new(request) } } } diff --git a/crates/teloxide-core/src/adaptors/parse_mode.rs b/crates/teloxide-core/src/adaptors/parse_mode.rs index 04516105..cd6e6870 100644 --- a/crates/teloxide-core/src/adaptors/parse_mode.rs +++ b/crates/teloxide-core/src/adaptors/parse_mode.rs @@ -21,10 +21,7 @@ impl DefaultParseMode { /// /// [`RequesterExt::parse_mode`]: crate::requests::RequesterExt::parse_mode pub fn new(bot: B, parse_mode: ParseMode) -> Self { - Self { - bot, - mode: parse_mode, - } + Self { bot, mode: parse_mode } } /// Allows to access the inner bot. diff --git a/crates/teloxide-core/src/adaptors/throttle.rs b/crates/teloxide-core/src/adaptors/throttle.rs index d55b3d88..7c4aaba3 100644 --- a/crates/teloxide-core/src/adaptors/throttle.rs +++ b/crates/teloxide-core/src/adaptors/throttle.rs @@ -88,10 +88,7 @@ impl Throttle { B: Requester + Clone, B::Err: AsResponseParameters, { - let settings = Settings { - limits, - ..<_>::default() - }; + let settings = Settings { limits, ..<_>::default() }; Self::with_settings(bot, settings) } @@ -108,11 +105,7 @@ impl Throttle { let (info_tx, info_rx) = mpsc::channel(2); let worker = worker(settings, rx, info_rx, bot.clone()); - let this = Self { - bot, - queue: tx, - info_tx, - }; + let this = Self { bot, queue: tx, info_tx }; (this, worker) } @@ -164,10 +157,7 @@ impl Throttle { let (tx, rx) = oneshot::channel(); - self.info_tx - .send(InfoMessage::GetLimits { response: tx }) - .await - .expect(WORKER_DIED); + self.info_tx.send(InfoMessage::GetLimits { response: tx }).await.expect(WORKER_DIED); rx.await.expect(WORKER_DIED) } @@ -178,10 +168,7 @@ impl Throttle { pub async fn set_limits(&self, new: Limits) { let (tx, rx) = oneshot::channel(); - self.info_tx - .send(InfoMessage::SetLimits { new, response: tx }) - .await - .ok(); + self.info_tx.send(InfoMessage::SetLimits { new, response: tx }).await.ok(); rx.await.ok(); } diff --git a/crates/teloxide-core/src/adaptors/throttle/worker.rs b/crates/teloxide-core/src/adaptors/throttle/worker.rs index 62438013..6a2994dd 100644 --- a/crates/teloxide-core/src/adaptors/throttle/worker.rs +++ b/crates/teloxide-core/src/adaptors/throttle/worker.rs @@ -90,12 +90,7 @@ pub(super) struct FreezeUntil { // the request that it can be now executed, increase counts, add record to the // history. pub(super) async fn worker( - Settings { - mut limits, - mut on_queue_full, - retry, - check_slow_mode, - }: Settings, + Settings { mut limits, mut on_queue_full, retry, check_slow_mode }: Settings, mut rx: mpsc::Receiver<(ChatIdHash, RequestLock)>, mut info_rx: mpsc::Receiver, bot: B, @@ -117,9 +112,8 @@ pub(super) async fn worker( let mut rx_is_closed = false; - let mut last_queue_full = Instant::now() - .checked_sub(QUEUE_FULL_DELAY) - .unwrap_or_else(Instant::now); + let mut last_queue_full = + Instant::now().checked_sub(QUEUE_FULL_DELAY).unwrap_or_else(Instant::now); let (freeze_tx, mut freeze_rx) = mpsc::channel::(1); @@ -214,10 +208,7 @@ pub(super) async fn worker( // as truncates which is ok since in case of truncation it would always be >= // limits.overall_s - let used = history - .iter() - .take_while(|(_, time)| time > &sec_back) - .count() as u32; + let used = history.iter().take_while(|(_, time)| time > &sec_back).count() as u32; let mut allowed = limits.messages_per_sec_overall.saturating_sub(used); if allowed == 0 { diff --git a/crates/teloxide-core/src/adaptors/trace.rs b/crates/teloxide-core/src/adaptors/trace.rs index fef86e76..bcc43828 100644 --- a/crates/teloxide-core/src/adaptors/trace.rs +++ b/crates/teloxide-core/src/adaptors/trace.rs @@ -249,11 +249,7 @@ where { if self.settings.contains(Settings::TRACE_RESPONSES_VERBOSE) { |response| { - log::trace!( - "Got response from `{}` request: {:?}", - R::Payload::NAME, - response - ) + log::trace!("Got response from `{}` request: {:?}", R::Payload::NAME, response) } } else if self.settings.contains(Settings::TRACE_RESPONSES) { |_| log::trace!("Got response from `{}` request", R::Payload::NAME) @@ -294,19 +290,13 @@ where fn send(self) -> Self::Send { self.trace_request(); - Send { - trace_fn: self.trace_response_fn(), - inner: self.inner.send(), - } + Send { trace_fn: self.trace_response_fn(), inner: self.inner.send() } } fn send_ref(&self) -> Self::SendRef { self.trace_request(); - Send { - trace_fn: self.trace_response_fn(), - inner: self.inner.send_ref(), - } + Send { trace_fn: self.trace_response_fn(), inner: self.inner.send_ref() } } } diff --git a/crates/teloxide-core/src/bot.rs b/crates/teloxide-core/src/bot.rs index 19bb00d5..ef0801f8 100644 --- a/crates/teloxide-core/src/bot.rs +++ b/crates/teloxide-core/src/bot.rs @@ -71,9 +71,7 @@ impl Bot { where S: Into, { - let client = net::default_reqwest_settings() - .build() - .expect("Client creation failed"); + let client = net::default_reqwest_settings().build().expect("Client creation failed"); Self::with_client(token, client) } @@ -98,11 +96,7 @@ impl Bot { .expect("Failed to parse default Telegram bot API url"), ); - Self { - token, - api_url, - client, - } + Self { token, api_url, client } } /// Creates a new `Bot` with the `TELOXIDE_TOKEN` & `TELOXIDE_PROXY` diff --git a/crates/teloxide-core/src/bot/api.rs b/crates/teloxide-core/src/bot/api.rs index f0fbfa78..1572a371 100644 --- a/crates/teloxide-core/src/bot/api.rs +++ b/crates/teloxide-core/src/bot/api.rs @@ -114,10 +114,7 @@ impl Requester for Bot { where C: Into, { - Self::SendAnimation::new( - self.clone(), - payloads::SendAnimation::new(chat_id, animation), - ) + Self::SendAnimation::new(self.clone(), payloads::SendAnimation::new(chat_id, animation)) } type SendVoice = MultipartRequest; @@ -135,10 +132,7 @@ impl Requester for Bot { where C: Into, { - Self::SendVideoNote::new( - self.clone(), - payloads::SendVideoNote::new(chat_id, video_note), - ) + Self::SendVideoNote::new(self.clone(), payloads::SendVideoNote::new(chat_id, video_note)) } type SendMediaGroup = MultipartRequest; @@ -276,10 +270,7 @@ impl Requester for Bot { Q: Into, O: IntoIterator, { - Self::SendPoll::new( - self.clone(), - payloads::SendPoll::new(chat_id, question, options), - ) + Self::SendPoll::new(self.clone(), payloads::SendPoll::new(chat_id, question, options)) } type SendDice = JsonRequest; @@ -325,10 +316,7 @@ impl Requester for Bot { where C: Into, { - Self::KickChatMember::new( - self.clone(), - payloads::KickChatMember::new(chat_id, user_id), - ) + Self::KickChatMember::new(self.clone(), payloads::KickChatMember::new(chat_id, user_id)) } type BanChatMember = JsonRequest; @@ -346,10 +334,7 @@ impl Requester for Bot { where C: Into, { - Self::UnbanChatMember::new( - self.clone(), - payloads::UnbanChatMember::new(chat_id, user_id), - ) + Self::UnbanChatMember::new(self.clone(), payloads::UnbanChatMember::new(chat_id, user_id)) } type RestrictChatMember = JsonRequest; @@ -568,10 +553,7 @@ impl Requester for Bot { where C: Into, { - Self::PinChatMessage::new( - self.clone(), - payloads::PinChatMessage::new(chat_id, message_id), - ) + Self::PinChatMessage::new(self.clone(), payloads::PinChatMessage::new(chat_id, message_id)) } type UnpinChatMessage = JsonRequest; @@ -892,10 +874,7 @@ impl Requester for Bot { where C: Into, { - Self::DeleteMessage::new( - self.clone(), - payloads::DeleteMessage::new(chat_id, message_id), - ) + Self::DeleteMessage::new(self.clone(), payloads::DeleteMessage::new(chat_id, message_id)) } type SendSticker = MultipartRequest; @@ -1131,10 +1110,7 @@ impl Requester for Bot { where G: Into, { - Self::SendGame::new( - self.clone(), - payloads::SendGame::new(chat_id, game_short_name), - ) + Self::SendGame::new(self.clone(), payloads::SendGame::new(chat_id, game_short_name)) } type SetGameScore = JsonRequest; diff --git a/crates/teloxide-core/src/codegen.rs b/crates/teloxide-core/src/codegen.rs index fa165066..5a11f801 100644 --- a/crates/teloxide-core/src/codegen.rs +++ b/crates/teloxide-core/src/codegen.rs @@ -26,9 +26,7 @@ fn ensure_rustfmt(sh: &Shell) { // FIXME(waffle): find a better way to set toolchain let toolchain = "nightly-2022-09-23"; - let version = cmd!(sh, "rustup run {toolchain} rustfmt --version") - .read() - .unwrap_or_default(); + let version = cmd!(sh, "rustup run {toolchain} rustfmt --version").read().unwrap_or_default(); if !version.contains("nightly") { panic!( @@ -81,12 +79,7 @@ pub fn ensure_files_contents<'a>( let mut err_count = 0; for (path, contents) in files_and_contents { - let mut file = fs::File::options() - .read(true) - .write(true) - .create(true) - .open(path) - .unwrap(); + let mut file = fs::File::options().read(true).write(true).create(true).open(path).unwrap(); let mut old_contents = String::with_capacity(contents.len()); file.read_to_string(&mut old_contents).unwrap(); @@ -146,28 +139,19 @@ pub fn replace_block(path: &Path, title: &str, new: &str) -> String { } let start_offset = match &*starts { - [] => panic!( - "Coulnd't find start of block {title} in {p}", - p = path.display() - ), + [] => panic!("Coulnd't find start of block {title} in {p}", p = path.display()), [offset] => offset.end, [..] => panic!(), }; let end_offset = match &*ends { - [] => panic!( - "Coulnd't find end of block {title} in {p}", - p = path.display() - ), + [] => panic!("Coulnd't find end of block {title} in {p}", p = path.display()), [offset] => offset.start, [..] => panic!(), }; if end_offset < start_offset { - panic!( - "End of the {title} block is located before the start in {p}", - p = path.display() - ); + panic!("End of the {title} block is located before the start in {p}", p = path.display()); } format!("{}{}{}", &file[..start_offset], new, &file[end_offset..]) diff --git a/crates/teloxide-core/src/codegen/patch.rs b/crates/teloxide-core/src/codegen/patch.rs index a235fcd2..60ebc820 100644 --- a/crates/teloxide-core/src/codegen/patch.rs +++ b/crates/teloxide-core/src/codegen/patch.rs @@ -6,11 +6,7 @@ pub fn patch_schema(mut schema: Schema) -> Schema { } schema.methods.iter_mut().for_each(|method| { - method - .params - .iter_mut() - .map(|p| &mut p.name) - .for_each(escape_kw); + method.params.iter_mut().map(|p| &mut p.name).for_each(escape_kw); DOC_PATCHES.iter().for_each(|(key, patch)| match key { Target::Method(m) => { @@ -18,10 +14,7 @@ pub fn patch_schema(mut schema: Schema) -> Schema { method.doc.patch(patch, *key); } } - Target::Field { - method_name: m, - field_name: f, - } => { + Target::Field { method_name: m, field_name: f } => { if check(m, &method.names.0) { method .params @@ -34,10 +27,7 @@ pub fn patch_schema(mut schema: Schema) -> Schema { if check(m, &method.names.0) { method.doc.patch(patch, *key); - method - .params - .iter_mut() - .for_each(|p| p.descr.patch(patch, *key)) + method.params.iter_mut().for_each(|p| p.descr.patch(patch, *key)) } } }); @@ -164,24 +154,18 @@ static DOC_PATCHES: &[(Target, Patch)] = &[ #[derive(Debug, Clone, Copy)] enum Target<'a> { - Any { - method_name: Option<&'a str>, - }, + Any { method_name: Option<&'a str> }, Method(Option<&'a str>), - Field { - method_name: Option<&'a str>, - field_name: Option<&'a str>, - }, + Field { method_name: Option<&'a str>, field_name: Option<&'a str> }, } impl<'a> Target<'a> { fn is_exact(&self) -> bool { match self { Target::Method(m) => m.is_some(), - Target::Field { - method_name, - field_name, - } => method_name.is_some() && field_name.is_some(), + Target::Field { method_name, field_name } => { + method_name.is_some() && field_name.is_some() + } Target::Any { method_name: _ } => false, } } @@ -208,8 +192,7 @@ impl Doc { } } Patch::AddLink { name, value } => { - self.md_links - .insert((*name).to_owned(), (*value).to_owned()); + self.md_links.insert((*name).to_owned(), (*value).to_owned()); } // Patch::RemoveLink { name } => drop(self.md_links.remove(*name)), // Patch::FullReplace { text, with } => { @@ -253,9 +236,7 @@ fn intra_links(doc: &mut Doc) { for repl in repls_t { if let Some(value) = doc.md_links.remove(repl.as_str()) { - doc.md = doc - .md - .replace(format!("[{}]", repl).as_str(), &format!("[`{}`]", repl)); + doc.md = doc.md.replace(format!("[{}]", repl).as_str(), &format!("[`{}`]", repl)); doc.md_links.insert(format!("`{}`", repl), value); } } @@ -263,9 +244,7 @@ fn intra_links(doc: &mut Doc) { for repl in repls_m { if let Some(value) = doc.md_links.remove(repl.as_str()) { let repln = to_uppercase(&repl); - doc.md = doc - .md - .replace(format!("[{}]", repl).as_str(), &format!("[`{}`]", repln)); + doc.md = doc.md.replace(format!("[{}]", repl).as_str(), &format!("[`{}`]", repln)); doc.md_links.insert(format!("`{}`", repln), value); } } @@ -284,21 +263,13 @@ fn to_uppercase(s: &str) -> String { pub(crate) fn patch_ty(mut schema: Schema) -> Schema { // URLs - patch_types( - &mut schema, - Type::String, - Type::Url, - &[("set_webhook", "url")], - ); + patch_types(&mut schema, Type::String, Type::Url, &[("set_webhook", "url")]); patch_types( &mut schema, Type::Option(Box::new(Type::String)), Type::Option(Box::new(Type::Url)), - &[ - ("answer_callback_query", "url"), - ("send_invoice", "photo_url"), - ], + &[("answer_callback_query", "url"), ("send_invoice", "photo_url")], ); // Dates @@ -317,10 +288,7 @@ pub(crate) fn patch_ty(mut schema: Schema) -> Schema { &mut schema, Type::Option(Box::new(Type::i64)), Type::Option(Box::new(Type::DateTime)), - &[ - ("create_chat_invite_link", "expire_date"), - ("edit_chat_invite_link", "expire_date"), - ], + &[("create_chat_invite_link", "expire_date"), ("edit_chat_invite_link", "expire_date")], ); schema diff --git a/crates/teloxide-core/src/errors.rs b/crates/teloxide-core/src/errors.rs index f6529608..3de77f09 100644 --- a/crates/teloxide-core/src/errors.rs +++ b/crates/teloxide-core/src/errors.rs @@ -110,10 +110,9 @@ pub enum ApiError { /// 1. [`EditMessageText`] /// /// [`EditMessageText`]: crate::payloads::EditMessageText - #[serde( - rename = "Bad Request: message is not modified: specified new message content and reply \ - markup are exactly the same as a current content and reply markup of the message" - )] + #[serde(rename = "Bad Request: message is not modified: specified new message content and \ + reply markup are exactly the same as a current content and reply markup \ + of the message")] #[error( "Bad Request: message is not modified: specified new message content and reply markup are \ exactly the same as a current content and reply markup of the message" @@ -390,10 +389,8 @@ pub enum ApiError { /// 1. [`AnswerCallbackQuery`] /// /// [`AnswerCallbackQuery`]: crate::payloads::AnswerCallbackQuery - #[serde( - rename = "Bad Request: query is too old and response timeout expired or query id is \ - invalid" - )] + #[serde(rename = "Bad Request: query is too old and response timeout expired or query id is \ + invalid")] #[error("Bad Request: query is too old and response timeout expired or query id is invalid")] InvalidQueryId, @@ -424,10 +421,8 @@ pub enum ApiError { /// 1. [`SendMessage`] /// /// [`SendMessage`]: crate::payloads::SendMessage - #[serde( - rename = "Bad Request: can't parse inline keyboard button: Text buttons are unallowed in \ - the inline keyboard" - )] + #[serde(rename = "Bad Request: can't parse inline keyboard button: Text buttons are \ + unallowed in the inline keyboard")] #[error( "Bad Request: can't parse inline keyboard button: Text buttons are unallowed in the \ inline keyboard" @@ -614,10 +609,8 @@ pub enum ApiError { /// 1. [`SetWebhook`] /// /// [`SetWebhook`]: crate::payloads::SetWebhook - #[serde( - rename = "Bad Request: bad webhook: Webhook can be set up only on ports 80, 88, 443 or \ - 8443" - )] + #[serde(rename = "Bad Request: bad webhook: Webhook can be set up only on ports 80, 88, 443 \ + or 8443")] #[error("Bad Request: bad webhook: Webhook can be set up only on ports 80, 88, 443 or 8443")] BadWebhookPort, @@ -627,9 +620,7 @@ pub enum ApiError { /// 1. [`SetWebhook`] /// /// [`SetWebhook`]: crate::payloads::SetWebhook - #[serde( - rename = "Bad Request: bad webhook: Failed to resolve host: Name or service not known" - )] + #[serde(rename = "Bad Request: bad webhook: Failed to resolve host: Name or service not known")] #[error("Bad Request: bad webhook: Failed to resolve host: Name or service not known")] UnknownHost, @@ -732,10 +723,8 @@ pub enum ApiError { /// 1. [`GetUpdates`] /// /// [`GetUpdates`]: crate::payloads::GetUpdates - #[serde( - rename = "Conflict: terminated by other getUpdates request; make sure that only one bot \ - instance is running" - )] + #[serde(rename = "Conflict: terminated by other getUpdates request; make sure that only one \ + bot instance is running")] #[error( "Conflict: terminated by other getUpdates request; make sure that only one bot instance \ is running" diff --git a/crates/teloxide-core/src/lib.rs b/crates/teloxide-core/src/lib.rs index 36916ec8..7ac35e29 100644 --- a/crates/teloxide-core/src/lib.rs +++ b/crates/teloxide-core/src/lib.rs @@ -22,11 +22,7 @@ //! let me = bot.get_me().await?; //! //! bot.send_dice(chat_id).emoji(DiceEmoji::Dice).await?; -//! bot.send_message( -//! chat_id, -//! format!("Hi, my name is **{}** 👋", me.user.first_name), -//! ) -//! .await?; +//! bot.send_message(chat_id, format!("Hi, my name is **{}** 👋", me.user.first_name)).await?; //! # Ok::<_, Box>(()) }; //! ``` //! diff --git a/crates/teloxide-core/src/local_macros.rs b/crates/teloxide-core/src/local_macros.rs index 8ab0370f..de69f36d 100644 --- a/crates/teloxide-core/src/local_macros.rs +++ b/crates/teloxide-core/src/local_macros.rs @@ -1293,11 +1293,9 @@ fn codegen_requester_forward() { .filter(|p| !matches!(p.ty, Type::Option(_))) .flat_map(|p| match convert_for(&p.ty) { Convert::Id(_) => None, - Convert::Into(ty) => Some(format!( - "{}: Into<{}>", - &to_uppercase(prefixes[&*p.name]), - ty - )), + Convert::Into(ty) => { + Some(format!("{}: Into<{}>", &to_uppercase(prefixes[&*p.name]), ty)) + } Convert::Collect(ty) => Some(format!( "{}: IntoIterator", &to_uppercase(prefixes[&*p.name]), @@ -1306,11 +1304,8 @@ fn codegen_requester_forward() { }) .join(",\n "); - let generics = if generics.is_empty() { - String::from("") - } else { - format!("<{}>", generics) - }; + let generics = + if generics.is_empty() { String::from("") } else { format!("<{}>", generics) }; let where_clause = if where_clause.is_empty() { String::from("") diff --git a/crates/teloxide-core/src/net.rs b/crates/teloxide-core/src/net.rs index 4f76fdb1..d7f96a76 100644 --- a/crates/teloxide-core/src/net.rs +++ b/crates/teloxide-core/src/net.rs @@ -80,24 +80,16 @@ pub fn default_reqwest_settings() -> reqwest::ClientBuilder { /// /// [Telegram documentation]: https://core.telegram.org/bots/api#making-requests fn method_url(base: reqwest::Url, token: &str, method_name: &str) -> reqwest::Url { - base.join(&format!( - "/bot{token}/{method}", - token = token, - method = method_name - )) - .expect("failed to format url") + base.join(&format!("/bot{token}/{method}", token = token, method = method_name)) + .expect("failed to format url") } /// Creates URL for downloading a file. See the [Telegram documentation]. /// /// [Telegram documentation]: https://core.telegram.org/bots/api#file fn file_url(base: reqwest::Url, token: &str, file_path: &str) -> reqwest::Url { - base.join(&format!( - "file/bot{token}/{file}", - token = token, - file = file_path - )) - .expect("failed to format url") + base.join(&format!("file/bot{token}/{file}", token = token, file = file_path)) + .expect("failed to format url") } #[cfg(test)] diff --git a/crates/teloxide-core/src/net/download.rs b/crates/teloxide-core/src/net/download.rs index 685d9f57..ac419a79 100644 --- a/crates/teloxide-core/src/net/download.rs +++ b/crates/teloxide-core/src/net/download.rs @@ -94,18 +94,15 @@ pub fn download_file<'o, D>( where D: ?Sized + AsyncWrite + Unpin, { - client - .get(file_url(api_url, token, path)) - .send() - .then(move |r| async move { - let mut res = r?.error_for_status()?; + client.get(file_url(api_url, token, path)).send().then(move |r| async move { + let mut res = r?.error_for_status()?; - while let Some(chunk) = res.chunk().await? { - dst.write_all(&chunk).await?; - } + while let Some(chunk) = res.chunk().await? { + dst.write_all(&chunk).await?; + } - Ok(()) - }) + Ok(()) + }) } /// Download a file from Telegram as [`Stream`]. @@ -119,11 +116,8 @@ pub fn download_file_stream( token: &str, path: &str, ) -> impl Stream> + 'static { - client - .get(file_url(api_url, token, path)) - .send() - .into_stream() - .flat_map(|res| match res.and_then(Response::error_for_status) { + client.get(file_url(api_url, token, path)).send().into_stream().flat_map(|res| { + match res.and_then(Response::error_for_status) { Ok(res) => Either::Left(unfold(res, |mut res| async { match res.chunk().await { Err(err) => Some((Err(err), res)), @@ -132,5 +126,6 @@ pub fn download_file_stream( } })), Err(err) => Either::Right(once(ready(Err(err)))), - }) + } + }) } diff --git a/crates/teloxide-core/src/net/request.rs b/crates/teloxide-core/src/net/request.rs index 1b2273cd..7fa345ec 100644 --- a/crates/teloxide-core/src/net/request.rs +++ b/crates/teloxide-core/src/net/request.rs @@ -100,9 +100,6 @@ where let text = response.text().await?; serde_json::from_str::>(&text) - .map_err(|source| RequestError::InvalidJson { - source, - raw: text.into(), - })? + .map_err(|source| RequestError::InvalidJson { source, raw: text.into() })? .into() } diff --git a/crates/teloxide-core/src/net/telegram_response.rs b/crates/teloxide-core/src/net/telegram_response.rs index 2c99235e..4dfa5ba1 100644 --- a/crates/teloxide-core/src/net/telegram_response.rs +++ b/crates/teloxide-core/src/net/telegram_response.rs @@ -37,10 +37,7 @@ impl From> for ResponseResult { fn from(this: TelegramResponse) -> ResponseResult { match this { TelegramResponse::Ok { response, .. } => Ok(response), - TelegramResponse::Err { - response_parameters: Some(params), - .. - } => Err(match params { + TelegramResponse::Err { response_parameters: Some(params), .. } => Err(match params { ResponseParameters::RetryAfter(i) => RequestError::RetryAfter(i), ResponseParameters::MigrateToChatId(to) => RequestError::MigrateToChatId(to), }), @@ -61,10 +58,7 @@ mod tests { assert!(matches!( val, - TelegramResponse::Err { - error: ApiError::TerminatedByOtherGetUpdates, - .. - } + TelegramResponse::Err { error: ApiError::TerminatedByOtherGetUpdates, .. } )); } diff --git a/crates/teloxide-core/src/payloads.rs b/crates/teloxide-core/src/payloads.rs index 168c257a..ee37f29c 100644 --- a/crates/teloxide-core/src/payloads.rs +++ b/crates/teloxide-core/src/payloads.rs @@ -237,10 +237,7 @@ fn codegen_payload_mods_and_reexports() { let schema = schema::get(); let mut block = String::new(); - schema - .methods - .iter() - .for_each(|m| block.push_str(&format!("mod {};\n", m.names.2))); + schema.methods.iter().for_each(|m| block.push_str(&format!("mod {};\n", m.names.2))); block.push('\n'); diff --git a/crates/teloxide-core/src/payloads/codegen.rs b/crates/teloxide-core/src/payloads/codegen.rs index 0032f9a5..771caa7d 100644 --- a/crates/teloxide-core/src/payloads/codegen.rs +++ b/crates/teloxide-core/src/payloads/codegen.rs @@ -24,19 +24,12 @@ fn codegen_payloads() { let uses = uses(&method); let method_doc = render_doc(&method.doc, method.sibling.as_deref()); - let eq_hash_derive = eq_hash_suitable(&method) - .then(|| " Eq, Hash,") - .unwrap_or(""); + let eq_hash_derive = eq_hash_suitable(&method).then(|| " Eq, Hash,").unwrap_or(""); let default_derive = default_needed(&method).then(|| " Default,").unwrap_or(""); let return_ty = method.return_ty.to_string(); - let required = params( - method - .params - .iter() - .filter(|p| !matches!(&p.ty, Type::Option(_))), - ); + let required = params(method.params.iter().filter(|p| !matches!(&p.ty, Type::Option(_)))); let required = match &*required { "" => "".to_owned(), _ => format!(" required {{\n{required}\n }}"), @@ -155,10 +148,8 @@ fn render_doc(doc: &Doc, sibling: Option<&str>) -> String { let links = match &doc.md_links { links if links.is_empty() => String::new(), links => { - let l: String = links - .iter() - .map(|(name, link)| format!("\n /// [{name}]: {link}")) - .collect(); + let l: String = + links.iter().map(|(name, link)| format!("\n /// [{name}]: {link}")).collect(); format!("\n ///{l}") } @@ -173,13 +164,7 @@ fn render_doc(doc: &Doc, sibling: Option<&str>) -> String { }) .unwrap_or_default(); - [ - " /// ", - &doc.md.replace('\n', "\n /// "), - &sibling_note, - &links, - ] - .concat() + [" /// ", &doc.md.replace('\n', "\n /// "), &sibling_note, &links].concat() } fn eq_hash_suitable(method: &Method) -> bool { @@ -208,10 +193,7 @@ fn eq_hash_suitable(method: &Method) -> bool { } fn default_needed(method: &Method) -> bool { - method - .params - .iter() - .all(|p| matches!(p.ty, Type::Option(_))) + method.params.iter().all(|p| matches!(p.ty, Type::Option(_))) } fn params(params: impl Iterator>) -> String { @@ -258,12 +240,8 @@ fn params(params: impl Iterator>) -> String { } fn multipart_input_file_fields(m: &Method) -> Option> { - let fields: Vec<_> = m - .params - .iter() - .filter(|&p| ty_is_multiparty(&p.ty)) - .map(|p| &*p.name) - .collect(); + let fields: Vec<_> = + m.params.iter().filter(|&p| ty_is_multiparty(&p.ty)).map(|p| &*p.name).collect(); if fields.is_empty() { None diff --git a/crates/teloxide-core/src/requests/multipart_payload.rs b/crates/teloxide-core/src/requests/multipart_payload.rs index f55ee74c..1b5b9242 100644 --- a/crates/teloxide-core/src/requests/multipart_payload.rs +++ b/crates/teloxide-core/src/requests/multipart_payload.rs @@ -14,17 +14,11 @@ pub trait MultipartPayload: Payload { impl MultipartPayload for payloads::SendMediaGroup { fn copy_files(&self, into: &mut dyn FnMut(InputFile)) { - self.media - .iter() - .flat_map(InputMedia::files) - .for_each(|f| f.copy_into(into)) + self.media.iter().flat_map(InputMedia::files).for_each(|f| f.copy_into(into)) } fn move_files(&mut self, into: &mut dyn FnMut(InputFile)) { - self.media - .iter_mut() - .flat_map(InputMedia::files_mut) - .for_each(|f| f.move_into(into)) + self.media.iter_mut().flat_map(InputMedia::files_mut).for_each(|f| f.move_into(into)) } } diff --git a/crates/teloxide-core/src/requests/requester.rs b/crates/teloxide-core/src/requests/requester.rs index 1529c39c..3fc819bb 100644 --- a/crates/teloxide-core/src/requests/requester.rs +++ b/crates/teloxide-core/src/requests/requester.rs @@ -72,9 +72,7 @@ use crate::{ /// bot.send_message(chat_id, "Text").await?; /// /// // This will use `ParseMode::MarkdownV2` -/// bot.send_message(chat_id, "**Text**") -/// .parse_mode(ParseMode::MarkdownV2) -/// .await?; +/// bot.send_message(chat_id, "**Text**").parse_mode(ParseMode::MarkdownV2).await?; /// # Ok::<_, teloxide_core::RequestError>(()) /// # }; /// ``` @@ -1284,11 +1282,9 @@ fn codegen_requester_methods() { .filter(|p| !matches!(p.ty, Type::Option(_))) .flat_map(|p| match convert_for(&p.ty) { Convert::Id(_) => None, - Convert::Into(ty) => Some(format!( - "{}: Into<{}>", - &to_uppercase(prefixes[&*p.name]), - ty - )), + Convert::Into(ty) => { + Some(format!("{}: Into<{}>", &to_uppercase(prefixes[&*p.name]), ty)) + } Convert::Collect(ty) => Some(format!( "{}: IntoIterator", &to_uppercase(prefixes[&*p.name]), @@ -1297,11 +1293,8 @@ fn codegen_requester_methods() { }) .join(",\n "); - let generics = if generics.is_empty() { - String::from("") - } else { - format!("<{}>", generics) - }; + let generics = + if generics.is_empty() { String::from("") } else { format!("<{}>", generics) }; let where_clause = if where_clause.is_empty() { String::from("") diff --git a/crates/teloxide-core/src/serde_multipart/mod.rs b/crates/teloxide-core/src/serde_multipart/mod.rs index 51b24fd8..ffa7ad09 100644 --- a/crates/teloxide-core/src/serde_multipart/mod.rs +++ b/crates/teloxide-core/src/serde_multipart/mod.rs @@ -99,11 +99,7 @@ mod tests { async fn issue_473() { to_form_ref( &payloads::SendPhoto::new(ChatId(0), InputFile::file_id("0")).caption_entities([ - MessageEntity { - kind: MessageEntityKind::Url, - offset: 0, - length: 0, - }, + MessageEntity { kind: MessageEntityKind::Url, offset: 0, length: 0 }, ]), ) .unwrap() @@ -131,9 +127,7 @@ mod tests { File::open("../../media/example.gif").await.unwrap(), )) .thumb(InputFile::read( - File::open("../../media/teloxide-core-logo.png") - .await - .unwrap(), + File::open("../../media/teloxide-core-logo.png").await.unwrap(), )) .duration(17), ), @@ -170,11 +164,7 @@ mod tests { InputFile::file("../../media/teloxide-core-logo.png"), ) .caption_entities(entities()) - .thumb(InputFile::read( - File::open("../../media/teloxide-core-logo.png") - .await - .unwrap(), - )) + .thumb(InputFile::read(File::open("../../media/teloxide-core-logo.png").await.unwrap())) .allow_sending_without_reply(true), ) .unwrap() @@ -185,18 +175,10 @@ mod tests { <_>::into_iter([ MessageEntity::new(MessageEntityKind::Url, 0, 0), MessageEntity::new(MessageEntityKind::Pre { language: None }, 0, 0), - MessageEntity::new( - MessageEntityKind::Pre { - language: Some(String::new()), - }, - 0, - 0, - ), + MessageEntity::new(MessageEntityKind::Pre { language: Some(String::new()) }, 0, 0), MessageEntity::new(MessageEntityKind::Url, 0, 0), MessageEntity::new( - MessageEntityKind::TextLink { - url: "https://example.com".parse().unwrap(), - }, + MessageEntityKind::TextLink { url: "https://example.com".parse().unwrap() }, 0, 0, ), diff --git a/crates/teloxide-core/src/serde_multipart/serializers.rs b/crates/teloxide-core/src/serde_multipart/serializers.rs index cf3a4b98..0d0f33be 100644 --- a/crates/teloxide-core/src/serde_multipart/serializers.rs +++ b/crates/teloxide-core/src/serde_multipart/serializers.rs @@ -62,10 +62,7 @@ impl Serializer for MultipartSerializer { type SerializeStructVariant = Impossible; fn serialize_map(self, _: Option) -> Result { - Ok(MultipartMapSerializer { - form: Form::new(), - key: None, - }) + Ok(MultipartMapSerializer { form: Form::new(), key: None }) } fn serialize_struct( @@ -266,10 +263,7 @@ impl SerializeMap for MultipartMapSerializer { where T: Serialize, { - let key = self - .key - .take() - .expect("Value serialized before key or key is not string"); + let key = self.key.take().expect("Value serialized before key or key is not string"); let part = value.serialize(PartSerializer {})?; @@ -373,17 +367,11 @@ impl Serializer for PartSerializer { _: &'static str, _: usize, ) -> Result { - Ok(JsonPartSerializer { - buf: String::new(), - state: PartSerializerStructState::Empty, - }) + Ok(JsonPartSerializer { buf: String::new(), state: PartSerializerStructState::Empty }) } fn serialize_seq(self, _: Option) -> Result { - Ok(JsonPartSerializer { - buf: String::new(), - state: PartSerializerStructState::Empty, - }) + Ok(JsonPartSerializer { buf: String::new(), state: PartSerializerStructState::Empty }) } // Unimplemented diff --git a/crates/teloxide-core/src/types.rs b/crates/teloxide-core/src/types.rs index 2ff4585a..117830b3 100644 --- a/crates/teloxide-core/src/types.rs +++ b/crates/teloxide-core/src/types.rs @@ -303,10 +303,7 @@ pub(crate) mod serde_date_from_unix_timestamp { { let timestamp = i64::deserialize(deserializer)?; - Ok(DateTime::from_utc( - NaiveDateTime::from_timestamp(timestamp, 0), - Utc, - )) + Ok(DateTime::from_utc(NaiveDateTime::from_timestamp(timestamp, 0), Utc)) } } @@ -348,10 +345,7 @@ pub(crate) mod option_url_from_string { let json = r#"{"url":"https://github.com/token"}"#; let url: Struct = serde_json::from_str(json).unwrap(); - assert_eq!( - url.url, - Some(Url::from_str("https://github.com/token").unwrap()) - ); + assert_eq!(url.url, Some(Url::from_str("https://github.com/token").unwrap())); assert_eq!(serde_json::to_string(&url).unwrap(), json.to_owned()); } } diff --git a/crates/teloxide-core/src/types/animation.rs b/crates/teloxide-core/src/types/animation.rs index 22aa8a46..b583cce9 100644 --- a/crates/teloxide-core/src/types/animation.rs +++ b/crates/teloxide-core/src/types/animation.rs @@ -59,20 +59,12 @@ mod tests { "mime_type":"video/gif", "file_size":6500}"#; let expected = Animation { - file: FileMeta { - id: "id".to_string(), - unique_id: "".to_string(), - size: 6500, - }, + file: FileMeta { id: "id".to_string(), unique_id: "".to_string(), size: 6500 }, width: 320, height: 320, duration: 59, thumb: Some(PhotoSize { - file: FileMeta { - id: "id".to_owned(), - unique_id: "".to_owned(), - size: 3452, - }, + file: FileMeta { id: "id".to_owned(), unique_id: "".to_owned(), size: 3452 }, width: 320, height: 320, }), diff --git a/crates/teloxide-core/src/types/audio.rs b/crates/teloxide-core/src/types/audio.rs index ee7d7468..87b0505e 100644 --- a/crates/teloxide-core/src/types/audio.rs +++ b/crates/teloxide-core/src/types/audio.rs @@ -59,21 +59,13 @@ mod tests { } }"#; let expected = Audio { - file: FileMeta { - id: "id".to_string(), - unique_id: "".to_string(), - size: 123_456, - }, + file: FileMeta { id: "id".to_string(), unique_id: "".to_string(), size: 123_456 }, duration: 60, performer: Some("Performer".to_string()), title: Some("Title".to_string()), mime_type: Some("application/zip".parse().unwrap()), thumb: Some(PhotoSize { - file: FileMeta { - id: "id".to_owned(), - unique_id: "".to_owned(), - size: 3452, - }, + file: FileMeta { id: "id".to_owned(), unique_id: "".to_owned(), size: 3452 }, width: 320, height: 320, }), diff --git a/crates/teloxide-core/src/types/bot_command.rs b/crates/teloxide-core/src/types/bot_command.rs index 5ea4f1c2..cb6d9c6e 100644 --- a/crates/teloxide-core/src/types/bot_command.rs +++ b/crates/teloxide-core/src/types/bot_command.rs @@ -20,10 +20,7 @@ impl BotCommand { S1: Into, S2: Into, { - Self { - command: command.into(), - description: description.into(), - } + Self { command: command.into(), description: description.into() } } pub fn command(mut self, val: S) -> Self diff --git a/crates/teloxide-core/src/types/bot_command_scope.rs b/crates/teloxide-core/src/types/bot_command_scope.rs index e005aabb..011ccd1b 100644 --- a/crates/teloxide-core/src/types/bot_command_scope.rs +++ b/crates/teloxide-core/src/types/bot_command_scope.rs @@ -58,10 +58,7 @@ pub enum BotCommandScope { fn issue_486() { use crate::types::ChatId; - serde_json::to_string(&BotCommandScope::Chat { - chat_id: Recipient::Id(ChatId(0)), - }) - .unwrap(); + serde_json::to_string(&BotCommandScope::Chat { chat_id: Recipient::Id(ChatId(0)) }).unwrap(); serde_json::to_string(&BotCommandScope::ChatAdministrators { chat_id: Recipient::Id(ChatId(0)), diff --git a/crates/teloxide-core/src/types/chat.rs b/crates/teloxide-core/src/types/chat.rs index 6500dfcb..96d470ae 100644 --- a/crates/teloxide-core/src/types/chat.rs +++ b/crates/teloxide-core/src/types/chat.rs @@ -205,35 +205,20 @@ impl Chat { #[must_use] pub fn is_group(&self) -> bool { - matches!( - self.kind, - ChatKind::Public(ChatPublic { - kind: PublicChatKind::Group(_), - .. - }) - ) + matches!(self.kind, ChatKind::Public(ChatPublic { kind: PublicChatKind::Group(_), .. })) } #[must_use] pub fn is_supergroup(&self) -> bool { matches!( self.kind, - ChatKind::Public(ChatPublic { - kind: PublicChatKind::Supergroup(_), - .. - }) + ChatKind::Public(ChatPublic { kind: PublicChatKind::Supergroup(_), .. }) ) } #[must_use] pub fn is_channel(&self) -> bool { - matches!( - self.kind, - ChatKind::Public(ChatPublic { - kind: PublicChatKind::Channel(_), - .. - }) - ) + matches!(self.kind, ChatKind::Public(ChatPublic { kind: PublicChatKind::Channel(_), .. })) } #[must_use] diff --git a/crates/teloxide-core/src/types/chat_id.rs b/crates/teloxide-core/src/types/chat_id.rs index a7a53224..21adf49b 100644 --- a/crates/teloxide-core/src/types/chat_id.rs +++ b/crates/teloxide-core/src/types/chat_id.rs @@ -104,9 +104,7 @@ mod tests { /// Test that `ChatId` is serialized as the underlying integer #[test] fn deser() { - let chat_id = S { - chat_id: ChatId(0xAA), - }; + let chat_id = S { chat_id: ChatId(0xAA) }; let json = r#"{"chat_id":170}"#; #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] @@ -120,10 +118,7 @@ mod tests { #[test] fn chonky_user_id_to_bare() { - assert!(matches!( - ChatId(5298363099).to_bare(), - BareChatId::User(UserId(5298363099)) - )); + assert!(matches!(ChatId(5298363099).to_bare(), BareChatId::User(UserId(5298363099)))); } #[test] @@ -137,19 +132,8 @@ mod tests { } // Somewhat random numbers - let ids = [ - 1, - 4, - 17, - 34, - 51, - 777000, - 1000000, - 617136926, - 1666111087, - 1 << 20, - (1 << 35) | 123456, - ]; + let ids = + [1, 4, 17, 34, 51, 777000, 1000000, 617136926, 1666111087, 1 << 20, (1 << 35) | 123456]; // rust 2021 when :( ids.iter().copied().for_each(assert_identity); diff --git a/crates/teloxide-core/src/types/chat_member.rs b/crates/teloxide-core/src/types/chat_member.rs index affed635..79c2e79f 100644 --- a/crates/teloxide-core/src/types/chat_member.rs +++ b/crates/teloxide-core/src/types/chat_member.rs @@ -324,9 +324,7 @@ impl ChatMemberKind { pub fn can_manage_chat(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_manage_chat, .. - }) => *can_manage_chat, + Self::Administrator(Administrator { can_manage_chat, .. }) => *can_manage_chat, Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => true, } } @@ -345,9 +343,7 @@ impl ChatMemberKind { pub fn can_change_info(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_change_info, .. - }) => *can_change_info, + Self::Administrator(Administrator { can_change_info, .. }) => *can_change_info, Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -365,9 +361,9 @@ impl ChatMemberKind { pub fn can_post_messages(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_post_messages, .. - }) => can_post_messages.unwrap_or_default(), + Self::Administrator(Administrator { can_post_messages, .. }) => { + can_post_messages.unwrap_or_default() + } Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -386,9 +382,9 @@ impl ChatMemberKind { pub fn can_edit_messages(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_edit_messages, .. - }) => can_edit_messages.unwrap_or_default(), + Self::Administrator(Administrator { can_edit_messages, .. }) => { + can_edit_messages.unwrap_or_default() + } Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -406,10 +402,7 @@ impl ChatMemberKind { pub fn can_delete_messages(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_delete_messages, - .. - }) => *can_delete_messages, + Self::Administrator(Administrator { can_delete_messages, .. }) => *can_delete_messages, Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -427,10 +420,9 @@ impl ChatMemberKind { pub fn can_manage_video_chats(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_manage_video_chats, - .. - }) => *can_manage_video_chats, + Self::Administrator(Administrator { can_manage_video_chats, .. }) => { + *can_manage_video_chats + } Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -454,9 +446,7 @@ impl ChatMemberKind { pub fn can_invite_users(&self) -> bool { match &self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_invite_users, .. - }) => *can_invite_users, + Self::Administrator(Administrator { can_invite_users, .. }) => *can_invite_users, Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -474,10 +464,9 @@ impl ChatMemberKind { pub fn can_restrict_members(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_restrict_members, - .. - }) => *can_restrict_members, + Self::Administrator(Administrator { can_restrict_members, .. }) => { + *can_restrict_members + } Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -495,9 +484,9 @@ impl ChatMemberKind { pub fn can_pin_messages(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_pin_messages, .. - }) => can_pin_messages.unwrap_or_default(), + Self::Administrator(Administrator { can_pin_messages, .. }) => { + can_pin_messages.unwrap_or_default() + } Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -518,10 +507,7 @@ impl ChatMemberKind { pub fn can_promote_members(&self) -> bool { match self { Self::Owner(_) => true, - Self::Administrator(Administrator { - can_promote_members, - .. - }) => *can_promote_members, + Self::Administrator(Administrator { can_promote_members, .. }) => *can_promote_members, Self::Member | Self::Restricted(_) | Self::Left | Self::Banned(_) => false, } } @@ -541,9 +527,7 @@ impl ChatMemberKind { #[must_use] pub fn can_send_messages(&self) -> bool { match &self { - Self::Restricted(Restricted { - can_send_messages, .. - }) => *can_send_messages, + Self::Restricted(Restricted { can_send_messages, .. }) => *can_send_messages, Self::Owner(_) | Self::Administrator(_) | Self::Member => true, Self::Left | Self::Banned(_) => false, } @@ -561,10 +545,9 @@ impl ChatMemberKind { #[must_use] pub fn can_send_media_messages(&self) -> bool { match &self { - Self::Restricted(Restricted { - can_send_media_messages, - .. - }) => *can_send_media_messages, + Self::Restricted(Restricted { can_send_media_messages, .. }) => { + *can_send_media_messages + } Self::Owner(_) | Self::Administrator(_) | Self::Member => true, Self::Left | Self::Banned(_) => false, } @@ -582,10 +565,9 @@ impl ChatMemberKind { #[must_use] pub fn can_send_other_messages(&self) -> bool { match &self { - Self::Restricted(Restricted { - can_send_other_messages, - .. - }) => *can_send_other_messages, + Self::Restricted(Restricted { can_send_other_messages, .. }) => { + *can_send_other_messages + } Self::Owner(_) | Self::Administrator(_) | Self::Member => true, Self::Left | Self::Banned(_) => false, } @@ -603,10 +585,9 @@ impl ChatMemberKind { #[must_use] pub fn can_add_web_page_previews(&self) -> bool { match &self { - Self::Restricted(Restricted { - can_add_web_page_previews, - .. - }) => *can_add_web_page_previews, + Self::Restricted(Restricted { can_add_web_page_previews, .. }) => { + *can_add_web_page_previews + } Self::Owner(_) | Self::Administrator(_) | Self::Member => true, Self::Left | Self::Banned(_) => false, } diff --git a/crates/teloxide-core/src/types/file.rs b/crates/teloxide-core/src/types/file.rs index 89ae95f7..f26963df 100644 --- a/crates/teloxide-core/src/types/file.rs +++ b/crates/teloxide-core/src/types/file.rs @@ -114,11 +114,7 @@ mod tests { assert_eq!( file, - FileMeta { - id: "FILE_ID".to_owned(), - unique_id: "FILE_UNIQUE_ID".to_owned(), - size: 42, - } + FileMeta { id: "FILE_ID".to_owned(), unique_id: "FILE_UNIQUE_ID".to_owned(), size: 42 } ); } diff --git a/crates/teloxide-core/src/types/force_reply.rs b/crates/teloxide-core/src/types/force_reply.rs index 471a55a6..f92d8d1c 100644 --- a/crates/teloxide-core/src/types/force_reply.rs +++ b/crates/teloxide-core/src/types/force_reply.rs @@ -35,11 +35,7 @@ pub struct ForceReply { impl ForceReply { #[must_use] pub const fn new() -> Self { - Self { - force_reply: True, - input_field_placeholder: None, - selective: None, - } + Self { force_reply: True, input_field_placeholder: None, selective: None } } pub fn input_field_placeholder(mut self, val: T) -> Self diff --git a/crates/teloxide-core/src/types/inline_keyboard_button.rs b/crates/teloxide-core/src/types/inline_keyboard_button.rs index 651f8931..4c7d0e95 100644 --- a/crates/teloxide-core/src/types/inline_keyboard_button.rs +++ b/crates/teloxide-core/src/types/inline_keyboard_button.rs @@ -96,10 +96,7 @@ impl InlineKeyboardButton { where S: Into, { - Self { - text: text.into(), - kind, - } + Self { text: text.into(), kind } } /// Constructor for `InlineKeyboardButton` with [`Url`] kind. @@ -130,10 +127,7 @@ impl InlineKeyboardButton { T: Into, C: Into, { - Self::new( - text, - InlineKeyboardButtonKind::CallbackData(callback_data.into()), - ) + Self::new(text, InlineKeyboardButtonKind::CallbackData(callback_data.into())) } /// Constructor for `InlineKeyboardButton` with [`WebApp`] kind. @@ -154,10 +148,7 @@ impl InlineKeyboardButton { T: Into, Q: Into, { - Self::new( - text, - InlineKeyboardButtonKind::SwitchInlineQuery(switch_inline_query.into()), - ) + Self::new(text, InlineKeyboardButtonKind::SwitchInlineQuery(switch_inline_query.into())) } /// Constructor for `InlineKeyboardButton` with diff --git a/crates/teloxide-core/src/types/inline_keyboard_markup.rs b/crates/teloxide-core/src/types/inline_keyboard_markup.rs index f0c61fd1..8b7747d3 100644 --- a/crates/teloxide-core/src/types/inline_keyboard_markup.rs +++ b/crates/teloxide-core/src/types/inline_keyboard_markup.rs @@ -50,11 +50,7 @@ impl InlineKeyboardMarkup { I: IntoIterator, I::Item: IntoIterator, { - self.inline_keyboard = val - .into_iter() - .map(<_>::into_iter) - .map(<_>::collect) - .collect(); + self.inline_keyboard = val.into_iter().map(<_>::into_iter).map(<_>::collect).collect(); self } @@ -92,9 +88,7 @@ mod tests { let markup = InlineKeyboardMarkup::default().append_row(vec![button1.clone(), button2.clone()]); - let expected = InlineKeyboardMarkup { - inline_keyboard: vec![vec![button1, button2]], - }; + let expected = InlineKeyboardMarkup { inline_keyboard: vec![vec![button1, button2]] }; assert_eq!(markup, expected); } @@ -108,9 +102,7 @@ mod tests { .append_row(vec![button1.clone()]) .append_to_row(0, button2.clone()); - let expected = InlineKeyboardMarkup { - inline_keyboard: vec![vec![button1, button2]], - }; + let expected = InlineKeyboardMarkup { inline_keyboard: vec![vec![button1, button2]] }; assert_eq!(markup, expected); } @@ -124,9 +116,7 @@ mod tests { .append_row(vec![button1.clone()]) .append_to_row(1, button2.clone()); - let expected = InlineKeyboardMarkup { - inline_keyboard: vec![vec![button1], vec![button2]], - }; + let expected = InlineKeyboardMarkup { inline_keyboard: vec![vec![button1], vec![button2]] }; assert_eq!(markup, expected); } diff --git a/crates/teloxide-core/src/types/inline_query_result_game.rs b/crates/teloxide-core/src/types/inline_query_result_game.rs index 68d01a2e..87eece14 100644 --- a/crates/teloxide-core/src/types/inline_query_result_game.rs +++ b/crates/teloxide-core/src/types/inline_query_result_game.rs @@ -28,11 +28,7 @@ impl InlineQueryResultGame { S1: Into, S2: Into, { - Self { - id: id.into(), - game_short_name: game_short_name.into(), - reply_markup: None, - } + Self { id: id.into(), game_short_name: game_short_name.into(), reply_markup: None } } pub fn id(mut self, val: S) -> Self diff --git a/crates/teloxide-core/src/types/input_file.rs b/crates/teloxide-core/src/types/input_file.rs index f0131db5..631cac82 100644 --- a/crates/teloxide-core/src/types/input_file.rs +++ b/crates/teloxide-core/src/types/input_file.rs @@ -116,11 +116,7 @@ impl InputFile { /// Shorthand for `Self { file_name: None, inner, id: default() }` /// (private because `InnerFile` iы private implementation detail) fn new(inner: InnerFile) -> Self { - Self { - file_name: None, - inner, - id: OnceCell::new(), - } + Self { file_name: None, inner, id: OnceCell::new() } } /// Returns id of this file. @@ -128,8 +124,7 @@ impl InputFile { /// This is used to coordinate with `attach://`. pub(crate) fn id(&self) -> &str { // FIXME: remove extra alloc - self.id - .get_or_init(|| uuid::Uuid::new_v4().to_string().into()) + self.id.get_or_init(|| uuid::Uuid::new_v4().to_string().into()) } /// Returns `true` if this file needs an attachment i.e. it's not a file_id @@ -255,12 +250,7 @@ impl Read { fn new(it: Arc>) -> Self { let (tx, rx) = watch::channel(()); - Self { - inner: it, - buf: Arc::default(), - notify: Arc::new(tx), - wait: rx, - } + Self { inner: it, buf: Arc::default(), notify: Arc::new(tx), wait: rx } } pub(crate) async fn into_part(mut self, filename: Cow<'static, str>) -> Part { diff --git a/crates/teloxide-core/src/types/input_media.rs b/crates/teloxide-core/src/types/input_media.rs index fd4ec1d8..f9953db7 100644 --- a/crates/teloxide-core/src/types/input_media.rs +++ b/crates/teloxide-core/src/types/input_media.rs @@ -45,12 +45,7 @@ pub struct InputMediaPhoto { impl InputMediaPhoto { pub const fn new(media: InputFile) -> Self { - Self { - media, - caption: None, - parse_mode: None, - caption_entities: None, - } + Self { media, caption: None, parse_mode: None, caption_entities: None } } pub fn media(mut self, val: InputFile) -> Self { diff --git a/crates/teloxide-core/src/types/keyboard_button.rs b/crates/teloxide-core/src/types/keyboard_button.rs index ab450cfe..c6c3390d 100644 --- a/crates/teloxide-core/src/types/keyboard_button.rs +++ b/crates/teloxide-core/src/types/keyboard_button.rs @@ -28,10 +28,7 @@ impl KeyboardButton { where T: Into, { - Self { - text: text.into(), - request: None, - } + Self { text: text.into(), request: None } } pub fn request(mut self, val: T) -> Self @@ -111,13 +108,8 @@ impl<'de> Deserialize<'de> for ButtonRequest { { let raw = RawRequest::deserialize(deserializer)?; match raw { - RawRequest { - contact, - location, - poll, - web_app, - } if 1 - < (contact.is_some() as u8 + RawRequest { contact, location, poll, web_app } + if 1 < (contact.is_some() as u8 + location.is_some() as u8 + poll.is_some() as u8 + web_app.is_some() as u8) => @@ -127,20 +119,10 @@ impl<'de> Deserialize<'de> for ButtonRequest { are mutually exclusive", )) } - RawRequest { - contact: Some(_), .. - } => Ok(Self::Contact), - RawRequest { - location: Some(_), .. - } => Ok(Self::Location), - RawRequest { - poll: Some(poll_type), - .. - } => Ok(Self::Poll(poll_type)), - RawRequest { - web_app: Some(web_app), - .. - } => Ok(Self::WebApp(web_app)), + RawRequest { contact: Some(_), .. } => Ok(Self::Contact), + RawRequest { location: Some(_), .. } => Ok(Self::Location), + RawRequest { poll: Some(poll_type), .. } => Ok(Self::Poll(poll_type)), + RawRequest { web_app: Some(web_app), .. } => Ok(Self::WebApp(web_app)), _ => Err(D::Error::custom( "Either one of `request_contact`, `request_location`, `request_poll` and \ @@ -155,12 +137,7 @@ impl Serialize for ButtonRequest { where S: Serializer, { - let mut raw = RawRequest { - contact: None, - location: None, - poll: None, - web_app: None, - }; + let mut raw = RawRequest { contact: None, location: None, poll: None, web_app: None }; match self { Self::Contact => raw.contact = Some(True), @@ -179,10 +156,7 @@ mod tests { #[test] fn serialize_no_request() { - let button = KeyboardButton { - text: String::from(""), - request: None, - }; + let button = KeyboardButton { text: String::from(""), request: None }; let expected = r#"{"text":""}"#; let actual = serde_json::to_string(&button).unwrap(); assert_eq!(expected, actual); @@ -190,10 +164,8 @@ mod tests { #[test] fn serialize_request_contact() { - let button = KeyboardButton { - text: String::from(""), - request: Some(ButtonRequest::Contact), - }; + let button = + KeyboardButton { text: String::from(""), request: Some(ButtonRequest::Contact) }; let expected = r#"{"text":"","request_contact":true}"#; let actual = serde_json::to_string(&button).unwrap(); assert_eq!(expected, actual); @@ -202,10 +174,7 @@ mod tests { #[test] fn deserialize_no_request() { let json = r#"{"text":""}"#; - let expected = KeyboardButton { - text: String::from(""), - request: None, - }; + let expected = KeyboardButton { text: String::from(""), request: None }; let actual = serde_json::from_str(json).unwrap(); assert_eq!(expected, actual); } @@ -213,10 +182,8 @@ mod tests { #[test] fn deserialize_request_contact() { let json = r#"{"text":"","request_contact":true}"#; - let expected = KeyboardButton { - text: String::from(""), - request: Some(ButtonRequest::Contact), - }; + let expected = + KeyboardButton { text: String::from(""), request: Some(ButtonRequest::Contact) }; let actual = serde_json::from_str(json).unwrap(); assert_eq!(expected, actual); } diff --git a/crates/teloxide-core/src/types/label_price.rs b/crates/teloxide-core/src/types/label_price.rs index 33cdd3f4..28cf9b30 100644 --- a/crates/teloxide-core/src/types/label_price.rs +++ b/crates/teloxide-core/src/types/label_price.rs @@ -24,10 +24,7 @@ impl LabeledPrice { where S: Into, { - Self { - label: label.into(), - amount, - } + Self { label: label.into(), amount } } pub fn label(mut self, val: S) -> Self @@ -51,10 +48,7 @@ mod tests { #[test] fn serialize() { - let labeled_price = LabeledPrice { - label: "Label".to_string(), - amount: 60, - }; + let labeled_price = LabeledPrice { label: "Label".to_string(), amount: 60 }; let expected = r#"{"label":"Label","amount":60}"#; let actual = serde_json::to_string(&labeled_price).unwrap(); assert_eq!(actual, expected); diff --git a/crates/teloxide-core/src/types/mask_position.rs b/crates/teloxide-core/src/types/mask_position.rs index 4f42c675..147654e1 100644 --- a/crates/teloxide-core/src/types/mask_position.rs +++ b/crates/teloxide-core/src/types/mask_position.rs @@ -36,12 +36,7 @@ pub enum MaskPoint { impl MaskPosition { pub const fn new(point: MaskPoint, x_shift: f64, y_shift: f64, scale: f64) -> Self { - Self { - point, - x_shift, - y_shift, - scale, - } + Self { point, x_shift, y_shift, scale } } pub const fn point(mut self, val: MaskPoint) -> Self { diff --git a/crates/teloxide-core/src/types/me.rs b/crates/teloxide-core/src/types/me.rs index b9cf3fe8..bea15ca3 100644 --- a/crates/teloxide-core/src/types/me.rs +++ b/crates/teloxide-core/src/types/me.rs @@ -28,10 +28,7 @@ impl Me { /// Returns the username of the bot. #[must_use] pub fn username(&self) -> &str { - self.user - .username - .as_deref() - .expect("Bots must have usernames") + self.user.username.as_deref().expect("Bots must have usernames") } /// Returns a username mention of this bot. @@ -79,9 +76,6 @@ mod tests { assert_eq!(me.username(), "SomethingSomethingBot"); assert_eq!(me.mention(), "@SomethingSomethingBot"); - assert_eq!( - me.tme_url(), - "https://t.me/SomethingSomethingBot".parse().unwrap() - ); + assert_eq!(me.tme_url(), "https://t.me/SomethingSomethingBot".parse().unwrap()); } } diff --git a/crates/teloxide-core/src/types/message.rs b/crates/teloxide-core/src/types/message.rs index 6edc9451..d0ff1510 100644 --- a/crates/teloxide-core/src/types/message.rs +++ b/crates/teloxide-core/src/types/message.rs @@ -555,9 +555,7 @@ mod getters { #[must_use] pub fn author_signature(&self) -> Option<&str> { match &self.kind { - Common(MessageCommon { - author_signature, .. - }) => author_signature.as_deref(), + Common(MessageCommon { author_signature, .. }) => author_signature.as_deref(), _ => None, } } @@ -711,45 +709,27 @@ mod getters { pub fn caption_entities(&self) -> Option<&[MessageEntity]> { match &self.kind { Common(MessageCommon { - media_kind: - MediaKind::Animation(MediaAnimation { - caption_entities, .. - }), + media_kind: MediaKind::Animation(MediaAnimation { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Audio(MediaAudio { - caption_entities, .. - }), + media_kind: MediaKind::Audio(MediaAudio { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Document(MediaDocument { - caption_entities, .. - }), + media_kind: MediaKind::Document(MediaDocument { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Photo(MediaPhoto { - caption_entities, .. - }), + media_kind: MediaKind::Photo(MediaPhoto { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Video(MediaVideo { - caption_entities, .. - }), + media_kind: MediaKind::Video(MediaVideo { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Voice(MediaVoice { - caption_entities, .. - }), + media_kind: MediaKind::Voice(MediaVoice { caption_entities, .. }), .. }) => Some(caption_entities), _ => None, @@ -978,9 +958,9 @@ mod getters { #[must_use] pub fn super_group_chat_created(&self) -> Option { match &self.kind { - SupergroupChatCreated(MessageSupergroupChatCreated { - supergroup_chat_created, - }) => Some(*supergroup_chat_created), + SupergroupChatCreated(MessageSupergroupChatCreated { supergroup_chat_created }) => { + Some(*supergroup_chat_created) + } _ => None, } } @@ -988,9 +968,9 @@ mod getters { #[must_use] pub fn channel_chat_created(&self) -> Option { match &self.kind { - ChannelChatCreated(MessageChannelChatCreated { - channel_chat_created, - }) => Some(*channel_chat_created), + ChannelChatCreated(MessageChannelChatCreated { channel_chat_created }) => { + Some(*channel_chat_created) + } _ => None, } } @@ -999,8 +979,7 @@ mod getters { pub fn chat_migration(&self) -> Option { match &self.kind { Common(MessageCommon { - media_kind: MediaKind::Migration(chat_migration), - .. + media_kind: MediaKind::Migration(chat_migration), .. }) => Some(*chat_migration), _ => None, } @@ -1101,10 +1080,7 @@ mod getters { #[must_use] pub fn is_automatic_forward(&self) -> bool { match &self.kind { - Common(MessageCommon { - is_automatic_forward, - .. - }) => *is_automatic_forward, + Common(MessageCommon { is_automatic_forward, .. }) => *is_automatic_forward, _ => false, } } @@ -1112,10 +1088,7 @@ mod getters { #[must_use] pub fn has_protected_content(&self) -> bool { match &self.kind { - Common(MessageCommon { - has_protected_content, - .. - }) => *has_protected_content, + Common(MessageCommon { has_protected_content, .. }) => *has_protected_content, _ => false, } } @@ -1250,12 +1223,7 @@ impl Message { /// supergroups). #[must_use] pub fn url_in_thread(&self, thread_starter_msg_id: MessageId) -> Option { - Self::url_in_thread_of( - self.chat.id, - self.chat.username(), - thread_starter_msg_id, - self.id, - ) + Self::url_in_thread_of(self.chat.id, self.chat.username(), thread_starter_msg_id, self.id) } /// Produces a direct link to a message in a given thread. @@ -1300,9 +1268,7 @@ impl Message { /// [`parse_caption_entities`]: Message::parse_caption_entities #[must_use] pub fn parse_entities(&self) -> Option>> { - self.text() - .zip(self.entities()) - .map(|(t, e)| MessageEntityRef::parse(t, e)) + self.text().zip(self.entities()).map(|(t, e)| MessageEntityRef::parse(t, e)) } /// Returns message entities that represent text formatting. @@ -1315,9 +1281,7 @@ impl Message { /// [`parse_entities`]: Message::parse_entities #[must_use] pub fn parse_caption_entities(&self) -> Option>> { - self.caption() - .zip(self.caption_entities()) - .map(|(t, e)| MessageEntityRef::parse(t, e)) + self.caption().zip(self.caption_entities()).map(|(t, e)| MessageEntityRef::parse(t, e)) } } @@ -1610,10 +1574,7 @@ mod tests { let message: Message = from_str(json).unwrap(); assert_eq!(message.chat.id, old); - assert_eq!( - message.chat_migration(), - Some(ChatMigration::To { chat_id: new }) - ); + assert_eq!(message.chat_migration(), Some(ChatMigration::To { chat_id: new })); assert_eq!(message.migrate_to_chat_id(), Some(new)); // The user who initialized the migration @@ -1624,10 +1585,7 @@ mod tests { let message: Message = from_str(json).unwrap(); assert_eq!(message.chat.id, new); - assert_eq!( - message.chat_migration(), - Some(ChatMigration::From { chat_id: old }) - ); + assert_eq!(message.chat_migration(), Some(ChatMigration::From { chat_id: old })); assert_eq!(message.migrate_from_chat_id(), Some(old)); // Anonymous bot diff --git a/crates/teloxide-core/src/types/message_entity.rs b/crates/teloxide-core/src/types/message_entity.rs index f417d442..98f90615 100644 --- a/crates/teloxide-core/src/types/message_entity.rs +++ b/crates/teloxide-core/src/types/message_entity.rs @@ -45,91 +45,55 @@ pub struct MessageEntityRef<'a> { impl MessageEntity { #[must_use] pub const fn new(kind: MessageEntityKind, offset: usize, length: usize) -> Self { - Self { - kind, - offset, - length, - } + Self { kind, offset, length } } /// Create a message entity representing a bold text. #[must_use] pub const fn bold(offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::Bold, - offset, - length, - } + Self { kind: MessageEntityKind::Bold, offset, length } } /// Create a message entity representing an italic text. #[must_use] pub const fn italic(offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::Italic, - offset, - length, - } + Self { kind: MessageEntityKind::Italic, offset, length } } /// Create a message entity representing an underline text. #[must_use] pub const fn underline(offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::Underline, - offset, - length, - } + Self { kind: MessageEntityKind::Underline, offset, length } } /// Create a message entity representing a strikethrough text. #[must_use] pub const fn strikethrough(offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::Strikethrough, - offset, - length, - } + Self { kind: MessageEntityKind::Strikethrough, offset, length } } /// Create a message entity representing a spoiler text. #[must_use] pub const fn spoiler(offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::Spoiler, - offset, - length, - } + Self { kind: MessageEntityKind::Spoiler, offset, length } } /// Create a message entity representing a monowidth text. #[must_use] pub const fn code(offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::Code, - offset, - length, - } + Self { kind: MessageEntityKind::Code, offset, length } } /// Create a message entity representing a monowidth block. #[must_use] pub const fn pre(language: Option, offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::Pre { language }, - offset, - length, - } + Self { kind: MessageEntityKind::Pre { language }, offset, length } } /// Create a message entity representing a clickable text URL. #[must_use] pub const fn text_link(url: reqwest::Url, offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::TextLink { url }, - offset, - length, - } + Self { kind: MessageEntityKind::TextLink { url }, offset, length } } /// Create a message entity representing a text mention. @@ -140,32 +104,20 @@ impl MessageEntity { /// [`MessageEntity::text_mention_id`] instead. #[must_use] pub const fn text_mention(user: User, offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::TextMention { user }, - offset, - length, - } + Self { kind: MessageEntityKind::TextMention { user }, offset, length } } /// Create a message entity representing a text link in the form of /// `tg://user/?id=...` that mentions user with `user_id`. #[must_use] pub fn text_mention_id(user_id: UserId, offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::TextLink { url: user_id.url() }, - offset, - length, - } + Self { kind: MessageEntityKind::TextLink { url: user_id.url() }, offset, length } } /// Create a message entity representing a custom emoji. #[must_use] pub const fn custom_emoji(custom_emoji_id: String, offset: usize, length: usize) -> Self { - Self { - kind: MessageEntityKind::CustomEmoji { custom_emoji_id }, - offset, - length, - } + Self { kind: MessageEntityKind::CustomEmoji { custom_emoji_id }, offset, length } } #[must_use] @@ -242,11 +194,7 @@ impl<'a> MessageEntityRef<'a> { // This creates entities with **wrong** offsets (UTF-16) that we later patch. let mut entities: Vec<_> = entities .iter() - .map(|e| Self { - message: text, - range: e.offset..e.offset + e.length, - kind: &e.kind, - }) + .map(|e| Self { message: text, range: e.offset..e.offset + e.length, kind: &e.kind }) .collect(); // Convert offsets @@ -254,12 +202,7 @@ impl<'a> MessageEntityRef<'a> { // References to all offsets that need patching let mut offsets: Vec<&mut usize> = entities .iter_mut() - .flat_map( - |Self { - range: Range { start, end }, - .. - }| [start, end], - ) + .flat_map(|Self { range: Range { start, end }, .. }| [start, end]) .collect(); // Sort in decreasing order, so the smallest elements are at the end and can be @@ -276,11 +219,7 @@ impl<'a> MessageEntityRef<'a> { } // Patch all offsets that can be patched - while offsets - .last() - .map(|&&mut offset| offset <= len_utf16) - .unwrap_or(false) - { + while offsets.last().map(|&&mut offset| offset <= len_utf16).unwrap_or(false) { let offset = offsets.pop().unwrap(); assert_eq!(*offset, len_utf16, "Invalid utf-16 offset"); @@ -352,9 +291,7 @@ mod tests { assert_eq!( MessageEntity { - kind: MessageEntityKind::Pre { - language: Some("rust".to_string()) - }, + kind: MessageEntityKind::Pre { language: Some("rust".to_string()) }, offset: 1, length: 2, }, @@ -385,26 +322,10 @@ mod tests { let parsed = MessageEntityRef::parse( "быба", &[ - MessageEntity { - kind: Strikethrough, - offset: 0, - length: 1, - }, - MessageEntity { - kind: Bold, - offset: 1, - length: 1, - }, - MessageEntity { - kind: Italic, - offset: 2, - length: 1, - }, - MessageEntity { - kind: Code, - offset: 3, - length: 1, - }, + MessageEntity { kind: Strikethrough, offset: 0, length: 1 }, + MessageEntity { kind: Bold, offset: 1, length: 1 }, + MessageEntity { kind: Italic, offset: 2, length: 1 }, + MessageEntity { kind: Code, offset: 3, length: 1 }, ], ); @@ -424,11 +345,7 @@ mod tests { fn parse_symbol_24bit() { let parsed = MessageEntityRef::parse( "xx আ #tt", - &[MessageEntity { - kind: Hashtag, - offset: 5, - length: 3, - }], + &[MessageEntity { kind: Hashtag, offset: 5, length: 3 }], ); assert_matches!( @@ -443,21 +360,9 @@ mod tests { "b i b", // For some reason this is how telegram encodes b i b &[ - MessageEntity { - kind: Bold, - offset: 0, - length: 2, - }, - MessageEntity { - kind: Bold, - offset: 2, - length: 3, - }, - MessageEntity { - kind: Italic, - offset: 2, - length: 1, - }, + MessageEntity { kind: Bold, offset: 0, length: 2 }, + MessageEntity { kind: Bold, offset: 2, length: 3 }, + MessageEntity { kind: Italic, offset: 2, length: 1 }, ], ); @@ -484,16 +389,8 @@ mod tests { let parsed = MessageEntityRef::parse( "", &[ - MessageEntity { - kind: Bold, - offset: 0, - length: 0, - }, - MessageEntity { - kind: Italic, - offset: 0, - length: 0, - }, + MessageEntity { kind: Bold, offset: 0, length: 0 }, + MessageEntity { kind: Italic, offset: 0, length: 0 }, ], ); diff --git a/crates/teloxide-core/src/types/passport_element_error.rs b/crates/teloxide-core/src/types/passport_element_error.rs index 3021bc69..6769bcf2 100644 --- a/crates/teloxide-core/src/types/passport_element_error.rs +++ b/crates/teloxide-core/src/types/passport_element_error.rs @@ -18,10 +18,7 @@ impl PassportElementError { where S: Into, { - Self { - message: message.into(), - kind, - } + Self { message: message.into(), kind } } pub fn message(mut self, val: S) -> Self @@ -98,11 +95,7 @@ impl PassportElementErrorDataField { S1: Into, S2: Into, { - Self { - r#type, - field_name: field_name.into(), - data_hash: data_hash.into(), - } + Self { r#type, field_name: field_name.into(), data_hash: data_hash.into() } } #[must_use] @@ -149,10 +142,7 @@ impl PassportElementErrorFrontSide { where S: Into, { - Self { - r#type, - file_hash: file_hash.into(), - } + Self { r#type, file_hash: file_hash.into() } } #[must_use] @@ -191,10 +181,7 @@ impl PassportElementErrorReverseSide { where S: Into, { - Self { - r#type, - file_hash: file_hash.into(), - } + Self { r#type, file_hash: file_hash.into() } } #[must_use] @@ -231,10 +218,7 @@ impl PassportElementErrorSelfie { where S: Into, { - Self { - r#type, - file_hash: file_hash.into(), - } + Self { r#type, file_hash: file_hash.into() } } #[must_use] @@ -272,10 +256,7 @@ impl PassportElementErrorFile { where S: Into, { - Self { - r#type, - file_hash: file_hash.into(), - } + Self { r#type, file_hash: file_hash.into() } } #[must_use] @@ -313,10 +294,7 @@ impl PassportElementErrorFiles { where S: IntoIterator, { - Self { - r#type, - file_hashes: file_hashes.into_iter().collect(), - } + Self { r#type, file_hashes: file_hashes.into_iter().collect() } } #[must_use] @@ -355,10 +333,7 @@ impl PassportElementErrorTranslationFile { where S: Into, { - Self { - r#type, - file_hash: file_hash.into(), - } + Self { r#type, file_hash: file_hash.into() } } #[must_use] @@ -396,10 +371,7 @@ impl PassportElementErrorTranslationFiles { where S: IntoIterator, { - Self { - r#type, - file_hashes: file_hashes.into_iter().collect(), - } + Self { r#type, file_hashes: file_hashes.into_iter().collect() } } #[must_use] @@ -437,10 +409,7 @@ impl PassportElementErrorUnspecified { where S: Into, { - Self { - r#type, - element_hash: file_hash.into(), - } + Self { r#type, element_hash: file_hash.into() } } #[must_use] diff --git a/crates/teloxide-core/src/types/photo_size.rs b/crates/teloxide-core/src/types/photo_size.rs index 9b0af706..f75955a2 100644 --- a/crates/teloxide-core/src/types/photo_size.rs +++ b/crates/teloxide-core/src/types/photo_size.rs @@ -29,11 +29,7 @@ mod tests { let json = r#"{"file_id":"id","file_unique_id":"","width":320,"height":320, "file_size":3452}"#; let expected = PhotoSize { - file: FileMeta { - id: "id".to_owned(), - unique_id: "".to_owned(), - size: 3452, - }, + file: FileMeta { id: "id".to_owned(), unique_id: "".to_owned(), size: 3452 }, width: 320, height: 320, }; diff --git a/crates/teloxide-core/src/types/reply_keyboard_markup.rs b/crates/teloxide-core/src/types/reply_keyboard_markup.rs index 8a80cb7b..649d9ee2 100644 --- a/crates/teloxide-core/src/types/reply_keyboard_markup.rs +++ b/crates/teloxide-core/src/types/reply_keyboard_markup.rs @@ -55,11 +55,7 @@ impl KeyboardMarkup { K::Item: IntoIterator, { Self { - keyboard: keyboard - .into_iter() - .map(<_>::into_iter) - .map(<_>::collect) - .collect(), + keyboard: keyboard.into_iter().map(<_>::into_iter).map(<_>::collect).collect(), resize_keyboard: None, one_time_keyboard: None, input_field_placeholder: None, diff --git a/crates/teloxide-core/src/types/reply_keyboard_remove.rs b/crates/teloxide-core/src/types/reply_keyboard_remove.rs index 4f2e85e1..0f48434b 100644 --- a/crates/teloxide-core/src/types/reply_keyboard_remove.rs +++ b/crates/teloxide-core/src/types/reply_keyboard_remove.rs @@ -40,10 +40,7 @@ pub struct KeyboardRemove { impl KeyboardRemove { #[must_use] pub const fn new() -> Self { - Self { - remove_keyboard: True, - selective: None, - } + Self { remove_keyboard: True, selective: None } } #[must_use] diff --git a/crates/teloxide-core/src/types/shipping_option.rs b/crates/teloxide-core/src/types/shipping_option.rs index ec6e8a3e..d1b4fe6e 100644 --- a/crates/teloxide-core/src/types/shipping_option.rs +++ b/crates/teloxide-core/src/types/shipping_option.rs @@ -24,11 +24,7 @@ impl ShippingOption { S2: Into, P: IntoIterator, { - Self { - id: id.into(), - title: title.into(), - prices: prices.into_iter().collect(), - } + Self { id: id.into(), title: title.into(), prices: prices.into_iter().collect() } } pub fn id(mut self, val: S) -> Self @@ -65,10 +61,7 @@ mod tests { let shipping_option = ShippingOption { id: "0".to_string(), title: "Option".to_string(), - prices: vec![LabeledPrice { - label: "Label".to_string(), - amount: 60, - }], + prices: vec![LabeledPrice { label: "Label".to_string(), amount: 60 }], }; let expected = r#"{"id":"0","title":"Option","prices":[{"label":"Label","amount":60}]}"#; let actual = serde_json::to_string(&shipping_option).unwrap(); diff --git a/crates/teloxide-core/src/types/sticker.rs b/crates/teloxide-core/src/types/sticker.rs index dd5c651e..0424b7ae 100644 --- a/crates/teloxide-core/src/types/sticker.rs +++ b/crates/teloxide-core/src/types/sticker.rs @@ -289,10 +289,7 @@ impl TryFrom for StickerFormat { type Error = &'static str; fn try_from( - StickerFormatRaw { - is_animated, - is_video, - }: StickerFormatRaw, + StickerFormatRaw { is_animated, is_video }: StickerFormatRaw, ) -> Result { let ret = match (is_animated, is_video) { (false, false) => Self::Raster, @@ -308,18 +305,9 @@ impl TryFrom for StickerFormat { impl From for StickerFormatRaw { fn from(kind: StickerFormat) -> Self { match kind { - StickerFormat::Raster => Self { - is_animated: false, - is_video: false, - }, - StickerFormat::Animated => Self { - is_animated: true, - is_video: false, - }, - StickerFormat::Video => Self { - is_animated: false, - is_video: true, - }, + StickerFormat::Raster => Self { is_animated: false, is_video: false }, + StickerFormat::Animated => Self { is_animated: true, is_video: false }, + StickerFormat::Video => Self { is_animated: false, is_video: true }, } } } diff --git a/crates/teloxide-core/src/types/update.rs b/crates/teloxide-core/src/types/update.rs index 0fb34e6e..1cd90467 100644 --- a/crates/teloxide-core/src/types/update.rs +++ b/crates/teloxide-core/src/types/update.rs @@ -161,10 +161,9 @@ impl<'de> Deserialize<'de> for UpdateKind { if let Ok(Some(k)) = k { let res = match k { - "message" => map - .next_value::() - .map(UpdateKind::Message) - .map_err(|_| false), + "message" => { + map.next_value::().map(UpdateKind::Message).map_err(|_| false) + } "edited_message" => map .next_value::() .map(UpdateKind::EditedMessage) @@ -197,10 +196,7 @@ impl<'de> Deserialize<'de> for UpdateKind { .next_value::() .map(UpdateKind::PreCheckoutQuery) .map_err(|_| false), - "poll" => map - .next_value::() - .map(UpdateKind::Poll) - .map_err(|_| false), + "poll" => map.next_value::().map(UpdateKind::Poll).map_err(|_| false), "poll_answer" => map .next_value::() .map(UpdateKind::PollAnswer) diff --git a/crates/teloxide-core/src/types/user.rs b/crates/teloxide-core/src/types/user.rs index 07c14052..1dc0b672 100644 --- a/crates/teloxide-core/src/types/user.rs +++ b/crates/teloxide-core/src/types/user.rs @@ -66,11 +66,7 @@ impl User { /// Returns `None` if `self.username.is_none()`. #[must_use] pub fn tme_url(&self) -> Option { - Some( - format!("https://t.me/{}", self.username.as_ref()?) - .parse() - .unwrap(), - ) + Some(format!("https://t.me/{}", self.username.as_ref()?).parse().unwrap()) } /// Returns an URL that links to this user in the form of `t.me/<...>` or @@ -190,19 +186,10 @@ mod tests { assert_eq!(user_a.mention(), Some("@aaaaaaaaaaaaaaaa".to_owned())); assert_eq!(user_b.mention(), None); - assert_eq!( - user_a.tme_url(), - Some("https://t.me/aaaaaaaaaaaaaaaa".parse().unwrap()) - ); + assert_eq!(user_a.tme_url(), Some("https://t.me/aaaaaaaaaaaaaaaa".parse().unwrap())); assert_eq!(user_b.tme_url(), None); - assert_eq!( - user_a.preferably_tme_url(), - "https://t.me/aaaaaaaaaaaaaaaa".parse().unwrap() - ); - assert_eq!( - user_b.preferably_tme_url(), - "tg://user/?id=44".parse().unwrap() - ); + assert_eq!(user_a.preferably_tme_url(), "https://t.me/aaaaaaaaaaaaaaaa".parse().unwrap()); + assert_eq!(user_b.preferably_tme_url(), "tg://user/?id=44".parse().unwrap()); } } diff --git a/crates/teloxide-core/src/types/user_id.rs b/crates/teloxide-core/src/types/user_id.rs index a767234c..71d41984 100644 --- a/crates/teloxide-core/src/types/user_id.rs +++ b/crates/teloxide-core/src/types/user_id.rs @@ -61,9 +61,7 @@ mod tests { /// Test that `UserId` is serialized as the underlying integer #[test] fn deser() { - let user_id = S { - user_id: UserId(17), - }; + let user_id = S { user_id: UserId(17) }; let json = r#"{"user_id":17}"#; #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] diff --git a/crates/teloxide-macros/rustfmt.toml b/crates/teloxide-macros/rustfmt.toml deleted file mode 100644 index aba42ed2..00000000 --- a/crates/teloxide-macros/rustfmt.toml +++ /dev/null @@ -1,7 +0,0 @@ -format_code_in_doc_comments = true -wrap_comments = true -format_strings = true -max_width = 80 -imports_granularity = "Crate" -use_small_heuristics = "Max" -use_field_init_shorthand = true diff --git a/crates/teloxide-macros/src/attr.rs b/crates/teloxide-macros/src/attr.rs index 04a070ed..9f872946 100644 --- a/crates/teloxide-macros/src/attr.rs +++ b/crates/teloxide-macros/src/attr.rs @@ -19,13 +19,12 @@ pub(crate) fn fold_attrs( .filter(|&a| filter(a)) .flat_map(|attribute| { // FIXME: don't allocate here - let attrs = - match attribute.parse_args_with(|input: &ParseBuffer| { - input.parse_terminated::<_, Token![,]>(Attr::parse) - }) { - Ok(ok) => ok, - Err(err) => return vec![Err(err.into())], - }; + let attrs = match attribute.parse_args_with(|input: &ParseBuffer| { + input.parse_terminated::<_, Token![,]>(Attr::parse) + }) { + Ok(ok) => ok, + Err(err) => return vec![Err(err.into())], + }; attrs.into_iter().map(&parse).collect() }) @@ -75,10 +74,7 @@ impl Parse for Attr { impl Attr { pub(crate) fn span(&self) -> Span { - self.key - .span() - .join(self.value.span()) - .unwrap_or_else(|| self.key.span()) + self.key.span().join(self.value.span()).unwrap_or_else(|| self.key.span()) } } @@ -99,16 +95,9 @@ impl AttrValue { // }) // } - pub fn expect( - self, - expected: &str, - f: impl FnOnce(Self) -> Result, - ) -> Result { + pub fn expect(self, expected: &str, f: impl FnOnce(Self) -> Result) -> Result { f(self).map_err(|this| { - compile_error_at( - &format!("expected {expected}, found {}", this.descr()), - this.span(), - ) + compile_error_at(&format!("expected {expected}, found {}", this.descr()), this.span()) }) } diff --git a/crates/teloxide-macros/src/bot_commands.rs b/crates/teloxide-macros/src/bot_commands.rs index 7d7337e6..b257d668 100644 --- a/crates/teloxide-macros/src/bot_commands.rs +++ b/crates/teloxide-macros/src/bot_commands.rs @@ -1,6 +1,6 @@ use crate::{ - command::Command, command_enum::CommandEnum, compile_error, - fields_parse::impl_parse_args, unzip::Unzip, Result, + command::Command, command_enum::CommandEnum, compile_error, fields_parse::impl_parse_args, + unzip::Unzip, Result, }; use proc_macro2::TokenStream; @@ -15,17 +15,12 @@ pub(crate) fn bot_commands_impl(input: DeriveInput) -> Result { .variants .iter() .map(|variant| { - let command = Command::new( - &variant.ident.to_string(), - &variant.attrs, - &command_enum, - )?; + let command = Command::new(&variant.ident.to_string(), &variant.attrs, &command_enum)?; let variant_name = &variant.ident; let self_variant = quote! { Self::#variant_name }; - let parse = - impl_parse_args(&variant.fields, self_variant, &command.parser); + let parse = impl_parse_args(&variant.fields, self_variant, &command.parser); Ok((parse, command)) }) @@ -48,14 +43,11 @@ pub(crate) fn bot_commands_impl(input: DeriveInput) -> Result { } fn impl_commands(infos: &[Command]) -> proc_macro2::TokenStream { - let commands = infos - .iter() - .filter(|command| command.description_is_enabled()) - .map(|command| { - let c = command.get_prefixed_command(); - let d = command.description.as_deref().unwrap_or_default(); - quote! { BotCommand::new(#c,#d) } - }); + let commands = infos.iter().filter(|command| command.description_is_enabled()).map(|command| { + let c = command.get_prefixed_command(); + let d = command.description.as_deref().unwrap_or_default(); + quote! { BotCommand::new(#c,#d) } + }); quote! { fn bot_commands() -> Vec { @@ -65,10 +57,7 @@ fn impl_commands(infos: &[Command]) -> proc_macro2::TokenStream { } } -fn impl_descriptions( - infos: &[Command], - global: &CommandEnum, -) -> proc_macro2::TokenStream { +fn impl_descriptions(infos: &[Command], global: &CommandEnum) -> proc_macro2::TokenStream { let command_descriptions = infos .iter() .filter(|command| command.description_is_enabled()) diff --git a/crates/teloxide-macros/src/command.rs b/crates/teloxide-macros/src/command.rs index 72b05f3e..fb421e8f 100644 --- a/crates/teloxide-macros/src/command.rs +++ b/crates/teloxide-macros/src/command.rs @@ -1,6 +1,6 @@ use crate::{ - command_attr::CommandAttrs, command_enum::CommandEnum, - error::compile_error_at, fields_parse::ParserType, Result, + command_attr::CommandAttrs, command_enum::CommandEnum, error::compile_error_at, + fields_parse::ParserType, Result, }; pub(crate) struct Command { @@ -43,13 +43,9 @@ impl Command { (None, None) => global_options.rename_rule.apply(name), }; - let prefix = prefix - .map(|(p, _)| p) - .unwrap_or_else(|| global_options.prefix.clone()); + let prefix = prefix.map(|(p, _)| p).unwrap_or_else(|| global_options.prefix.clone()); let description = description.map(|(d, _)| d); - let parser = parser - .map(|(p, _)| p) - .unwrap_or_else(|| global_options.parser_type.clone()); + let parser = parser.map(|(p, _)| p).unwrap_or_else(|| global_options.parser_type.clone()); Ok(Self { prefix, description, parser, name }) } diff --git a/crates/teloxide-macros/src/command_attr.rs b/crates/teloxide-macros/src/command_attr.rs index e735b7bb..96c9c2b7 100644 --- a/crates/teloxide-macros/src/command_attr.rs +++ b/crates/teloxide-macros/src/command_attr.rs @@ -60,19 +60,13 @@ impl CommandAttrs { separator: None, }, |mut this, attr| { - fn insert( - opt: &mut Option<(T, Span)>, - x: T, - sp: Span, - ) -> Result<()> { + fn insert(opt: &mut Option<(T, Span)>, x: T, sp: Span) -> Result<()> { match opt { slot @ None => { *slot = Some((x, sp)); Ok(()) } - Some(_) => { - Err(compile_error_at("duplicate attribute", sp)) - } + Some(_) => Err(compile_error_at("duplicate attribute", sp)), } } @@ -100,18 +94,16 @@ impl CommandAttr { let kind = match &*key.to_string() { "prefix" => Prefix(value.expect_string()?), "description" => Description(value.expect_string()?), - "rename_rule" => RenameRule( - value - .expect_string() - .and_then(|r| self::RenameRule::parse(&r))?, - ), + "rename_rule" => { + RenameRule(value.expect_string().and_then(|r| self::RenameRule::parse(&r))?) + } "rename" => Rename(value.expect_string()?), "parse_with" => ParseWith(ParserType::parse(value)?), "separator" => Separator(value.expect_string()?), _ => { return Err(compile_error_at( - "unexpected attribute name (expected one of `prefix`, \ - `description`, `rename`, `parse_with` and `separator`", + "unexpected attribute name (expected one of `prefix`, `description`, \ + `rename`, `parse_with` and `separator`", key.span(), )) } diff --git a/crates/teloxide-macros/src/command_enum.rs b/crates/teloxide-macros/src/command_enum.rs index 55f37610..83f20dec 100644 --- a/crates/teloxide-macros/src/command_enum.rs +++ b/crates/teloxide-macros/src/command_enum.rs @@ -1,6 +1,6 @@ use crate::{ - command_attr::CommandAttrs, error::compile_error_at, - fields_parse::ParserType, rename_rules::RenameRule, Result, + command_attr::CommandAttrs, error::compile_error_at, fields_parse::ParserType, + rename_rules::RenameRule, Result, }; pub(crate) struct CommandEnum { @@ -13,14 +13,7 @@ pub(crate) struct CommandEnum { impl CommandEnum { pub fn from_attributes(attributes: &[syn::Attribute]) -> Result { let attrs = CommandAttrs::from_attributes(attributes)?; - let CommandAttrs { - prefix, - description, - rename_rule, - rename, - parser, - separator, - } = attrs; + let CommandAttrs { prefix, description, rename_rule, rename, parser, separator } = attrs; if let Some((_rename, sp)) = rename { return Err(compile_error_at( @@ -32,18 +25,14 @@ impl CommandEnum { let mut parser = parser.map(|(p, _)| p).unwrap_or(ParserType::Default); // FIXME: Error on unused separator - if let (ParserType::Split { separator }, Some((s, _))) = - (&mut parser, &separator) - { + if let (ParserType::Split { separator }, Some((s, _))) = (&mut parser, &separator) { *separator = Some(s.clone()) } Ok(Self { prefix: prefix.map(|(p, _)| p).unwrap_or_else(|| "/".to_owned()), description: description.map(|(d, _)| d), - rename_rule: rename_rule - .map(|(rr, _)| rr) - .unwrap_or(RenameRule::Identity), + rename_rule: rename_rule.map(|(rr, _)| rr).unwrap_or(RenameRule::Identity), parser_type: parser, }) } diff --git a/crates/teloxide-macros/src/error.rs b/crates/teloxide-macros/src/error.rs index 0d27c475..59088db2 100644 --- a/crates/teloxide-macros/src/error.rs +++ b/crates/teloxide-macros/src/error.rs @@ -14,9 +14,7 @@ where } pub(crate) fn compile_error_at(msg: &str, sp: Span) -> Error { - use proc_macro2::{ - Delimiter, Group, Ident, Literal, Punct, Spacing, TokenTree, - }; + use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, TokenTree}; // compile_error! { $msg } let ts = TokenStream::from_iter(vec![ TokenTree::Ident(Ident::new("compile_error", sp)), diff --git a/crates/teloxide-macros/src/fields_parse.rs b/crates/teloxide-macros/src/fields_parse.rs index caf53127..ba7204d7 100644 --- a/crates/teloxide-macros/src/fields_parse.rs +++ b/crates/teloxide-macros/src/fields_parse.rs @@ -12,18 +12,15 @@ pub(crate) enum ParserType { impl ParserType { pub fn parse(value: AttrValue) -> Result { - value.expect( - r#""default", "split", or a path to a custom parser function"#, - |v| match v { - AttrValue::Path(p) => Ok(ParserType::Custom(p)), - AttrValue::Lit(syn::Lit::Str(ref l)) => match &*l.value() { - "default" => Ok(ParserType::Default), - "split" => Ok(ParserType::Split { separator: None }), - _ => Err(v), - }, + value.expect(r#""default", "split", or a path to a custom parser function"#, |v| match v { + AttrValue::Path(p) => Ok(ParserType::Custom(p)), + AttrValue::Lit(syn::Lit::Str(ref l)) => match &*l.value() { + "default" => Ok(ParserType::Default), + "split" => Ok(ParserType::Split { separator: None }), _ => Err(v), }, - ) + _ => Err(v), + }) } } @@ -34,12 +31,8 @@ pub(crate) fn impl_parse_args( ) -> proc_macro2::TokenStream { match fields { Fields::Unit => self_variant, - Fields::Unnamed(fields) => { - impl_parse_args_unnamed(fields, self_variant, parser) - } - Fields::Named(named) => { - impl_parse_args_named(named, self_variant, parser) - } + Fields::Unnamed(fields) => impl_parse_args_unnamed(fields, self_variant, parser), + Fields::Named(named) => impl_parse_args_named(named, self_variant, parser), } } @@ -48,8 +41,7 @@ pub(crate) fn impl_parse_args_unnamed( variant: proc_macro2::TokenStream, parser_type: &ParserType, ) -> proc_macro2::TokenStream { - let get_arguments = - create_parser(parser_type, data.unnamed.iter().map(|f| &f.ty)); + let get_arguments = create_parser(parser_type, data.unnamed.iter().map(|f| &f.ty)); let iter = (0..data.unnamed.len()).map(syn::Index::from); let mut initialization = quote! {}; for i in iter { @@ -69,8 +61,7 @@ pub(crate) fn impl_parse_args_named( variant: proc_macro2::TokenStream, parser_type: &ParserType, ) -> proc_macro2::TokenStream { - let get_arguments = - create_parser(parser_type, data.named.iter().map(|f| &f.ty)); + let get_arguments = create_parser(parser_type, data.named.iter().map(|f| &f.ty)); let i = (0..).map(syn::Index::from); let name = data.named.iter().map(|f| f.ident.as_ref().unwrap()); let res = quote! { @@ -105,10 +96,9 @@ fn create_parser<'a>( quote! { compile_error!("Default parser works only with exactly 1 field") } } }, - ParserType::Split { separator } => parser_with_separator( - &separator.clone().unwrap_or_else(|| " ".to_owned()), - types, - ), + ParserType::Split { separator } => { + parser_with_separator(&separator.clone().unwrap_or_else(|| " ".to_owned()), types) + } ParserType::Custom(path) => quote! { #path }, }; diff --git a/crates/teloxide-macros/src/rename_rules.rs b/crates/teloxide-macros/src/rename_rules.rs index 55280617..b4fab615 100644 --- a/crates/teloxide-macros/src/rename_rules.rs +++ b/crates/teloxide-macros/src/rename_rules.rs @@ -3,8 +3,7 @@ use crate::error::{compile_error, Result}; use heck::{ - ToKebabCase, ToLowerCamelCase, ToPascalCase, ToShoutyKebabCase, - ToShoutySnakeCase, ToSnakeCase, + ToKebabCase, ToLowerCamelCase, ToPascalCase, ToShoutyKebabCase, ToShoutySnakeCase, ToSnakeCase, }; #[derive(Copy, Clone, Debug)] @@ -65,10 +64,9 @@ impl RenameRule { "identity" => Identity, invalid => { return Err(compile_error(format!( - "invalid rename rule `{invalid}` (supported rules: \ - `lowercase`, `UPPERCASE`, `PascalCase`, `camelCase`, \ - `snake_case`, `SCREAMING_SNAKE_CASE`, `kebab-case`, \ - `SCREAMING-KEBAB-CASE` and `identity`)" + "invalid rename rule `{invalid}` (supported rules: `lowercase`, `UPPERCASE`, \ + `PascalCase`, `camelCase`, `snake_case`, `SCREAMING_SNAKE_CASE`, \ + `kebab-case`, `SCREAMING-KEBAB-CASE` and `identity`)" ))) } }; diff --git a/crates/teloxide-macros/tests/command.rs b/crates/teloxide-macros/tests/command.rs index 65aea651..b627aa65 100644 --- a/crates/teloxide-macros/tests/command.rs +++ b/crates/teloxide-macros/tests/command.rs @@ -62,42 +62,23 @@ fn many_attributes() { Help, } - assert_eq!( - DefaultCommands::Start, - DefaultCommands::parse("!start", "").unwrap() - ); - assert_eq!( - DefaultCommands::descriptions().to_string(), - "!start — desc\n/help" - ); + assert_eq!(DefaultCommands::Start, DefaultCommands::parse("!start", "").unwrap()); + assert_eq!(DefaultCommands::descriptions().to_string(), "!start — desc\n/help"); } #[test] fn global_attributes() { #[derive(BotCommands, Debug, PartialEq)] - #[command( - prefix = "!", - rename_rule = "lowercase", - description = "Bot commands" - )] + #[command(prefix = "!", rename_rule = "lowercase", description = "Bot commands")] enum DefaultCommands { #[command(prefix = "/")] Start, Help, } - assert_eq!( - DefaultCommands::Start, - DefaultCommands::parse("/start", "MyNameBot").unwrap() - ); - assert_eq!( - DefaultCommands::Help, - DefaultCommands::parse("!help", "MyNameBot").unwrap() - ); - assert_eq!( - DefaultCommands::descriptions().to_string(), - "Bot commands\n\n/start\n!help" - ); + assert_eq!(DefaultCommands::Start, DefaultCommands::parse("/start", "MyNameBot").unwrap()); + assert_eq!(DefaultCommands::Help, DefaultCommands::parse("!help", "MyNameBot").unwrap()); + assert_eq!(DefaultCommands::descriptions().to_string(), "Bot commands\n\n/start\n!help"); } #[test] @@ -153,25 +134,15 @@ fn parse_custom_parser() { mod parser { use teloxide::utils::command::ParseError; - pub fn custom_parse_function( - s: String, - ) -> Result<(u8, String), ParseError> { + pub fn custom_parse_function(s: String) -> Result<(u8, String), ParseError> { let vec = s.split_whitespace().collect::>(); let (left, right) = match vec.as_slice() { [l, r] => (l, r), - _ => { - return Err(ParseError::IncorrectFormat( - "might be 2 arguments!".into(), - )) - } + _ => return Err(ParseError::IncorrectFormat("might be 2 arguments!".into())), }; - left.parse::().map(|res| (res, (*right).to_string())).map_err( - |_| { - ParseError::Custom( - "First argument must be a integer!".to_owned().into(), - ) - }, - ) + left.parse::().map(|res| (res, (*right).to_string())).map_err(|_| { + ParseError::Custom("First argument must be a integer!".to_owned().into()) + }) } } @@ -253,46 +224,18 @@ fn rename_rules() { Foo, } - assert_eq!( - DefaultCommands::AaaAaa, - DefaultCommands::parse("/aaaaaa", "").unwrap() - ); - assert_eq!( - DefaultCommands::BbbBbb, - DefaultCommands::parse("/BBBBBB", "").unwrap() - ); - assert_eq!( - DefaultCommands::CccCcc, - DefaultCommands::parse("/CccCcc", "").unwrap() - ); - assert_eq!( - DefaultCommands::DddDdd, - DefaultCommands::parse("/dddDdd", "").unwrap() - ); - assert_eq!( - DefaultCommands::EeeEee, - DefaultCommands::parse("/eee_eee", "").unwrap() - ); - assert_eq!( - DefaultCommands::FffFff, - DefaultCommands::parse("/FFF_FFF", "").unwrap() - ); - assert_eq!( - DefaultCommands::GggGgg, - DefaultCommands::parse("/ggg-ggg", "").unwrap() - ); - assert_eq!( - DefaultCommands::HhhHhh, - DefaultCommands::parse("/HHH-HHH", "").unwrap() - ); - assert_eq!( - DefaultCommands::Foo, - DefaultCommands::parse("/Bar", "").unwrap() - ); + assert_eq!(DefaultCommands::AaaAaa, DefaultCommands::parse("/aaaaaa", "").unwrap()); + assert_eq!(DefaultCommands::BbbBbb, DefaultCommands::parse("/BBBBBB", "").unwrap()); + assert_eq!(DefaultCommands::CccCcc, DefaultCommands::parse("/CccCcc", "").unwrap()); + assert_eq!(DefaultCommands::DddDdd, DefaultCommands::parse("/dddDdd", "").unwrap()); + assert_eq!(DefaultCommands::EeeEee, DefaultCommands::parse("/eee_eee", "").unwrap()); + assert_eq!(DefaultCommands::FffFff, DefaultCommands::parse("/FFF_FFF", "").unwrap()); + assert_eq!(DefaultCommands::GggGgg, DefaultCommands::parse("/ggg-ggg", "").unwrap()); + assert_eq!(DefaultCommands::HhhHhh, DefaultCommands::parse("/HHH-HHH", "").unwrap()); + assert_eq!(DefaultCommands::Foo, DefaultCommands::parse("/Bar", "").unwrap()); assert_eq!( - "/aaaaaa\n/BBBBBB\n/CccCcc\n/dddDdd\n/eee_eee\n/FFF_FFF\n/ggg-ggg\n/\ - HHH-HHH\n/Bar", + "/aaaaaa\n/BBBBBB\n/CccCcc\n/dddDdd\n/eee_eee\n/FFF_FFF\n/ggg-ggg\n/HHH-HHH\n/Bar", DefaultCommands::descriptions().to_string() ); } diff --git a/rustfmt.toml b/rustfmt.toml index 38db4219..6353e228 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -4,3 +4,4 @@ format_strings = true imports_granularity = "Crate" use_small_heuristics = "Max" use_field_init_shorthand = true +merge_derives = false