Apply automatic clippy

This commit is contained in:
Natsu Kagami 2024-08-04 22:40:46 +02:00
parent 054a7d5862
commit b9f6fa7fb8
Signed by: nki
GPG key ID: 55A032EB38B49ADB
14 changed files with 49 additions and 43 deletions

View file

@ -192,7 +192,7 @@ pub async fn ranks(ctx: &Context, m: &Message) -> CommandResult {
} }
let ranks = &ranks[start..end]; let ranks = &ranks[start..end];
const HEADERS: [&'static str; 4] = ["Rank", "Rating", "Handle", "Username"]; const HEADERS: [&str; 4] = ["Rank", "Rating", "Handle", "Username"];
const ALIGNS: [Align; 4] = [Right, Right, Left, Left]; const ALIGNS: [Align; 4] = [Right, Right, Left, Left];
let ranks_arr = ranks let ranks_arr = ranks
@ -354,11 +354,11 @@ pub(crate) async fn contest_rank_table(
if result.points > 0.0 { if result.points > 0.0 {
p_results.push(format!("{}", result.points)); p_results.push(format!("{}", result.points));
} else if result.best_submission_time_seconds.is_some() { } else if result.best_submission_time_seconds.is_some() {
p_results.push(format!("{}", "?")); p_results.push("?".to_string());
} else if result.rejected_attempt_count > 0 { } else if result.rejected_attempt_count > 0 {
p_results.push(format!("-{}", result.rejected_attempt_count)); p_results.push(format!("-{}", result.rejected_attempt_count));
} else { } else {
p_results.push(format!("{}", "----")); p_results.push("----".to_string());
} }
} }

View file

@ -56,7 +56,7 @@ async fn list(ctx: &Context, m: &Message, _: Args) -> CommandResult {
let roles = &roles[start..end]; let roles = &roles[start..end];
const ROLE_HEADERS: [&'static str; 3] = ["Name", "ID", "Description"]; const ROLE_HEADERS: [&str; 3] = ["Name", "ID", "Description"];
const ROLE_ALIGNS: [Align; 3] = [Right, Right, Right]; const ROLE_ALIGNS: [Align; 3] = [Right, Right, Right];
let roles_arr = roles let roles_arr = roles

View file

@ -203,7 +203,7 @@ impl Announcer {
let (user, top_scores) = try_join!(user, top_scores)?; let (user, top_scores) = try_join!(user, top_scores)?;
let mut user = user.unwrap(); let mut user = user.unwrap();
// if top scores exist, user would too // if top scores exist, user would too
let events = std::mem::replace(&mut user.events, vec![]) let events = std::mem::take(&mut user.events)
.into_iter() .into_iter()
.filter_map(|v| v.to_event_rank()) .filter_map(|v| v.to_event_rank())
.filter(|s| Self::is_announceable_date(s.date, last_update, now)) .filter(|s| Self::is_announceable_date(s.date, last_update, now))
@ -344,7 +344,7 @@ impl<'a> CollectedScore<'a> {
) )
.await?; .await?;
save_beatmap(&env, channel, bm).await.pls_ok(); save_beatmap(env, channel, bm).await.pls_ok();
Ok(m) Ok(m)
} }
} }

View file

@ -298,7 +298,7 @@ mod scores {
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
const SCORE_HEADERS: [&'static str; 6] = const SCORE_HEADERS: [&str; 6] =
["#", "PP", "Acc", "Ranks", "Mods", "Beatmap"]; ["#", "PP", "Acc", "Ranks", "Mods", "Beatmap"];
const SCORE_ALIGNS: [Align; 6] = [Right, Right, Right, Right, Right, Left]; const SCORE_ALIGNS: [Align; 6] = [Right, Right, Right, Right, Right, Left];
@ -310,7 +310,7 @@ mod scores {
.map(|(id, ((play, beatmap), (rank, pp)))| { .map(|(id, ((play, beatmap), (rank, pp)))| {
[ [
format!("{}", id + start + 1), format!("{}", id + start + 1),
format!("{}", pp), pp.to_string(),
format!("{:.2}%", play.accuracy(self.mode)), format!("{:.2}%", play.accuracy(self.mode)),
format!("{}", rank), format!("{}", rank),
play.mods.to_string(), play.mods.to_string(),

View file

@ -16,9 +16,9 @@ use super::{
BeatmapWithMode, OsuEnv, BeatmapWithMode, OsuEnv,
}; };
pub(super) const BTN_CHECK: &'static str = "youmubot_osu_btn_check"; pub(super) const BTN_CHECK: &str = "youmubot_osu_btn_check";
pub(super) const BTN_LB: &'static str = "youmubot_osu_btn_lb"; pub(super) const BTN_LB: &str = "youmubot_osu_btn_lb";
pub(super) const BTN_LAST: &'static str = "youmubot_osu_btn_last"; pub(super) const BTN_LAST: &str = "youmubot_osu_btn_last";
/// Create an action row for score pages. /// Create an action row for score pages.
pub fn score_components(guild_id: Option<GuildId>) -> CreateActionRow { pub fn score_components(guild_id: Option<GuildId>) -> CreateActionRow {
@ -208,7 +208,7 @@ pub fn handle_lb_button<'a>(
CreateInteractionResponse::Defer(CreateInteractionResponseMessage::new()), CreateInteractionResponse::Defer(CreateInteractionResponseMessage::new()),
) )
.await?; .await?;
let scores = get_leaderboard(&ctx, &env, &bm, order, guild).await?; let scores = get_leaderboard(ctx, &env, &bm, order, guild).await?;
if scores.is_empty() { if scores.is_empty() {
comp.create_followup( comp.create_followup(
@ -230,7 +230,7 @@ pub fn handle_lb_button<'a>(
)), )),
) )
.await?; .await?;
display_rankings_table(&ctx, reply, scores, &bm, order).await?; display_rankings_table(ctx, reply, scores, &bm, order).await?;
Ok(()) Ok(())
}) })
} }

