diff --git a/parser/src/command/assign.rs b/parser/src/command/assign.rs index a774e7ad..7d9e34c9 100644 --- a/parser/src/command/assign.rs +++ b/parser/src/command/assign.rs @@ -47,7 +47,7 @@ impl AssignCommand { if let Some(Token::Dot) | Some(Token::EndOfLine) = toks.peek_token()? { toks.next_token()?; *input = toks; - return Ok(Some(AssignCommand::Own)); + Ok(Some(AssignCommand::Own)) } else { return Err(toks.error(ParseError::ExpectedEnd)); } @@ -97,9 +97,9 @@ impl AssignCommand { mod tests { use super::*; - fn parse<'a>(input: &'a str) -> Result, Error<'a>> { + fn parse(input: &str) -> Result, Error<'_>> { let mut toks = Tokenizer::new(input); - Ok(AssignCommand::parse(&mut toks)?) + AssignCommand::parse(&mut toks) } #[test] @@ -135,9 +135,9 @@ mod tests { ); } - fn parse_review<'a>(input: &'a str) -> Result, Error<'a>> { + fn parse_review(input: &str) -> Result, Error<'_>> { let mut toks = Tokenizer::new(input); - Ok(AssignCommand::parse_review(&mut toks)?) + AssignCommand::parse_review(&mut toks) } #[test] diff --git a/parser/src/command/glacier.rs b/parser/src/command/glacier.rs index 5d90e079..46856fdb 100644 --- a/parser/src/command/glacier.rs +++ b/parser/src/command/glacier.rs @@ -45,7 +45,7 @@ impl GlacierCommand { Some(Token::Quote(s)) => { let source = s.to_owned(); if source.starts_with("https://gist.github.com/") { - return Ok(Some(GlacierCommand { source })); + Ok(Some(GlacierCommand { source })) } else { return Err(toks.error(ParseError::InvalidLink)); } @@ -67,9 +67,9 @@ impl GlacierCommand { mod test { use super::*; - fn parse<'a>(input: &'a str) -> Result, Error<'a>> { + fn parse(input: &str) -> Result, Error<'_>> { let mut toks = Tokenizer::new(input); - Ok(GlacierCommand::parse(&mut toks)?) + GlacierCommand::parse(&mut toks) } #[test] diff --git a/parser/src/command/nominate.rs b/parser/src/command/nominate.rs index e8bea584..c2af70f2 100644 --- a/parser/src/command/nominate.rs +++ b/parser/src/command/nominate.rs @@ -72,7 +72,7 @@ impl NominateCommand { if let Some(Token::Dot) | Some(Token::EndOfLine) = toks.peek_token()? { toks.next_token()?; *input = toks; - return Ok(Some(NominateCommand { team, style })); + Ok(Some(NominateCommand { team, style })) } else { return Err(toks.error(ParseError::ExpectedEnd)); } @@ -80,9 +80,9 @@ impl NominateCommand { } #[cfg(test)] -fn parse<'a>(input: &'a str) -> Result, Error<'a>> { +fn parse(input: &str) -> Result, Error<'_>> { let mut toks = Tokenizer::new(input); - Ok(NominateCommand::parse(&mut toks)?) + NominateCommand::parse(&mut toks) } #[test] diff --git a/parser/src/command/note.rs b/parser/src/command/note.rs index c25fa8e7..6a8da045 100644 --- a/parser/src/command/note.rs +++ b/parser/src/command/note.rs @@ -29,7 +29,7 @@ impl NoteCommand { let mut remove = false; loop { match toks.next_token()? { - Some(Token::Word(title)) if title == "remove" => { + Some(Token::Word("remove")) => { remove = true; continue; } diff --git a/parser/src/command/ping.rs b/parser/src/command/ping.rs index 16089549..a013286a 100644 --- a/parser/src/command/ping.rs +++ b/parser/src/command/ping.rs @@ -47,20 +47,20 @@ impl PingCommand { if let Some(Token::Dot) | Some(Token::EndOfLine) = toks.peek_token()? { toks.next_token()?; *input = toks; - return Ok(Some(PingCommand { team })); + Ok(Some(PingCommand { team })) } else { return Err(toks.error(ParseError::ExpectedEnd)); } } else { - return Ok(None); + Ok(None) } } } #[cfg(test)] -fn parse<'a>(input: &'a str) -> Result, Error<'a>> { +fn parse(input: &str) -> Result, Error<'_>> { let mut toks = Tokenizer::new(input); - Ok(PingCommand::parse(&mut toks)?) + PingCommand::parse(&mut toks) } #[test] diff --git a/parser/src/command/relabel.rs b/parser/src/command/relabel.rs index 55f3435f..dd1300c1 100644 --- a/parser/src/command/relabel.rs +++ b/parser/src/command/relabel.rs @@ -92,13 +92,13 @@ impl LabelDelta { return Err(input.error(ParseError::ExpectedLabelDelta)); } }; - if delta.starts_with('+') { + if let Some(rest) = delta.strip_prefix('+') { Ok(LabelDelta::Add( - Label::parse(&delta[1..]).map_err(|e| input.error(e))?, + Label::parse(rest).map_err(|e| input.error(e))?, )) - } else if delta.starts_with('-') { + } else if let Some(rest) = delta.strip_prefix('-') { Ok(LabelDelta::Remove( - Label::parse(&delta[1..]).map_err(|e| input.error(e))?, + Label::parse(rest).map_err(|e| input.error(e))?, )) } else { Ok(LabelDelta::Add( @@ -165,7 +165,7 @@ impl RelabelCommand { } #[cfg(test)] -fn parse<'a>(input: &'a str) -> Result>, Error<'a>> { +fn parse(input: &str) -> Result>, Error<'_>> { let mut toks = Tokenizer::new(input); Ok(RelabelCommand::parse(&mut toks)?.map(|c| c.0)) } diff --git a/parser/src/command/shortcut.rs b/parser/src/command/shortcut.rs index ed36d919..ce98a712 100644 --- a/parser/src/command/shortcut.rs +++ b/parser/src/command/shortcut.rs @@ -57,7 +57,7 @@ impl ShortcutCommand { #[cfg(test)] fn parse(input: &str) -> Result, Error<'_>> { let mut toks = Tokenizer::new(input); - Ok(ShortcutCommand::parse(&mut toks)?) + ShortcutCommand::parse(&mut toks) } #[test] diff --git a/parser/src/ignore_block.rs b/parser/src/ignore_block.rs index 250273e4..c22c2425 100644 --- a/parser/src/ignore_block.rs +++ b/parser/src/ignore_block.rs @@ -13,7 +13,7 @@ impl IgnoreBlocks { while let Some((event, range)) = parser.next() { if let Event::Start(Tag::CodeBlock(_)) = event { let start = range.start; - while let Some((event, range)) = parser.next() { + for (event, range) in parser.by_ref() { if let Event::End(Tag::CodeBlock(_)) = event { ignore.push(start..range.end); break; @@ -22,7 +22,7 @@ impl IgnoreBlocks { } else if let Event::Start(Tag::BlockQuote) = event { let start = range.start; let mut count = 1; - while let Some((event, range)) = parser.next() { + for (event, range) in parser.by_ref() { if let Event::Start(Tag::BlockQuote) = event { count += 1; } else if let Event::End(Tag::BlockQuote) = event { diff --git a/parser/src/token.rs b/parser/src/token.rs index a2e7b5fd..1fd6b196 100644 --- a/parser/src/token.rs +++ b/parser/src/token.rs @@ -207,7 +207,7 @@ impl<'a> Tokenizer<'a> { } self.advance(); } - Ok(Some(Token::Word(&self.str_from(start)))) + Ok(Some(Token::Word(self.str_from(start)))) } pub fn eat_token(&mut self, token: Token<'a>) -> Result> { @@ -222,7 +222,7 @@ impl<'a> Tokenizer<'a> { } #[cfg(test)] -fn tokenize<'a>(input: &'a str) -> Result>, Error<'a>> { +fn tokenize(input: &str) -> Result>, Error<'_>> { let mut tokens = Vec::new(); let mut gen = Tokenizer::new(input); while let Some(tok) = gen.next_token()? { diff --git a/src/agenda.rs b/src/agenda.rs index 238b4780..90db2c42 100644 --- a/src/agenda.rs +++ b/src/agenda.rs @@ -2,7 +2,7 @@ use crate::actions::{Action, Query, QueryKind, QueryMap, Step}; use crate::github; use std::sync::Arc; -pub fn prioritization<'a>() -> Box { +pub fn prioritization() -> Box { Box::new(Step { name: "prioritization_agenda", actions: vec![ @@ -442,7 +442,7 @@ pub fn prioritization<'a>() -> Box { }) } -pub fn lang<'a>() -> Box { +pub fn lang() -> Box { Box::new(Step { name: "lang_agenda", actions: vec![ @@ -561,7 +561,7 @@ pub fn lang<'a>() -> Box { }) } -pub fn lang_planning<'a>() -> Box { +pub fn lang_planning() -> Box { Box::new(Step { name: "lang_planning_agenda", actions: vec![ @@ -611,7 +611,7 @@ pub fn lang_planning<'a>() -> Box { }) } -pub fn types_planning<'a>() -> Box { +pub fn types_planning() -> Box { Box::new(Step { name: "types_planning_agenda", actions: vec![ @@ -677,7 +677,7 @@ pub fn types_planning<'a>() -> Box { // Things to add (maybe): // - Compiler RFCs // - P-high issues -pub fn compiler_backlog_bonanza<'a>() -> Box { +pub fn compiler_backlog_bonanza() -> Box { Box::new(Step { name: "compiler_backlog_bonanza", actions: vec![Query { diff --git a/src/bin/compiler.rs b/src/bin/compiler.rs index d4aff5f8..5486e68e 100644 --- a/src/bin/compiler.rs +++ b/src/bin/compiler.rs @@ -6,15 +6,10 @@ async fn main() -> anyhow::Result<()> { tracing_subscriber::fmt::init(); let args: Vec = std::env::args().collect(); - if args.len() == 2 { - match &args[1][..] { - "backlog_bonanza" => { - let agenda = agenda::compiler_backlog_bonanza(); - print!("{}", agenda.call().await?); - return Ok(()); - } - _ => {} - } + if args.len() == 2 && args[1] == "backlog_bonanza" { + let agenda = agenda::compiler_backlog_bonanza(); + print!("{}", agenda.call().await?); + return Ok(()); } eprintln!("Usage: compiler (backlog_bonanza)"); diff --git a/src/bin/types.rs b/src/bin/types.rs index ec411927..c4cc6c22 100644 --- a/src/bin/types.rs +++ b/src/bin/types.rs @@ -6,15 +6,10 @@ async fn main() -> anyhow::Result<()> { tracing_subscriber::fmt::init(); let args: Vec = std::env::args().collect(); - if args.len() == 2 { - match &args[1][..] { - "planning" => { - let agenda = agenda::types_planning(); - print!("{}", agenda.call().await?); - return Ok(()); - } - _ => {} - } + if args.len() == 2 && args[1] == "planning" { + let agenda = agenda::types_planning(); + print!("{}", agenda.call().await?); + return Ok(()); } eprintln!("Usage: types (planning)"); diff --git a/src/changelogs/rustc.rs b/src/changelogs/rustc.rs index 42dc86e5..8a500fbc 100644 --- a/src/changelogs/rustc.rs +++ b/src/changelogs/rustc.rs @@ -24,7 +24,7 @@ impl<'a> RustcFormat<'a> { } pub(super) fn parse(mut self, content: &str) -> anyhow::Result { - let ast = comrak::parse_document(&self.arena, &content, &ComrakOptions::default()); + let ast = comrak::parse_document(self.arena, content, &ComrakOptions::default()); let mut section_ast = Vec::new(); for child in ast.children() { diff --git a/src/config.rs b/src/config.rs index 8312aab3..29460087 100644 --- a/src/config.rs +++ b/src/config.rs @@ -9,9 +9,11 @@ use tracing as log; static CONFIG_FILE_NAME: &str = "triagebot.toml"; const REFRESH_EVERY: Duration = Duration::from_secs(2 * 60); // Every two minutes +type CacheLeaf = (Result, ConfigurationError>, Instant); + lazy_static::lazy_static! { static ref CONFIG_CACHE: - RwLock, ConfigurationError>, Instant)>> = + RwLock> = RwLock::new(HashMap::new()); } @@ -378,7 +380,7 @@ mod tests { [shortcut] "#; - let config = toml::from_str::(&config).unwrap(); + let config = toml::from_str::(config).unwrap(); let mut ping_teams = HashMap::new(); ping_teams.insert( "compiler".to_owned(), diff --git a/src/db.rs b/src/db.rs index 272601b0..9c7fb280 100644 --- a/src/db.rs +++ b/src/db.rs @@ -95,7 +95,7 @@ async fn make_client() -> anyhow::Result { let db_url = std::env::var("DATABASE_URL").expect("needs DATABASE_URL"); if db_url.contains("rds.amazonaws.com") { let cert = &CERTIFICATE_PEM[..]; - let cert = Certificate::from_pem(&cert).context("made certificate")?; + let cert = Certificate::from_pem(cert).context("made certificate")?; let connector = TlsConnector::builder() .add_root_certificate(cert) .build() @@ -205,29 +205,32 @@ pub async fn schedule_job( anyhow::bail!("Job {} does not exist in the current job list.", job_name); } - if let Err(_) = get_job_by_name_and_scheduled_at(&db, job_name, &when).await { + if get_job_by_name_and_scheduled_at(db, job_name, &when) + .await + .is_err() + { // mean there's no job already in the db with that name and scheduled_at - insert_job(&db, job_name, &when, &job_metadata).await?; + insert_job(db, job_name, &when, &job_metadata).await?; } Ok(()) } pub async fn run_scheduled_jobs(ctx: &Context, db: &DbClient) -> anyhow::Result<()> { - let jobs = get_jobs_to_execute(&db).await.unwrap(); + let jobs = get_jobs_to_execute(db).await.unwrap(); tracing::trace!("jobs to execute: {:#?}", jobs); for job in jobs.iter() { - update_job_executed_at(&db, &job.id).await?; + update_job_executed_at(db, &job.id).await?; - match handle_job(&ctx, &job.name, &job.metadata).await { + match handle_job(ctx, &job.name, &job.metadata).await { Ok(_) => { tracing::trace!("job successfully executed (id={})", job.id); - delete_job(&db, &job.id).await?; + delete_job(db, &job.id).await?; } Err(e) => { tracing::error!("job failed on execution (id={:?}, error={:?})", job.id, e); - update_job_error_message(&db, &job.id, &e.to_string()).await?; + update_job_error_message(db, &job.id, &e.to_string()).await?; } } } @@ -242,7 +245,7 @@ async fn handle_job( metadata: &serde_json::Value, ) -> anyhow::Result<()> { for job in jobs() { - if &job.name() == &name { + if job.name() == name { return job.run(ctx, metadata).await; } } diff --git a/src/db/notifications.rs b/src/db/notifications.rs index 5b185793..264f21aa 100644 --- a/src/db/notifications.rs +++ b/src/db/notifications.rs @@ -1,5 +1,6 @@ use anyhow::Context as _; use chrono::{DateTime, FixedOffset}; +use std::cmp::Ordering; use tokio_postgres::Client as DbClient; use tracing as log; @@ -222,10 +223,10 @@ pub async fn move_indices( ); } - if from < to { - notifications[from..=to].rotate_left(1); - } else if to < from { - notifications[to..=from].rotate_right(1); + match from.cmp(&to) { + Ordering::Less => notifications[from..=to].rotate_left(1), + Ordering::Greater => notifications[to..=from].rotate_right(1), + Ordering::Equal => (), } for (idx, id) in notifications.into_iter().enumerate() { diff --git a/src/github.rs b/src/github.rs index bbd824dd..340a4470 100644 --- a/src/github.rs +++ b/src/github.rs @@ -514,9 +514,7 @@ impl Issue { self.repository().url(), self.number, ); - Ok(client - .json::>(client.get(&comment_url)) - .await?) + client.json::>(client.get(&comment_url)).await } // returns an array of one element @@ -529,9 +527,7 @@ impl Issue { self.repository().url(), self.number, ); - Ok(client - .json::>(client.get(&comment_url)) - .await?) + client.json::>(client.get(&comment_url)).await } pub async fn edit_body(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> { @@ -625,7 +621,7 @@ impl Issue { // Don't try to add labels already present on this issue. let labels = labels .into_iter() - .filter(|l| !self.labels().contains(&l)) + .filter(|l| !self.labels().contains(l)) .map(|l| l.name) .collect::>(); @@ -870,7 +866,7 @@ impl Issue { self.repository().url(), self.number )); - Ok(client.json(req).await?) + client.json(req).await } } @@ -1154,8 +1150,8 @@ impl Repository { fn build_issues_url( &self, - filters: &Vec<(&str, &str)>, - include_labels: &Vec<&str>, + filters: &[(&str, &str)], + include_labels: &[&str], ordering: Ordering<'_>, ) -> String { self.build_endpoint_url("issues", filters, include_labels, ordering) @@ -1163,8 +1159,8 @@ impl Repository { fn build_pulls_url( &self, - filters: &Vec<(&str, &str)>, - include_labels: &Vec<&str>, + filters: &[(&str, &str)], + include_labels: &[&str], ordering: Ordering<'_>, ) -> String { self.build_endpoint_url("pulls", filters, include_labels, ordering) @@ -1173,8 +1169,8 @@ impl Repository { fn build_endpoint_url( &self, endpoint: &str, - filters: &Vec<(&str, &str)>, - include_labels: &Vec<&str>, + filters: &[(&str, &str)], + include_labels: &[&str], ordering: Ordering<'_>, ) -> String { let filters = filters @@ -1203,9 +1199,9 @@ impl Repository { fn build_search_issues_url( &self, - filters: &Vec<(&str, &str)>, - include_labels: &Vec<&str>, - exclude_labels: &Vec<&str>, + filters: &[(&str, &str)], + include_labels: &[&str], + exclude_labels: &[&str], ordering: Ordering<'_>, ) -> String { let filters = filters @@ -1680,7 +1676,7 @@ fn quote_reply(markdown: &str) -> String { if markdown.is_empty() { String::from("*No content*") } else { - format!("\n\t> {}", markdown.replace("\n", "\n\t> ")) + format!("\n\t> {}", markdown.replace('\n', "\n\t> ")) } } @@ -1694,7 +1690,7 @@ impl<'q> IssuesQuery for Query<'q> { client: &'a GithubClient, ) -> anyhow::Result> { let issues = repo - .get_issues(&client, self) + .get_issues(client, self) .await .with_context(|| "Unable to get issues.")?; @@ -1729,7 +1725,7 @@ impl<'q> IssuesQuery for Query<'q> { let fk_initiating_comment = fcp.fcp.fk_initiating_comment; let init_comment = issue - .get_comment(&client, fk_initiating_comment.try_into()?) + .get_comment(client, fk_initiating_comment.try_into()?) .await?; Some(crate::actions::FCPDetails { @@ -1746,7 +1742,7 @@ impl<'q> IssuesQuery for Query<'q> { }; let mcp_details = if include_mcp_details { - let first_comment = issue.get_first_comment(&client).await?; + let first_comment = issue.get_first_comment(client).await?; let split = re_zulip_link .split(&first_comment[0].body) .collect::>(); @@ -1909,14 +1905,12 @@ impl RequestSend for RequestBuilder { /// Finds the token in the user's environment, panicking if no suitable token /// can be found. pub fn default_token_from_env() -> String { - match std::env::var("GITHUB_API_TOKEN") { - Ok(v) => return v, - Err(_) => (), + if let Ok(v) = std::env::var("GITHUB_API_TOKEN") { + return v; } - match get_token_from_git_config() { - Ok(v) => return v, - Err(_) => (), + if let Ok(v) = get_token_from_git_config() { + return v; } panic!("could not find token in GITHUB_API_TOKEN or .gitconfig/github.oath-token") diff --git a/src/handlers/assign.rs b/src/handlers/assign.rs index 1c3eb6f3..4b5f97e2 100644 --- a/src/handlers/assign.rs +++ b/src/handlers/assign.rs @@ -118,7 +118,7 @@ pub(super) async fn handle_input( // Don't auto-assign or welcome if the user manually set the assignee when opening. if event.issue.assignees.is_empty() { - let (assignee, from_comment) = determine_assignee(ctx, event, config, &diff).await?; + let (assignee, from_comment) = determine_assignee(ctx, event, config, diff).await?; if assignee.as_deref() == Some("ghost") { // "ghost" is GitHub's placeholder account for deleted accounts. // It is used here as a convenient way to prevent assignment. This @@ -231,7 +231,7 @@ fn modifies_submodule(diff: &[FileDiff]) -> Option { /// Sets the assignee of a PR, alerting any errors. async fn set_assignee(issue: &Issue, github: &GithubClient, username: &str) { // Don't re-assign if already assigned, e.g. on comment edit - if issue.contain_assignee(&username) { + if issue.contain_assignee(username) { log::trace!( "ignoring assign PR {} to {}, already assigned", issue.global_id(), @@ -239,7 +239,7 @@ async fn set_assignee(issue: &Issue, github: &GithubClient, username: &str) { ); return; } - if let Err(err) = issue.set_assignee(github, &username).await { + if let Err(err) = issue.set_assignee(github, username).await { log::warn!( "failed to set assignee of PR {} to {}: {:?}", issue.global_id(), @@ -425,12 +425,11 @@ pub(super) async fn handle_command( event: &Event, cmd: AssignCommand, ) -> anyhow::Result<()> { - let is_team_member = if let Err(_) | Ok(false) = event.user().is_team_member(&ctx.github).await - { - false - } else { - true - }; + let is_team_member = event + .user() + .is_team_member(&ctx.github) + .await + .unwrap_or(false); // Don't handle commands in comments from the bot. Some of the comments it // posts contain commands to instruct the user, not things that the bot @@ -523,7 +522,7 @@ pub(super) async fn handle_command( return Ok(()); } - let e = EditIssueBody::new(&issue, "ASSIGN"); + let e = EditIssueBody::new(issue, "ASSIGN"); let to_assign = match cmd { AssignCommand::Own => event.user().login.clone(), @@ -550,7 +549,7 @@ pub(super) async fn handle_command( let current = &event.user().login; if issue.contain_assignee(current) { issue - .remove_assignees(&ctx.github, Selection::One(¤t)) + .remove_assignees(&ctx.github, Selection::One(current)) .await?; e.apply(&ctx.github, String::new(), AssignData { user: None }) .await?; @@ -783,7 +782,7 @@ fn candidate_reviewers_from_names<'a>( } } if candidates.is_empty() { - let initial = names.iter().cloned().collect(); + let initial = names.to_vec(); if filtered.is_empty() { Err(FindReviewerError::NoReviewer { initial }) } else { diff --git a/src/handlers/assign/tests/tests_candidates.rs b/src/handlers/assign/tests/tests_candidates.rs index f78aeca4..231b0dee 100644 --- a/src/handlers/assign/tests/tests_candidates.rs +++ b/src/handlers/assign/tests/tests_candidates.rs @@ -19,7 +19,7 @@ fn test_from_names( (Ok(candidates), Ok(expected)) => { let mut candidates: Vec<_> = candidates.into_iter().collect(); candidates.sort(); - let expected: Vec<_> = expected.iter().map(|x| *x).collect(); + let expected: Vec<_> = expected.to_vec(); assert_eq!(candidates, expected); } (Err(actual), Err(expected)) => { diff --git a/src/handlers/assign/tests/tests_from_diff.rs b/src/handlers/assign/tests/tests_from_diff.rs index 05729cf0..75669162 100644 --- a/src/handlers/assign/tests/tests_from_diff.rs +++ b/src/handlers/assign/tests/tests_from_diff.rs @@ -135,7 +135,7 @@ fn empty_file_still_counts() { let diff = "diff --git a/compiler/rustc_parse/src/foo.rs b/compiler/rustc_parse/src/foo.rs\n\ new file mode 100644\n\ index 0000000..e69de29\n"; - test_from_diff(&diff, config, &["parser"]); + test_from_diff(diff, config, &["parser"]); } #[test] diff --git a/src/handlers/close.rs b/src/handlers/close.rs index 2aa21df0..05d0c901 100644 --- a/src/handlers/close.rs +++ b/src/handlers/close.rs @@ -16,7 +16,7 @@ pub(super) async fn handle_command( .await .unwrap_or(false); if !is_team_member { - let cmnt = ErrorComment::new(&issue, "Only team members can close issues."); + let cmnt = ErrorComment::new(issue, "Only team members can close issues."); cmnt.post(&ctx.github).await?; return Ok(()); } diff --git a/src/handlers/docs_update.rs b/src/handlers/docs_update.rs index 80e5886b..b25a29f3 100644 --- a/src/handlers/docs_update.rs +++ b/src/handlers/docs_update.rs @@ -191,7 +191,7 @@ async fn create_commit( async fn create_pr(gh: &GithubClient, dest_repo: &Repository, updates: &[Update]) -> Result { let mut body = String::new(); for update in updates { - write!(body, "{}\n", update.pr_body).unwrap(); + writeln!(body, "{}", update.pr_body).unwrap(); } let username = WORK_REPO.split('/').next().unwrap(); diff --git a/src/handlers/major_change.rs b/src/handlers/major_change.rs index 0678ea42..ef1f7cc4 100644 --- a/src/handlers/major_change.rs +++ b/src/handlers/major_change.rs @@ -73,7 +73,7 @@ pub(super) async fn parse_input( } // All other issue events are ignored - return Ok(None); + Ok(None) } pub(super) async fn handle_input( @@ -126,7 +126,7 @@ pub(super) async fn handle_input( content: "The associated GitHub issue has been renamed. Renaming this Zulip topic.", }; let zulip_send_res = zulip_send_req - .send(&ctx.github.raw()) + .send(ctx.github.raw()) .await .context("zulip post failed")?; @@ -139,7 +139,7 @@ pub(super) async fn handle_input( content: None, }; zulip_update_req - .send(&ctx.github.raw()) + .send(ctx.github.raw()) .await .context("zulip message update failed")?; @@ -162,7 +162,7 @@ pub(super) async fn handle_input( content: &breadcrumb_comment, }; zulip_send_breadcrumb_req - .send(&ctx.github.raw()) + .send(ctx.github.raw()) .await .context("zulip post failed")?; @@ -194,8 +194,8 @@ pub(super) async fn handle_command( .any(|l| l.name == config.enabling_label) { let cmnt = ErrorComment::new( - &issue, - &format!( + issue, + format!( "This issue cannot be seconded; it lacks the `{}` label.", config.enabling_label ), @@ -212,7 +212,7 @@ pub(super) async fn handle_command( .unwrap_or(false); if !is_team_member { - let cmnt = ErrorComment::new(&issue, "Only team members can second issues."); + let cmnt = ErrorComment::new(issue, "Only team members can second issues."); cmnt.post(&ctx.github).await?; return Ok(()); } @@ -296,7 +296,7 @@ async fn handle( .context("post major change comment")?; } - let zulip_req = zulip_req.send(&ctx.github.raw()); + let zulip_req = zulip_req.send(ctx.github.raw()); let (gh_res, zulip_res) = futures::join!(github_req, zulip_req); zulip_res.context("zulip post failed")?; diff --git a/src/handlers/mentions.rs b/src/handlers/mentions.rs index a8bf49cd..82393840 100644 --- a/src/handlers/mentions.rs +++ b/src/handlers/mentions.rs @@ -69,7 +69,7 @@ pub(super) async fn parse_input( let touches_relevant_files = file_paths.iter().any(|p| p.starts_with(path)); // Don't mention if only the author is in the list. let pings_non_author = match &cc[..] { - [only_cc] => only_cc.trim_start_matches('@') != &event.issue.user.login, + [only_cc] => only_cc.trim_start_matches('@') != event.issue.user.login, _ => true, }; touches_relevant_files && pings_non_author diff --git a/src/handlers/nominate.rs b/src/handlers/nominate.rs index 77b20b90..bd287991 100644 --- a/src/handlers/nominate.rs +++ b/src/handlers/nominate.rs @@ -14,20 +14,18 @@ pub(super) async fn handle_command( event: &Event, cmd: NominateCommand, ) -> anyhow::Result<()> { - let is_team_member = if let Err(_) | Ok(false) = event.user().is_team_member(&ctx.github).await - { - false - } else { - true - }; + let is_team_member = event + .user() + .is_team_member(&ctx.github) + .await + .unwrap_or(false); if !is_team_member { let cmnt = ErrorComment::new( - &event.issue().unwrap(), - format!( - "Nominating and approving issues and pull requests is restricted to members of\ + event.issue().unwrap(), + "Nominating and approving issues and pull requests is restricted to members of\ the Rust teams." - ), + .to_string(), ); cmnt.post(&ctx.github).await?; return Ok(()); @@ -38,7 +36,7 @@ pub(super) async fn handle_command( if cmd.style == Style::BetaApprove { if !issue_labels.iter().any(|l| l.name == "beta-nominated") { let cmnt = ErrorComment::new( - &event.issue().unwrap(), + event.issue().unwrap(), format!( "This pull request is not beta-nominated, so it cannot be approved yet.\ Perhaps try to beta-nominate it by using `@{} beta-nominate `?", @@ -57,7 +55,7 @@ pub(super) async fn handle_command( } else { if !config.teams.contains_key(&cmd.team) { let cmnt = ErrorComment::new( - &event.issue().unwrap(), + event.issue().unwrap(), format!( "This team (`{}`) cannot be nominated for via this command;\ it may need to be added to `triagebot.toml` on the default branch.", diff --git a/src/handlers/note.rs b/src/handlers/note.rs index 11df402f..8b8b80f3 100644 --- a/src/handlers/note.rs +++ b/src/handlers/note.rs @@ -121,7 +121,7 @@ pub(super) async fn handle_command( cmd: NoteCommand, ) -> anyhow::Result<()> { let issue = event.issue().unwrap(); - let e = EditIssueBody::new(&issue, "SUMMARY"); + let e = EditIssueBody::new(issue, "SUMMARY"); let mut current: NoteData = e.current_data().unwrap_or_default(); diff --git a/src/handlers/notify_zulip.rs b/src/handlers/notify_zulip.rs index 87d0a018..c8b8a3ba 100644 --- a/src/handlers/notify_zulip.rs +++ b/src/handlers/notify_zulip.rs @@ -167,7 +167,7 @@ pub(super) async fn handle_input<'a>( }, content: &msg, }; - zulip_req.send(&ctx.github.raw()).await?; + zulip_req.send(ctx.github.raw()).await?; } Ok(()) diff --git a/src/handlers/ping.rs b/src/handlers/ping.rs index fc2d005c..6d011426 100644 --- a/src/handlers/ping.rs +++ b/src/handlers/ping.rs @@ -18,17 +18,16 @@ pub(super) async fn handle_command( event: &Event, team_name: PingCommand, ) -> anyhow::Result<()> { - let is_team_member = if let Err(_) | Ok(false) = event.user().is_team_member(&ctx.github).await - { - false - } else { - true - }; + let is_team_member = event + .user() + .is_team_member(&ctx.github) + .await + .unwrap_or(false); if !is_team_member { let cmnt = ErrorComment::new( - &event.issue().unwrap(), - format!("Only Rust team members can ping teams."), + event.issue().unwrap(), + "Only Rust team members can ping teams.".to_string(), ); cmnt.post(&ctx.github).await?; return Ok(()); @@ -38,7 +37,7 @@ pub(super) async fn handle_command( Some(v) => v, None => { let cmnt = ErrorComment::new( - &event.issue().unwrap(), + event.issue().unwrap(), format!( "This team (`{}`) cannot be pinged via this command; \ it may need to be added to `triagebot.toml` on the default branch.", @@ -49,12 +48,12 @@ pub(super) async fn handle_command( return Ok(()); } }; - let team = github::get_team(&ctx.github, &gh_team).await?; + let team = github::get_team(&ctx.github, gh_team).await?; let team = match team { Some(team) => team, None => { let cmnt = ErrorComment::new( - &event.issue().unwrap(), + event.issue().unwrap(), format!( "This team (`{}`) does not exist in the team repository.", team_name.team, @@ -90,7 +89,7 @@ pub(super) async fn handle_command( } let ping_msg = if users.is_empty() { - format!("no known users to ping?") + "no known users to ping?".to_string() } else { format!("cc {}", users.join(" ")) }; diff --git a/src/handlers/prioritize.rs b/src/handlers/prioritize.rs index 61b0cdf4..1dc3294c 100644 --- a/src/handlers/prioritize.rs +++ b/src/handlers/prioritize.rs @@ -11,10 +11,9 @@ pub(super) async fn handle_command( event: &Event, _: PrioritizeCommand, ) -> anyhow::Result<()> { - let mut labels = vec![]; - labels.push(github::Label { + let labels = vec![github::Label { name: config.label.to_owned(), - }); + }]; event .issue() .unwrap() diff --git a/src/handlers/relabel.rs b/src/handlers/relabel.rs index 6e7954df..8dae5a13 100644 --- a/src/handlers/relabel.rs +++ b/src/handlers/relabel.rs @@ -26,7 +26,7 @@ pub(super) async fn handle_command( let mut to_add = vec![]; for delta in &input.0 { let name = delta.label().as_str(); - let err = match check_filter(name, config, is_member(&event.user(), &ctx.github).await) { + let err = match check_filter(name, config, is_member(event.user(), &ctx.github).await) { Ok(CheckFilterResult::Allow) => None, Ok(CheckFilterResult::Deny) => Some(format!( "Label {} can only be set by Rust team members", @@ -40,7 +40,7 @@ pub(super) async fn handle_command( Err(err) => Some(err), }; if let Some(msg) = err { - let cmnt = ErrorComment::new(&event.issue().unwrap(), msg); + let cmnt = ErrorComment::new(event.issue().unwrap(), msg); cmnt.post(&ctx.github).await?; return Ok(()); } @@ -53,7 +53,7 @@ pub(super) async fn handle_command( LabelDelta::Remove(label) => { results.push(( label, - event.issue().unwrap().remove_label(&ctx.github, &label), + event.issue().unwrap().remove_label(&ctx.github, label), )); } } @@ -139,7 +139,7 @@ fn check_filter( } } if matched { - return Ok(CheckFilterResult::Allow); + Ok(CheckFilterResult::Allow) } else if is_member == TeamMembership::Outsider { return Ok(CheckFilterResult::Deny); } else { @@ -155,15 +155,17 @@ enum MatchPatternResult { } fn match_pattern(pattern: &str, label: &str) -> anyhow::Result { - let (pattern, inverse) = if pattern.starts_with('!') { - (&pattern[1..], true) + let (pattern, inverse) = if let Some(rest) = pattern.strip_prefix('!') { + (rest, true) } else { (pattern, false) }; let glob = glob::Pattern::new(pattern)?; - let mut matchopts = glob::MatchOptions::default(); - matchopts.case_sensitive = false; + let matchopts = glob::MatchOptions { + case_sensitive: false, + ..Default::default() + }; Ok(match (glob.matches_with(label, matchopts), inverse) { (true, false) => MatchPatternResult::Allow, diff --git a/src/handlers/review_submitted.rs b/src/handlers/review_submitted.rs index 92716aee..2ef84c52 100644 --- a/src/handlers/review_submitted.rs +++ b/src/handlers/review_submitted.rs @@ -24,7 +24,7 @@ pub(crate) async fn handle( if event.issue.assignees.contains(&event.comment.user) { // Remove review labels for label in &config.review_labels { - event.issue.remove_label(&ctx.github, &label).await?; + event.issue.remove_label(&ctx.github, label).await?; } // Add waiting on author event diff --git a/src/handlers/rfc_helper.rs b/src/handlers/rfc_helper.rs index 9daab157..caf3037c 100644 --- a/src/handlers/rfc_helper.rs +++ b/src/handlers/rfc_helper.rs @@ -15,7 +15,7 @@ pub async fn handle(ctx: &Context, event: &Event) -> anyhow::Result<()> { return Ok(()); } - if let Err(e) = add_rendered_link(&ctx, &e).await { + if let Err(e) = add_rendered_link(ctx, e).await { tracing::error!("Error adding rendered link: {:?}", e); } diff --git a/src/handlers/shortcut.rs b/src/handlers/shortcut.rs index 9f9584e9..f9a9e4c7 100644 --- a/src/handlers/shortcut.rs +++ b/src/handlers/shortcut.rs @@ -20,7 +20,7 @@ pub(super) async fn handle_command( // NOTE: if shortcuts available to issues are created, they need to be allowed here if !issue.is_pr() { let msg = format!("The \"{:?}\" shortcut only works on pull requests.", input); - let cmnt = ErrorComment::new(&issue, msg); + let cmnt = ErrorComment::new(issue, msg); cmnt.post(&ctx.github).await?; return Ok(()); } diff --git a/src/handlers/types_planning_updates.rs b/src/handlers/types_planning_updates.rs index a6c9c0c4..54501184 100644 --- a/src/handlers/types_planning_updates.rs +++ b/src/handlers/types_planning_updates.rs @@ -6,7 +6,7 @@ use async_trait::async_trait; use chrono::{Datelike, Duration, NaiveTime, TimeZone, Utc}; use serde::{Deserialize, Serialize}; -const TYPES_REPO: &'static str = "rust-lang/types-team"; +const TYPES_REPO: &str = "rust-lang/types-team"; // T-types/meetings const TYPES_MEETINGS_STREAM: u64 = 326132; @@ -27,10 +27,10 @@ impl Job for TypesPlanningMeetingThreadOpenJob { return Ok(()); } let meeting_date_string = first_monday.format("%Y-%m-%d").to_string(); - let message = format!("\ + let message = "\ Hello @*T-types/meetings*. Monthly planning meeting in one week.\n\ This is a reminder to update the current [roadmap tracking issues](https://github.com/rust-lang/types-team/issues?q=is%3Aissue+is%3Aopen+label%3Aroadmap-tracking-issue).\n\ - Extra reminders will be sent later this week."); + Extra reminders will be sent later this week.".to_string(); let zulip_req = crate::zulip::MessageApiRequest { recipient: crate::zulip::Recipient::Stream { id: TYPES_MEETINGS_STREAM, @@ -38,7 +38,7 @@ impl Job for TypesPlanningMeetingThreadOpenJob { }, content: &message, }; - zulip_req.send(&ctx.github.raw()).await?; + zulip_req.send(ctx.github.raw()).await?; // Then, we want to schedule the next Thursday after this let mut thursday = today; @@ -97,7 +97,7 @@ pub async fn request_updates( exclude_labels: vec![], }; let issues = types_repo - .get_issues(&gh, &tracking_issues_query) + .get_issues(gh, &tracking_issues_query) .await .with_context(|| "Unable to get issues.")?; @@ -164,7 +164,7 @@ pub async fn request_updates( }, content: &message, }; - zulip_req.send(&ctx.github.raw()).await?; + zulip_req.send(ctx.github.raw()).await?; Ok(()) } diff --git a/src/http_client/mod.rs b/src/http_client/mod.rs index 67418937..5c60e63f 100644 --- a/src/http_client/mod.rs +++ b/src/http_client/mod.rs @@ -51,8 +51,8 @@ impl HttpClient for CompilerMeeting { } }; let google_calendar_id = "6u5rrtce6lrtv07pfi3damgjus%40group.calendar.google.com"; - let time_min = format!("{}T00:00:00+00:00", start_date.format("%F").to_string()); - let time_max = format!("{}T23:59:59+00:00", end_date.format("%F").to_string()); + let time_min = format!("{}T00:00:00+00:00", start_date.format("%F")); + let time_max = format!("{}T23:59:59+00:00", end_date.format("%F")); let url = Url::parse_with_params( &format!( "https://www.googleapis.com/calendar/v3/calendars/{}/events", diff --git a/src/interactions.rs b/src/interactions.rs index f3d6a115..2f468712 100644 --- a/src/interactions.rs +++ b/src/interactions.rs @@ -153,16 +153,16 @@ impl<'a> EditIssueBody<'a> { let end_idx = start_idx + all_new.len(); current_body.replace_range(start_idx..end_idx, ""); } - self.issue.edit_body(&client, ¤t_body).await?; + self.issue.edit_body(client, ¤t_body).await?; } else { - let end_idx = current_body.find(&END_BOT).unwrap(); + let end_idx = current_body.find(END_BOT).unwrap(); current_body.insert_str(end_idx, &bot_section); - self.issue.edit_body(&client, ¤t_body).await?; + self.issue.edit_body(client, ¤t_body).await?; } } else { let new_body = format!("{}{}", current_body, all_new); - self.issue.edit_body(&client, &new_body).await?; + self.issue.edit_body(client, &new_body).await?; } Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index 629cf646..9ebefe57 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -123,7 +123,7 @@ impl From for WebhookError { } pub fn deserialize_payload(v: &str) -> anyhow::Result { - let mut deserializer = serde_json::Deserializer::from_str(&v); + let mut deserializer = serde_json::Deserializer::from_str(v); let res: Result = serde_path_to_error::deserialize(&mut deserializer); match res { Ok(r) => Ok(r), @@ -230,7 +230,7 @@ pub async fn webhook( return Ok(false); } }; - let errors = handlers::handle(&ctx, &event).await; + let errors = handlers::handle(ctx, &event).await; let mut other_error = false; let mut message = String::new(); for err in errors { diff --git a/src/main.rs b/src/main.rs index 9fa5dbf0..fb830bb2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -114,7 +114,7 @@ async fn serve_req( return Ok(Response::builder() .status(StatusCode::OK) .body(Body::from( - notification_listing::render(&ctx.db.get().await, &*name).await, + notification_listing::render(&ctx.db.get().await, &name).await, )) .unwrap()); } @@ -212,7 +212,7 @@ async fn serve_req( payload.extend_from_slice(&chunk); } - if let Err(_) = payload::assert_signed(signature, &payload) { + if payload::assert_signed(signature, &payload).is_err() { return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Wrong signature")) diff --git a/src/payload.rs b/src/payload.rs index f05e13a1..5e76efbc 100644 --- a/src/payload.rs +++ b/src/payload.rs @@ -14,7 +14,7 @@ impl std::error::Error for SignedPayloadError {} pub fn assert_signed(signature: &str, payload: &[u8]) -> Result<(), SignedPayloadError> { let signature = signature.get("sha1=".len()..).ok_or(SignedPayloadError)?; - let signature = match hex::decode(&signature) { + let signature = match hex::decode(signature) { Ok(e) => e, Err(e) => { tracing::trace!("hex decode failed for {:?}: {:?}", signature, e); @@ -29,7 +29,7 @@ pub fn assert_signed(signature: &str, payload: &[u8]) -> Result<(), SignedPayloa ) .unwrap(); let mut signer = Signer::new(MessageDigest::sha1(), &key).unwrap(); - signer.update(&payload).unwrap(); + signer.update(payload).unwrap(); let hmac = signer.sign_to_vec().unwrap(); if !memcmp::eq(&hmac, &signature) { diff --git a/src/rfcbot.rs b/src/rfcbot.rs index 93770a35..256e6472 100644 --- a/src/rfcbot.rs +++ b/src/rfcbot.rs @@ -62,7 +62,7 @@ pub struct FullFCP { } pub async fn get_all_fcps() -> anyhow::Result> { - let url = Url::parse(&"https://rfcbot.rs/api/all")?; + let url = Url::parse("https://rfcbot.rs/api/all")?; let res = reqwest::get(url).await?.json::>().await?; let mut map: HashMap = HashMap::new(); for full_fcp in res.into_iter() { diff --git a/src/zulip.rs b/src/zulip.rs index a158db50..0b73710a 100644 --- a/src/zulip.rs +++ b/src/zulip.rs @@ -139,7 +139,7 @@ fn handle_command<'a>( let mut next = words.next(); if let Some("as") = next { - return execute_for_other_user(&ctx, words, message_data) + return execute_for_other_user(ctx, words, message_data) .await .map_err(|e| { format_err!("Failed to parse; expected `as `: {e:?}.") @@ -148,13 +148,13 @@ fn handle_command<'a>( let gh_id = gh_id?; match next { - Some("acknowledge") | Some("ack") => acknowledge(&ctx, gh_id, words).await + Some("acknowledge") | Some("ack") => acknowledge(ctx, gh_id, words).await .map_err(|e| format_err!("Failed to parse acknowledgement, expected `(acknowledge|ack) `: {e:?}.")), - Some("add") => add_notification(&ctx, gh_id, words).await + Some("add") => add_notification(ctx, gh_id, words).await .map_err(|e| format_err!("Failed to parse description addition, expected `add `: {e:?}.")), - Some("move") => move_notification(&ctx, gh_id, words).await + Some("move") => move_notification(ctx, gh_id, words).await .map_err(|e| format_err!("Failed to parse movement, expected `move `: {e:?}.")), - Some("meta") => add_meta_notification(&ctx, gh_id, words).await + Some("meta") => add_meta_notification(ctx, gh_id, words).await .map_err(|e| format_err!("Failed to parse movement, expected `move `: {e:?}.")), _ => { while let Some(word) = next { @@ -162,7 +162,7 @@ fn handle_command<'a>( let next = words.next(); match next { Some("end-topic") | Some("await") => { - return post_waiter(&ctx, message_data, WaitingMessage::end_topic()) + return post_waiter(ctx, message_data, WaitingMessage::end_topic()) .await .map_err(|e| { format_err!("Failed to await at this time: {e:?}") @@ -170,7 +170,7 @@ fn handle_command<'a>( } Some("end-meeting") => { return post_waiter( - &ctx, + ctx, message_data, WaitingMessage::end_meeting(), ) @@ -179,7 +179,7 @@ fn handle_command<'a>( } Some("read") => { return post_waiter( - &ctx, + ctx, message_data, WaitingMessage::start_reading(), ) @@ -502,7 +502,7 @@ async fn acknowledge( Identifier::Url(filter) }; let mut db = ctx.db.get().await; - let deleted = delete_ping(&mut *db, gh_id, ident) + let deleted = delete_ping(&mut db, gh_id, ident) .await .map_err(|e| format_err!("Failed to acknowledge {filter}: {e:?}."))?; @@ -727,7 +727,7 @@ async fn post_waiter( message_id, emoji_name: reaction, } - .send(&ctx.github.raw()) + .send(ctx.github.raw()) .await .context("emoji reaction failed")?; }