From db8e4a7168a995483f143cc96ec00edc3532a741 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20H=E1=BB=93ng=20Qu=C3=A2n?= Date: Thu, 28 Sep 2023 11:27:48 +0700 Subject: [PATCH] Improve code per clippy advice --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + build.rs | 2 +- src/api/auth.rs | 2 +- src/api/errors.rs | 33 +++++++++++++++------------------ src/api/structs.rs | 28 ++++++++++++++-------------- src/conf.rs | 4 ++-- src/front/structs.rs | 2 +- src/front/views/feeds.rs | 13 +++++++------ src/models/feeds.rs | 2 +- src/stores/blog.rs | 19 ++++++++++--------- src/thingsup.rs | 4 ++-- src/types/mod.rs | 3 +-- src/utils/markdown.rs | 2 +- src/utils/mod.rs | 2 +- src/utils/urls.rs | 3 +-- 16 files changed, 66 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 67ed6f7..5b41bdc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2639,6 +2639,7 @@ dependencies = [ "serde_json", "serde_with", "smart-default", + "str-macro", "strum", "strum_macros", "syntect", @@ -3363,6 +3364,12 @@ dependencies = [ "lock_api", ] +[[package]] +name = "str-macro" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7514866270741c7b03dd36e2c68f71cf064b230e8217c81bbd4d619d564864" + [[package]] name = "string_cache" version = "0.8.7" diff --git a/Cargo.toml b/Cargo.toml index d13b9c4..79d1c40 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ serde-value = "0.7.0" serde_json = "1.0.99" serde_with = "3.0.0" smart-default = "0.7.1" +str-macro = "1.0.0" strum = { version = "0.25.0", features = ["derive", "strum_macros"] } strum_macros = "0.25.0" syntect = { version = "5.0.0", default-features = false, features = ["fancy-regex", "html"] } diff --git a/build.rs b/build.rs index 17f124b..e3c967f 100644 --- a/build.rs +++ b/build.rs @@ -6,7 +6,7 @@ fn main() { if env::var("PROFILE") == Ok("release".into()) { eprintln!("To build static files..."); Command::new("yarn") - .args(&["build-tailwind"]) + .args(["build-tailwind"]) .status() .expect("Failed to build static files!"); } diff --git a/src/api/auth.rs b/src/api/auth.rs index ecffb6c..3bc4556 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -32,7 +32,7 @@ pub async fn login( let resp: ApiErrorShape = "User not found".to_string().into(); (StatusCode::UNAUTHORIZED, Json(resp)) })?; - let passwd_check = check_password(&login_data.password.expose_secret(), &user.password) + let passwd_check = check_password(login_data.password.expose_secret(), &user.password) .map_err(|e| { tracing::error!("Error checking password: {:?}", e); ApiError::LoginError("Wrong password".into()) diff --git a/src/api/errors.rs b/src/api/errors.rs index a8080b1..57992c7 100644 --- a/src/api/errors.rs +++ b/src/api/errors.rs @@ -6,9 +6,9 @@ use axum::{response::IntoResponse, Json}; use edgedb_errors::display::display_error_verbose; use edgedb_errors::kinds as EdErrKind; use indexmap::IndexMap; +use serde_json::value::Value; use thiserror::Error; use validify::ValidationError as VE; -use serde_json::value::Value; use crate::types::ApiErrorShape; @@ -103,7 +103,7 @@ pub fn flatten_validation_errors( } => Some(( field, message - .or_else(|| deduce_message(code, params)) + .or_else(|| deduce_message(code, ¶ms)) .unwrap_or("Please check again".into()), )), }); @@ -111,23 +111,20 @@ pub fn flatten_validation_errors( hm } -pub fn deduce_message(code: &str, params: Box>) -> Option { +pub fn deduce_message(code: &str, params: &HashMap<&str, Value>) -> Option { if code == "url" { return Some("Must be a valid URL".into()); } - params - .get("min") - .map(|cond| { - params - .get("value") - .map(|input_value| { - if input_value.is_string() { - format!("Must be at least {cond} characters long") - } else { - format!("Must be at least {cond} elements") - } - }) - .or(Some(format!("Must be at least {cond}"))) - }) - .flatten() + params.get("min").and_then(|cond| { + params + .get("value") + .map(|input_value| { + if input_value.is_string() { + format!("Must be at least {cond} characters long") + } else { + format!("Must be at least {cond} elements") + } + }) + .or(Some(format!("Must be at least {cond}"))) + }) } diff --git a/src/api/structs.rs b/src/api/structs.rs index 39d6fe4..9f0a85a 100644 --- a/src/api/structs.rs +++ b/src/api/structs.rs @@ -64,7 +64,7 @@ pub struct BlogPostPatchData { } impl BlogPostPatchData { - pub fn gen_set_clause<'a>(&self, submitted_fields: &Vec<&String>) -> String { + pub fn gen_set_clause(&self, submitted_fields: &Vec<&String>) -> String { let mut lines = Vec::<&str>::new(); append_set_statement!("title", "optional str", lines, submitted_fields); append_set_statement!("slug", "optional str", lines, submitted_fields); @@ -88,7 +88,7 @@ impl BlogPostPatchData { lines.join(&format!(",\n{}", " ".repeat(8))) } - pub fn make_edgedb_object<'a>(&self, post_id: Uuid, submitted_fields: &Vec<&String>) -> EValue { + pub fn make_edgedb_object(&self, post_id: Uuid, submitted_fields: &Vec<&String>) -> EValue { let mut pairs = indexmap! { "id" => (Some(EValue::Uuid(post_id)), Cd::One), }; @@ -176,7 +176,7 @@ pub struct BlogPostCreateData { } impl BlogPostCreateData { - pub fn gen_set_clause<'a>(&self, submitted_fields: &Vec<&String>) -> String { + pub fn gen_set_clause(&self, submitted_fields: &Vec<&String>) -> String { let mut lines = vec!["title := $title", "slug := $slug"]; append_set_statement!("is_published", "optional bool", lines, submitted_fields); if submitted_fields.contains("body") { @@ -199,7 +199,7 @@ impl BlogPostCreateData { lines.join(&sep) } - pub fn make_edgedb_object<'a>(&self, submitted_fields: &Vec<&String>) -> EValue { + pub fn make_edgedb_object(&self, submitted_fields: &Vec<&String>) -> EValue { let mut pairs = indexmap! { "title" => (Some(EValue::Str(self.title.clone())), Cd::One), "slug" => (Some(EValue::Str(self.slug.clone())), Cd::One), @@ -266,7 +266,7 @@ pub struct BlogCategoryPatchData { } impl BlogCategoryPatchData { - pub fn gen_set_clause<'a>(&self, submitted_fields: &Vec<&String>) -> String { + pub fn gen_set_clause(&self, submitted_fields: &[&String]) -> String { let mut lines = Vec::<&str>::new(); append_set_statement!("title", "optional str", lines, submitted_fields); append_set_statement!("slug", "optional str", lines, submitted_fields); @@ -274,7 +274,7 @@ impl BlogCategoryPatchData { lines.join(&sep) } - pub fn make_edgedb_object<'a>(&self, id: Uuid, submitted_fields: &Vec<&String>) -> EValue { + pub fn make_edgedb_object(&self, id: Uuid, submitted_fields: &Vec<&String>) -> EValue { let mut pairs = indexmap!( "id" => (Some(EValue::Uuid(id)), Cd::One), ); @@ -303,13 +303,13 @@ pub struct BlogCategoryCreateData { } impl BlogCategoryCreateData { - pub fn gen_set_clause<'a>(&self) -> String { - let lines = vec!["title := $title", "slug := $slug"]; + pub fn gen_set_clause(&self) -> String { + let lines = ["title := $title", "slug := $slug"]; let sep = format!(",\n{}", " ".repeat(12)); lines.join(&sep) } - pub fn make_edgedb_object<'a>(&self) -> EValue { + pub fn make_edgedb_object(&self) -> EValue { let pairs = indexmap! { "title" => Some(EValue::from(self.title.clone())), "slug" => Some(EValue::from(self.slug.clone())), @@ -326,7 +326,7 @@ pub struct PresentationPatchData { } impl PresentationPatchData { - pub fn gen_set_clause<'a>(&self, submitted_fields: &Vec<&String>) -> String { + pub fn gen_set_clause(&self, submitted_fields: &[&String]) -> String { let mut lines = Vec::<&str>::new(); append_set_statement!("title", "optional str", lines, submitted_fields); append_set_statement!("url", "optional str", lines, submitted_fields); @@ -335,7 +335,7 @@ impl PresentationPatchData { lines.join(&sep) } - pub fn make_edgedb_object<'a>(&self, id: Uuid, submitted_fields: &Vec<&String>) -> EValue { + pub fn make_edgedb_object(&self, id: Uuid, submitted_fields: &Vec<&String>) -> EValue { let mut pairs = indexmap!( "id" => (Some(EValue::Uuid(id)), Cd::One), ); @@ -373,7 +373,7 @@ pub struct PresentationCreateData { impl PresentationCreateData { pub fn gen_set_clause(&self) -> String { - let lines = vec![ + let lines = [ "title := $title", "url := $url", "event := $event", @@ -408,7 +408,7 @@ pub struct BookPatchData { } impl BookPatchData { - pub fn gen_set_clause<'a>(&self, submitted_fields: &Vec<&String>) -> String { + pub fn gen_set_clause(&self, submitted_fields: &Vec<&String>) -> String { let mut lines = Vec::<&str>::new(); append_set_statement!("title", "optional str", lines, submitted_fields); append_set_statement!("download_url", "optional str", lines, submitted_fields); @@ -422,7 +422,7 @@ impl BookPatchData { lines.join(&sep) } - pub fn make_edgedb_object<'a>(&self, id: Uuid, submitted_fields: &Vec<&String>) -> EValue { + pub fn make_edgedb_object(&self, id: Uuid, submitted_fields: &Vec<&String>) -> EValue { let mut pairs = indexmap!( "id" => (Some(EValue::Uuid(id)), Cd::One), ); diff --git a/src/conf.rs b/src/conf.rs index 9d7ce2d..eb7daba 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -3,7 +3,7 @@ use miette::{miette, Report}; use config::{Config, ConfigError, File}; -pub const KEY_SECRET: &'static str = "secret_key"; +pub const KEY_SECRET: &str = "secret_key"; pub const KEY_EDGEDB_INSTANCE: &str = "edgedb_instance"; pub const KEY_PORT: &str = "port"; pub const DEFAULT_PORT: u16 = 3721; @@ -12,7 +12,7 @@ pub const ALPHANUMERIC: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV pub fn gen_fallback_secret() -> String { let pool: Pool = ALPHANUMERIC.parse().unwrap_or_default(); // 64 is the secret bytes count required by axum-sessions - generate_password(&pool, 64).into() + generate_password(&pool, 64) } pub fn get_config() -> Result { diff --git a/src/front/structs.rs b/src/front/structs.rs index a2175a3..f1710ed 100644 --- a/src/front/structs.rs +++ b/src/front/structs.rs @@ -17,7 +17,7 @@ impl LaxPaging { /// The type is NonZeroU16 because our website is small enough for page number /// to be fit in u16. pub fn get_page_as_number(&self) -> NonZeroU16 { - self.page.as_deref().map(|s| s.parse().ok()).flatten().unwrap_or(NonZeroU16::MIN) + self.page.as_deref().and_then(|s| s.parse().ok()).unwrap_or(NonZeroU16::MIN) } } diff --git a/src/front/views/feeds.rs b/src/front/views/feeds.rs index fc17d73..25cc8e8 100644 --- a/src/front/views/feeds.rs +++ b/src/front/views/feeds.rs @@ -61,8 +61,7 @@ pub async fn gen_atom_feeds( .await .map_err(PageError::EdgeDBQueryError)?; let updated_at = latest_post - .map(|p| p.updated_at.map(|d| d.into())) - .flatten() + .and_then(|p| p.updated_at.map(|d| d.into())) .unwrap_or_else(|| Utc.with_ymd_and_hms(2013, 1, 1, 0, 0, 0).unwrap()); let feed = FeedBuilder::default() .title("QuanWeb") @@ -98,13 +97,15 @@ pub async fn gen_json_feeds( total_pages, }; let next_page_url = paginator.next_url(¤t_url); - let mut feed = JsonFeed::default(); - feed.feed_url = Some(format!("{base_url}{current_url}")); - feed.next_url = next_page_url.map(|url| format!("{base_url}{url}")); + let mut feed = JsonFeed { + feed_url: Some(format!("{base_url}{current_url}")), + next_url: next_page_url.map(|url| format!("{base_url}{url}")), + ..Default::default() + }; let mut items: Vec = posts.into_iter().map(JsonItem::from).collect(); items.iter_mut().for_each(|it| { match it.url { - Some(ref url) if url.starts_with("/") => { + Some(ref url) if url.starts_with('/') => { it.url = Some(format!("{base_url}{url}")); } _ => {} diff --git a/src/models/feeds.rs b/src/models/feeds.rs index 7da1f32..648615a 100644 --- a/src/models/feeds.rs +++ b/src/models/feeds.rs @@ -68,7 +68,7 @@ impl EntryExt for Entry { fn prepend_url(&mut self, base_url: &Uri) { self.links.iter_mut().for_each(|u| { let old_url = u.href(); - if old_url.starts_with("/") { + if old_url.starts_with('/') { u.set_href(base_url.join(old_url).to_string()); } }); diff --git a/src/stores/blog.rs b/src/stores/blog.rs index e97450d..34f3253 100644 --- a/src/stores/blog.rs +++ b/src/stores/blog.rs @@ -1,3 +1,4 @@ +use str_macro::str; use edgedb_protocol::common::Cardinality as Cd; use edgedb_protocol::model::Datetime as EDatetime; use edgedb_protocol::value::Value as EValue; @@ -81,16 +82,16 @@ pub async fn get_blogposts( let mut pairs = IndexMap::with_capacity(3); let mut paging_lines: Vec = Vec::with_capacity(2); if let Some(ss) = lower_search_tokens { - let search: Vec = ss.into_iter().map(|s| EValue::Str(s.into())).collect(); + let search: Vec = ss.iter().map(|s| EValue::Str(s.into())).collect(); pairs.insert("tokens", (Some(EValue::Array(search)), Cd::One)); } if let Some(offset) = offset { pairs.insert("offset", (Some(EValue::Int64(offset)), Cd::One)); - paging_lines.push(format!("OFFSET $offset")); + paging_lines.push(str!("OFFSET $offset")); } if let Some(limit) = limit { pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One)); - paging_lines.push(format!("LIMIT $limit")); + paging_lines.push(str!("LIMIT $limit")); } let paging_expr = paging_lines.join(" "); let fields = MediumBlogPost::fields_as_shape(); @@ -115,11 +116,11 @@ pub async fn get_published_posts( let mut paging_lines: Vec = Vec::with_capacity(2); if let Some(offset) = offset { pairs.insert("offset", (Some(EValue::Int64(offset)), Cd::One)); - paging_lines.push(format!("OFFSET $offset")); + paging_lines.push(str!("OFFSET $offset")); } if let Some(limit) = limit { pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One)); - paging_lines.push(format!("LIMIT $limit")); + paging_lines.push(str!("LIMIT $limit")); } let paging_expr = paging_lines.join(" "); let fields = MediumBlogPost::fields_as_shape(); @@ -152,11 +153,11 @@ pub async fn get_published_posts_under_category( } if let Some(offset) = offset { pairs.insert("offset", (Some(EValue::Int64(offset)), Cd::One)); - paging_lines.push(format!("OFFSET $offset")); + paging_lines.push(str!("OFFSET $offset")); } if let Some(limit) = limit { pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One)); - paging_lines.push(format!("LIMIT $limit")); + paging_lines.push(str!("LIMIT $limit")); } let filter_expr = filter_lines.join(" AND "); let paging_expr = paging_lines.join(" "); @@ -190,11 +191,11 @@ pub async fn get_published_uncategorized_blogposts( let mut paging_lines: Vec = Vec::with_capacity(2); if let Some(offset) = offset { pairs.insert("offset", (Some(EValue::Int64(offset)), Cd::One)); - paging_lines.push(format!("OFFSET $offset")); + paging_lines.push(str!("OFFSET $offset")); } if let Some(limit) = limit { pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One)); - paging_lines.push(format!("LIMIT $limit")); + paging_lines.push(str!("LIMIT $limit")); } let paging_expr = paging_lines.join(" "); let fields = MediumBlogPost::fields_as_shape(); diff --git a/src/thingsup.rs b/src/thingsup.rs index 28a843d..c4b6871 100644 --- a/src/thingsup.rs +++ b/src/thingsup.rs @@ -89,8 +89,8 @@ pub fn get_listening_addr() -> [u8; 4] { } } -pub fn get_binding_addr<'a>(bind_opt: &'a str) -> Result { - if bind_opt.contains(":") { +pub fn get_binding_addr(bind_opt: &str) -> Result { + if bind_opt.contains(':') { bind_opt.parse::() } else { let auto_addr = format!("127.0.0.1:{bind_opt}"); diff --git a/src/types/mod.rs b/src/types/mod.rs index d0332b2..43a4cb8 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -84,8 +84,7 @@ where let mime = mime_guess::from_path(path).first_or_octet_stream(); let last_modified = file.metadata.last_modified(); let last_modified: DateTime = last_modified - .map(|t| UNIX_EPOCH.checked_add(Duration::from_secs(t))) - .flatten() + .and_then(|t| UNIX_EPOCH.checked_add(Duration::from_secs(t))) .unwrap_or(SystemTime::now()) .into(); let headers = [ diff --git a/src/utils/markdown.rs b/src/utils/markdown.rs index 1d57cfa..077c658 100644 --- a/src/utils/markdown.rs +++ b/src/utils/markdown.rs @@ -25,7 +25,7 @@ impl CssSyntectAdapter { SYNTECT_CLASS_STYLE, ); for line in LinesWithEndings::from(code) { - html_generator.parse_html_for_line_which_includes_newline(&line)?; + html_generator.parse_html_for_line_which_includes_newline(line)?; } Ok(html_generator.finalize()) } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 61d2c6b..d1b6baa 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -3,7 +3,7 @@ pub mod markdown; pub mod html; pub mod jinja_extra; -pub fn split_search_query<'a>(query: Option<&'a str>) -> Option> { +pub fn split_search_query(query: Option<&str>) -> Option> { let tokens: Option> = query.map(|s| s.split_whitespace().filter(|&s| !s.is_empty()).collect()); tokens.and_then(|v| if v.is_empty() { None } else { Some(v) }) } diff --git a/src/utils/urls.rs b/src/utils/urls.rs index 2d41d1b..3726d76 100644 --- a/src/utils/urls.rs +++ b/src/utils/urls.rs @@ -5,8 +5,7 @@ use std::fmt::Display; pub fn update_entry_in_query(name: &str, value: T, original_uri: &Uri) -> Uri { let mut query = original_uri .query() - .map(|s| QueryString::decode(s.as_bytes()).ok()) - .flatten() + .and_then(|s| QueryString::decode(s.as_bytes()).ok()) .unwrap_or(QueryString::new()); query.set(name, format!("{value}")); let path = original_uri.path();