View file

@ -49,7 +49,7 @@ pub fn parse_old_links<'a>(
.name("mode") .name("mode")
.map(|v| v.as_str().parse::<u8>()) .map(|v| v.as_str().parse::<u8>())
.transpose()? .transpose()?
.map(|v| Mode::from(v)); .map(Mode::from);
let embed = match req_type { let embed = match req_type {
"b" => { "b" => {
// collect beatmap info // collect beatmap info
@ -57,9 +57,9 @@ pub fn parse_old_links<'a>(
.name("mods") .name("mods")
.and_then(|v| Mods::from_str(v.as_str()).pls_ok()) .and_then(|v| Mods::from_str(v.as_str()).pls_ok())
.unwrap_or(Mods::NOMOD); .unwrap_or(Mods::NOMOD);
EmbedType::from_beatmap_id(&env, capture["id"].parse()?, mode, mods).await EmbedType::from_beatmap_id(env, capture["id"].parse()?, mode, mods).await
} }
"s" => EmbedType::from_beatmapset_id(&env, capture["id"].parse()?).await, "s" => EmbedType::from_beatmapset_id(env, capture["id"].parse()?).await,
_ => unreachable!(), _ => unreachable!(),
}?; }?;
Ok(ToPrint { Ok(ToPrint {
@ -92,11 +92,11 @@ pub fn parse_new_links<'a>(
.name("mods") .name("mods")
.and_then(|v| Mods::from_str(v.as_str()).pls_ok()) .and_then(|v| Mods::from_str(v.as_str()).pls_ok())
.unwrap_or(Mods::NOMOD); .unwrap_or(Mods::NOMOD);
EmbedType::from_beatmap_id(&env, beatmap_id, mode, mods).await EmbedType::from_beatmap_id(env, beatmap_id, mode, mods).await
} }
None => { None => {
EmbedType::from_beatmapset_id( EmbedType::from_beatmapset_id(
&env, env,
capture.name("set_id").unwrap().as_str().parse()?, capture.name("set_id").unwrap().as_str().parse()?,
) )
.await .await
@ -124,7 +124,7 @@ pub fn parse_short_links<'a>(
.name("mods") .name("mods")
.and_then(|v| Mods::from_str(v.as_str()).pls_ok()) .and_then(|v| Mods::from_str(v.as_str()).pls_ok())
.unwrap_or(Mods::NOMOD); .unwrap_or(Mods::NOMOD);
let embed = EmbedType::from_beatmap_id(&env, id, mode, mods).await?; let embed = EmbedType::from_beatmap_id(env, id, mode, mods).await?;
Ok(ToPrint { embed, link, mode }) Ok(ToPrint { embed, link, mode })
}) })
.collect::<stream::FuturesUnordered<_>>() .collect::<stream::FuturesUnordered<_>>()

View file

