Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make TabletBot pass most clippy::pedantic lints #30

Merged
merged 4 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub async fn respond_embed(ctx: &Context<'_>, embed: CreateEmbed, ephemeral: boo
let result = ctx.send(builder).await;

if let Err(e) = result {
println!("Failed to respond: {}", e)
println!("Failed to respond: {e}");
}
}

Expand Down Expand Up @@ -70,8 +70,8 @@ pub async fn paginate_lists<U, E>(
embed_title: &str,
) -> Result<(), Error> {
let ctx_id = ctx.id();
let prev_button_id = format!("{}prev", ctx_id);
let next_button_id = format!("{}next", ctx_id);
let prev_button_id = format!("{ctx_id}prev");
let next_button_id = format!("{ctx_id}next");

let colour = Colour::TEAL;

Expand Down
30 changes: 16 additions & 14 deletions src/commands/snippets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use poise::serenity_prelude::{
CreateInteractionResponseMessage,
};

#[allow(clippy::unused_async)]
async fn autocomplete_snippet<'a>(
ctx: Context<'a>,
partial: &'a str,
Expand Down Expand Up @@ -40,7 +41,7 @@ pub async fn snippet(
id: String,
) -> Result<(), Error> {
// Lazily get snippet because this is a prefix command too.
if let Some(snippet) = get_snippet_lazy(&ctx, &id).await {
if let Some(snippet) = get_snippet_lazy(&ctx, &id) {
let embed = snippet.embed();

respond_embed(&ctx, embed, false).await;
Expand Down Expand Up @@ -78,6 +79,7 @@ pub async fn create_snippet(
};

println!("New snippet created '{}: {}'", snippet.id, snippet.title);

let mut embed = snippet.embed();

embed = embed.colour(super::OK_COLOUR);
Expand Down Expand Up @@ -111,7 +113,7 @@ pub async fn edit_snippet(
#[description = "The snippet's title"] title: Option<String>,
#[description = "The snippet's content"] content: Option<String>,
) -> Result<(), Error> {
match get_snippet_lazy(&ctx, &id).await {
match get_snippet_lazy(&ctx, &id) {
Some(mut snippet) => {
if let Some(title) = title {
snippet.title = title;
Expand All @@ -134,7 +136,7 @@ pub async fn edit_snippet(
None => {
let title = &"Failed to edit snippet";
let content = &&format!("The snippet '{id}' does not exist");
respond_err(&ctx, title, content).await
respond_err(&ctx, title, content).await;
}
};

Expand All @@ -149,14 +151,14 @@ pub async fn remove_snippet(
#[description = "The snippet's id"]
id: String,
) -> Result<(), Error> {
match get_snippet_lazy(&ctx, &id).await {
match get_snippet_lazy(&ctx, &id) {
Some(snippet) => {
remove_snippet_confirm(&ctx, &snippet).await?;
}
None => {
let title = &"Failed to remove snippet";
let content = &&format!("The snippet '{id}' does not exist");
respond_err(&ctx, title, content).await
respond_err(&ctx, title, content).await;
}
}

Expand Down Expand Up @@ -190,7 +192,7 @@ pub async fn list_snippets(ctx: Context<'_>) -> Result<(), Error> {
.map(|snippet| (snippet.id.clone(), snippet.title.clone(), true))
.collect::<Vec<(String, String, bool)>>()
.chunks(25)
.map(|chunk| chunk.to_vec())
.map(<[(String, String, bool)]>::to_vec)
.collect();

super::paginate_lists(ctx, &pages, "Snippets").await?;
Expand All @@ -209,7 +211,7 @@ pub async fn export_snippet(
#[description = "The snippet's id"]
id: String,
) -> Result<(), Error> {
match get_snippet_lazy(&ctx, &id).await {
match get_snippet_lazy(&ctx, &id) {
Some(snippet) => {
let attachment =
CreateAttachment::bytes(snippet.content.replace('\n', r"\n"), "snippet.txt");
Expand All @@ -221,7 +223,7 @@ pub async fn export_snippet(
None => {
let title = &"Failed to export snippet";
let content = &&format!("The snippet '{id}' does not exist");
respond_err(&ctx, title, content).await
respond_err(&ctx, title, content).await;
}
}

Expand All @@ -239,7 +241,7 @@ impl Embeddable for Snippet {
}

// Exact matches the snippet id and name.
async fn _get_snippet(ctx: &Context<'_>, id: &str) -> Option<Snippet> {
fn _get_snippet(ctx: &Context<'_>, id: &str) -> Option<Snippet> {
let data = ctx.data();
let rwlock_guard = data.state.read().unwrap();

Expand All @@ -251,7 +253,7 @@ async fn _get_snippet(ctx: &Context<'_>, id: &str) -> Option<Snippet> {
}

// Matches the snippet by checking if its starts with the id and name.
async fn get_snippet_lazy(ctx: &Context<'_>, id: &str) -> Option<Snippet> {
fn get_snippet_lazy(ctx: &Context<'_>, id: &str) -> Option<Snippet> {
let data = ctx.data();
let rwlock_guard = data.state.read().unwrap();

Expand All @@ -262,7 +264,7 @@ async fn get_snippet_lazy(ctx: &Context<'_>, id: &str) -> Option<Snippet> {
.cloned()
}

async fn rm_snippet(ctx: &Context<'_>, snippet: &Snippet) {
fn rm_snippet(ctx: &Context<'_>, snippet: &Snippet) {
let data = ctx.data();
let mut rwlock_guard = data.state.write().unwrap();

Expand All @@ -281,8 +283,8 @@ async fn remove_snippet_confirm(ctx: &Context<'_>, snippet: &Snippet) -> Result<
let snippet_embed = snippet.embed();

let ctx_id = ctx.id();
let delete_id = format!("{}cancel", ctx_id);
let cancel_id = format!("{}delete", ctx_id);
let delete_id = format!("{ctx_id}cancel");
let cancel_id = format!("{ctx_id}delete");

let components = serenity::CreateActionRow::Buttons(vec![
serenity::CreateButton::new(&cancel_id).label("Cancel"),
Expand Down Expand Up @@ -322,7 +324,7 @@ async fn handle_delete(
snippet: &Snippet,
interaction: serenity::ComponentInteraction,
) -> Result<(), Error> {
rm_snippet(ctx, snippet).await;
rm_snippet(ctx, snippet);
interaction
.create_response(
ctx,
Expand Down
25 changes: 13 additions & 12 deletions src/commands/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use poise::serenity_prelude::{Colour, CreateEmbed, CreateEmbedFooter, EditMessag
use regex::Regex;
use serenity::futures::{self, Stream, StreamExt};

#[allow(clippy::unused_async)]
async fn autocomplete_key<'a>(
ctx: Context<'a>,
partial: &'a str,
Expand Down Expand Up @@ -63,7 +64,7 @@ pub async fn embed(
match url.parse::<reqwest::Url>() {
Ok(_) => {
if title.is_some() {
embed = embed.url(url)
embed = embed.url(url);
} else {
respond_err(
&ctx,
Expand All @@ -76,7 +77,7 @@ pub async fn embed(
}
Err(e) => {
let title = "Invalid url provided";
let content = &format!("The url '{}' is not a valid url: {}", url, e);
let content = &format!("The url '{url}' is not a valid url: {e}");
respond_err(&ctx, title, content).await;
return Ok(());
}
Expand Down Expand Up @@ -229,7 +230,7 @@ pub async fn edit_embed(
let builder = EditMessage::default().embed(embedb);

match msg_clone.edit(ctx, builder).await {
Ok(_) => {
Ok(()) => {
respond_ok(
&ctx,
"Successfully edited embed",
Expand All @@ -239,7 +240,7 @@ pub async fn edit_embed(
}
Err(error) => {
// Better error handling later.
respond_err(&ctx, "Error while handling message!", &format!("{}", error)).await
respond_err(&ctx, "Error while handling message!", &format!("{error}")).await;
}
}
} else {
Expand Down Expand Up @@ -313,7 +314,7 @@ pub async fn add_repo(
respond_ok(
&ctx,
"Successfully added issue token",
&format!("{}: {}/{}", key, owner, repository),
&format!("{key}: {owner}/{repository}"),
)
.await;

Expand All @@ -333,16 +334,16 @@ pub async fn remove_repo(
// impl a solution directly into the types?

// not sure why I have to do this, it won't settle otherwise.
let key_str = format!("The repository with the key '{}' has been removed", key);
match get_repo_details(&ctx, &key).await {
let key_str = format!("The repository with the key '{key}' has been removed");
match get_repo_details(&ctx, &key) {
Some(_) => {
rm_repo(&ctx, &key).await;
rm_repo(&ctx, &key);

respond_ok(&ctx, "Successfully removed repository!", &key_str).await;
}
None => {
let title = "Failure to find repository";
let content = format!("The key '{}' does not exist.", key);
let content = format!("The key '{key}' does not exist.");
respond_err(&ctx, title, &content).await;
}
};
Expand Down Expand Up @@ -383,22 +384,22 @@ pub async fn list_repos(ctx: Context<'_>) -> Result<(), Error> {
})
.collect::<Vec<(String, String, bool)>>()
.chunks(25)
.map(|chunk| chunk.to_vec())
.map(<[(String, String, bool)]>::to_vec)
.collect();

super::paginate_lists(ctx, &pages, "Repositories").await?;

Ok(())
}

async fn get_repo_details(ctx: &Context<'_>, key: &str) -> Option<RepositoryDetails> {
fn get_repo_details(ctx: &Context<'_>, key: &str) -> Option<RepositoryDetails> {
let data = ctx.data();
let rwlock_guard = data.state.read().unwrap();

rwlock_guard.issue_prefixes.get(key).cloned()
}

async fn rm_repo(ctx: &Context<'_>, key: &str) {
fn rm_repo(ctx: &Context<'_>, key: &str) {
let data = ctx.data();
let mut rwlock_guard = data.state.write().unwrap();

Expand Down
20 changes: 10 additions & 10 deletions src/events/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ async fn get_embeds(ctx: &Context, message: &Message) -> Option<Vec<CreateEmbed>

typing.stop();

if !embeds.is_empty() {
Some(embeds)
} else {
if embeds.is_empty() {
None
} else {
Some(embeds)
}
}

Expand All @@ -47,12 +47,12 @@ async fn http_get_body_text(url: &String) -> Option<String> {
Ok(res) => match res.text().await {
Ok(content) => Some(content),
Err(e) => {
println!("Failed to get text: {}", e);
println!("Failed to get text: {e}");
None
}
},
Err(e) => {
println!("Failed to get response: {}", e);
println!("Failed to get response: {e}");
None
}
}
Expand Down Expand Up @@ -95,10 +95,10 @@ impl FileReference<'_> {
})
.collect();

if !files.is_empty() {
Some(files)
} else {
if files.is_empty() {
None
} else {
Some(files)
}
}

Expand All @@ -108,7 +108,7 @@ impl FileReference<'_> {
if let Some(mut content) = self.display().await {
content.shrink_to(4096 - 8 - extension.len());

let description = format!("```{}\n{}\n```", extension, content);
let description = format!("```{extension}\n{content}\n```");

let mut default = CreateEmbed::default();
default = default
Expand All @@ -135,7 +135,7 @@ impl FileReference<'_> {
"https://raw.githubusercontent.com/{}/{}/{}/{}",
self.owner, self.repo, self.git_ref, self.path
);
println!("Downloading content: {}", url);
println!("Downloading content: {url}");

if let Some(content) = http_get_body_text(&url).await {
let lines: Vec<&str> = content.split('\n').collect();
Expand Down
18 changes: 9 additions & 9 deletions src/events/issue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ pub async fn message(data: &Data, ctx: &Context, message: &Message) {
let typing = message.channel_id.start_typing(&ctx.http);

let ctx_id = message.id.get(); // poise context isn't available here.
let remove_id = format!("{}remove", ctx_id);
let hide_body_id = format!("{}hide_body", ctx_id);
let remove_id = format!("{ctx_id}remove");
let hide_body_id = format!("{ctx_id}hide_body");
let remove = CreateActionRow::Buttons(vec![CreateButton::new(&remove_id)
.label("delete")
.style(ButtonStyle::Danger)]);
Expand Down Expand Up @@ -124,7 +124,7 @@ async fn issue_embeds(data: &Data, message: &Message) -> Option<Vec<CreateEmbed>
let client = octocrab::instance();
let ratelimit = client.ratelimit();

let regex = Regex::new(r#" ?([a-zA-Z0-9-_.]+)?#([0-9]+) ?"#).expect("Expected numbers regex");
let regex = Regex::new(r" ?([a-zA-Z0-9-_.]+)?#([0-9]+) ?").expect("Expected numbers regex");

let custom_repos = { data.state.read().unwrap().issue_prefixes.clone() };

Expand Down Expand Up @@ -211,7 +211,7 @@ impl Document for Issue {

let mut description = String::default();
for line in body.split('\n').take(15) {
description.push_str(&format!("{}\n", line));
description.push_str(&format!("{line}\n"));
}

description.shrink_to(4096);
Expand All @@ -226,16 +226,16 @@ impl Document for Issue {
}

fn get_labels(&self) -> Option<String> {
if !self.labels.is_empty() {
if self.labels.is_empty() {
None
} else {
let labels = &self
.labels
.iter()
.map(|l| l.name.clone())
.collect::<Vec<String>>();

Some(format!("`{}`", labels.join("`, `")))
} else {
None
}
}
}
Expand Down Expand Up @@ -270,7 +270,7 @@ impl Embeddable for PullRequest {
embed = embed.field("Labels", labels, true);
}

embed.to_owned()
embed
}
}

Expand All @@ -287,7 +287,7 @@ impl Document for PullRequest {

let mut content = String::default();
for line in body.split('\n').take(15) {
content.push_str(&format!("{}\n", line));
content.push_str(&format!("{line}\n"));
}

content.shrink_to(4096);
Expand Down
2 changes: 1 addition & 1 deletion src/formatting.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub fn trim_indent(lines: &[&str]) -> String {
let base_indent = get_base_indent(lines);
let prefix = String::from_iter(std::iter::repeat(' ').take(base_indent));
let prefix = " ".repeat(base_indent);

let trimmed_lines: Vec<&str> = lines
.iter()
Expand Down
Loading