@ -386,7 +386,7 @@ async fn add_user(target: serenity::model::id::UserId, user: User, env: &OsuEnv)
.user_best(UserID::ID(user.id), |f| f.mode(mode).limit(100)) .user_best(UserID::ID(user.id), |f| f.mode(mode).limit(100))
.await .await
.pls_ok() .pls_ok()
.unwrap_or_else(|| vec![]); .unwrap_or_else(std::vec::Vec::new);
( (
calculate_weighted_map_length(&scores, &env.beatmaps, mode) calculate_weighted_map_length(&scores, &env.beatmaps, mode)
@ -413,7 +413,7 @@ async fn add_user(target: serenity::model::id::UserId, user: User, env: &OsuEnv)
}) })
}) })
.collect::<stream::FuturesOrdered<_>>() .collect::<stream::FuturesOrdered<_>>()
.filter_map(|v| future::ready(v)) .filter_map(future::ready)
.collect::<Map<_, _>>() .collect::<Map<_, _>>()
.await; .await;
@ -605,7 +605,7 @@ pub(crate) async fn load_beatmap(
} }
} }
let b = cache::get_beatmap(&env, channel_id).await.ok().flatten(); let b = cache::get_beatmap(env, channel_id).await.ok().flatten();
b.map(|b| (b, None)) b.map(|b| (b, None))
} }
@ -836,7 +836,7 @@ async fn get_user(
mut args: Args, mut args: Args,
mode: Mode, mode: Mode,
) -> CommandResult { ) -> CommandResult {
let user = to_user_id_query(args.single::<UsernameArg>().ok(), &env, msg.author.id).await?; let user = to_user_id_query(args.single::<UsernameArg>().ok(), env, msg.author.id).await?;
let osu_client = &env.client; let osu_client = &env.client;
let meta_cache = &env.beatmaps; let meta_cache = &env.beatmaps;
let user = osu_client.user(&user, |f| f.mode(mode)).await?; let user = osu_client.user(&user, |f| f.mode(mode)).await?;

View file

@ -193,7 +193,7 @@ impl BeatmapCache {
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for beatmap in &mut osu_files { for beatmap in &mut osu_files {
if beatmap.metadata.background_file != "" { if !beatmap.metadata.background_file.is_empty() {
let bg = backgrounds let bg = backgrounds
.entry(beatmap.metadata.background_file.clone()) .entry(beatmap.metadata.background_file.clone())
.or_insert_with(|| { .or_insert_with(|| {
@ -205,7 +205,7 @@ impl BeatmapCache {
content: content.into_boxed_slice(), content: content.into_boxed_slice(),
})) }))
}); });
beatmap.beatmap_background = bg.clone(); beatmap.beatmap_background.clone_from(bg);
} }
} }
Ok(osu_files) Ok(osu_files)

View file

@ -225,7 +225,7 @@ pub async fn server_rank(ctx: &Context, m: &Message, mut args: Args) -> CommandR
table_formatting(&headers, &ALIGNS, table) table_formatting(&headers, &ALIGNS, table)
} }
RankQuery::PP => { RankQuery::PP => {
const HEADERS: [&'static str; 6] = const HEADERS: [&str; 6] =
["#", "pp", "Map length", "Map age", "Username", "Member"]; ["#", "pp", "Map length", "Map age", "Username", "Member"];
const ALIGNS: [Align; 6] = [Right, Right, Right, Right, Left, Left]; const ALIGNS: [Align; 6] = [Right, Right, Right, Right, Left, Left];
@ -250,7 +250,7 @@ pub async fn server_rank(ctx: &Context, m: &Message, mut args: Args) -> CommandR
table_formatting(&HEADERS, &ALIGNS, table) table_formatting(&HEADERS, &ALIGNS, table)
} }
RankQuery::TotalPP => { RankQuery::TotalPP => {
const HEADERS: [&'static str; 4] = ["#", "Total pp", "Username", "Member"]; const HEADERS: [&str; 4] = ["#", "Total pp", "Username", "Member"];
const ALIGNS: [Align; 4] = [Right, Right, Left, Left]; const ALIGNS: [Align; 4] = [Right, Right, Left, Left];
let table = users let table = users
@ -338,7 +338,7 @@ pub async fn show_leaderboard(ctx: &Context, msg: &Message, mut args: Args) -> C
let scores = { let scores = {
let reaction = msg.react(ctx, '⌛').await?; let reaction = msg.react(ctx, '⌛').await?;
let s = get_leaderboard(&ctx, &env, &bm, order, guild).await?; let s = get_leaderboard(ctx, &env, &bm, order, guild).await?;
reaction.delete(&ctx).await?; reaction.delete(&ctx).await?;
s s
}; };
@ -360,7 +360,7 @@ pub async fn show_leaderboard(ctx: &Context, msg: &Message, mut args: Args) -> C
), ),
) )
.await?; .await?;
display_rankings_table(&ctx, reply, scores, &bm, order).await?; display_rankings_table(ctx, reply, scores, &bm, order).await?;
} }
ScoreListStyle::Grid => { ScoreListStyle::Grid => {
let reply = msg let reply = msg
@ -497,9 +497,9 @@ pub async fn display_rankings_table(
let scores = scores[start..end].to_vec(); let scores = scores[start..end].to_vec();
let bm = (bm.0.clone(), bm.1); let bm = (bm.0.clone(), bm.1);
Box::pin(async move { Box::pin(async move {
const SCORE_HEADERS: [&'static str; 8] = const SCORE_HEADERS: [&str; 8] =
["#", "Score", "Mods", "Rank", "Acc", "Combo", "Miss", "User"]; ["#", "Score", "Mods", "Rank", "Acc", "Combo", "Miss", "User"];
const PP_HEADERS: [&'static str; 8] = const PP_HEADERS: [&str; 8] =
["#", "PP", "Mods", "Rank", "Acc", "Combo", "Miss", "User"]; ["#", "PP", "Mods", "Rank", "Acc", "Combo", "Miss", "User"];
const ALIGNS: [Align; 8] = [Right, Right, Right, Right, Right, Right, Right, Left]; const ALIGNS: [Align; 8] = [Right, Right, Right, Right, Right, Right, Right, Left];

View file

@ -123,7 +123,7 @@ impl Client {
let s = match self.rosu.score(score_id).await { let s = match self.rosu.score(score_id).await {
Ok(v) => v, Ok(v) => v,
Err(rosu_v2::error::OsuError::NotFound) => return Ok(None), Err(rosu_v2::error::OsuError::NotFound) => return Ok(None),
e @ _ => e?, e => e?,
}; };
Ok(Some(s.into())) Ok(Some(s.into()))
} }

View file

@ -77,7 +77,7 @@ impl MemberToChannels {
/// Gets the channel list of an user related to that channel. /// Gets the channel list of an user related to that channel.
pub async fn channels_of( pub async fn channels_of(
&self, &self,
http: impl CacheHttp + Clone + Sync, http: impl CacheHttp + Clone,
u: impl Into<UserId>, u: impl Into<UserId>,
) -> Vec<ChannelId> { ) -> Vec<ChannelId> {
let u: UserId = u.into(); let u: UserId = u.into();
@ -105,6 +105,12 @@ pub struct AnnouncerHandler {
} }
/// Announcer-managing related. /// Announcer-managing related.
impl Default for AnnouncerHandler {
fn default() -> Self {
Self::new()
}
}
impl AnnouncerHandler { impl AnnouncerHandler {
/// Create a new instance of the handler. /// Create a new instance of the handler.
pub fn new() -> Self { pub fn new() -> Self {
@ -119,7 +125,7 @@ impl AnnouncerHandler {
pub fn add( pub fn add(
&mut self, &mut self,
key: &'static str, key: &'static str,
announcer: impl Announcer + Send + Sync + 'static, announcer: impl Announcer + Sync + 'static,
) -> &mut Self { ) -> &mut Self {
if self if self
.announcers .announcers
@ -136,12 +142,12 @@ impl AnnouncerHandler {
} }
pub fn run(self, client: &Client) -> AnnouncerRunner { pub fn run(self, client: &Client) -> AnnouncerRunner {
let runner = AnnouncerRunner {
AnnouncerRunner {
cache_http: CacheAndHttp::from_client(client), cache_http: CacheAndHttp::from_client(client),
data: client.data.clone(), data: client.data.clone(),
announcers: self.announcers, announcers: self.announcers,
}; }
runner
} }
} }

View file

@ -39,11 +39,11 @@ pub async fn setup_prelude(
// Set up the SQL client. // Set up the SQL client.
data.insert::<crate::SQLClient>(sql_pool.clone()); data.insert::<crate::SQLClient>(sql_pool.clone());
let env = Env {
Env {
http: http_client, http: http_client,
sql: sql_pool, sql: sql_pool,
members: member_cache, members: member_cache,
}; }
env
} }

View file

@ -28,7 +28,7 @@ impl Framework for ComposedFramework {
} }
async fn init(&mut self, client: &Client) { async fn init(&mut self, client: &Client) {
for f in self.frameworks.iter_mut() { for f in self.frameworks.iter_mut() {
f.init(&client).await f.init(client).await
} }
} }
} }

View file

@ -115,7 +115,7 @@ impl EventHandler for Handler {
.iter() .iter()
.map(|hook| { .map(|hook| {
hook.write() hook.write()
.then(|mut h| async move { h.call(&ctx, &interaction).await }) .then(|mut h| async move { h.call(ctx, interaction).await })
}) })
.collect::<stream::FuturesUnordered<_>>() .collect::<stream::FuturesUnordered<_>>()
.for_each(|v| async move { .for_each(|v| async move {