Skip to content

Commit

Permalink
Improve code per clippy advice
Browse files Browse the repository at this point in the history
  • Loading branch information
hongquan committed Sep 28, 2023
1 parent d5ddf48 commit db8e4a7
Show file tree
Hide file tree
Showing 16 changed files with 66 additions and 61 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
2 changes: 1 addition & 1 deletion build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!");
}
Expand Down
2 changes: 1 addition & 1 deletion src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
33 changes: 15 additions & 18 deletions src/api/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -103,31 +103,28 @@ pub fn flatten_validation_errors(
} => Some((
field,
message
.or_else(|| deduce_message(code, params))
.or_else(|| deduce_message(code, &params))
.unwrap_or("Please check again".into()),
)),
});
hm.extend(field_errors);
hm
}

pub fn deduce_message(code: &str, params: Box<HashMap<&str, Value>>) -> Option<String> {
pub fn deduce_message(code: &str, params: &HashMap<&str, Value>) -> Option<String> {
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}")))
})
}
28 changes: 14 additions & 14 deletions src/api/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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),
};
Expand Down Expand Up @@ -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 := <str>$title", "slug := <str>$slug"];
append_set_statement!("is_published", "optional bool", lines, submitted_fields);
if submitted_fields.contains("body") {
Expand All @@ -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),
Expand Down Expand Up @@ -266,15 +266,15 @@ 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);
let sep = format!(",\n{}", " ".repeat(12));
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),
);
Expand Down Expand Up @@ -303,13 +303,13 @@ pub struct BlogCategoryCreateData {
}

impl BlogCategoryCreateData {
pub fn gen_set_clause<'a>(&self) -> String {
let lines = vec!["title := <str>$title", "slug := <str>$slug"];
pub fn gen_set_clause(&self) -> String {
let lines = ["title := <str>$title", "slug := <str>$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())),
Expand All @@ -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);
Expand All @@ -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),
);
Expand Down Expand Up @@ -373,7 +373,7 @@ pub struct PresentationCreateData {

impl PresentationCreateData {
pub fn gen_set_clause(&self) -> String {
let lines = vec![
let lines = [
"title := <str>$title",
"url := <str>$url",
"event := <optional str>$event",
Expand Down Expand Up @@ -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);
Expand All @@ -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),
);
Expand Down
4 changes: 2 additions & 2 deletions src/conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Config, ConfigError> {
Expand Down
2 changes: 1 addition & 1 deletion src/front/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
13 changes: 7 additions & 6 deletions src/front/views/feeds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -98,13 +97,15 @@ pub async fn gen_json_feeds(
total_pages,
};
let next_page_url = paginator.next_url(&current_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<JsonItem> = 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}"));
}
_ => {}
Expand Down
2 changes: 1 addition & 1 deletion src/models/feeds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
});
Expand Down
19 changes: 10 additions & 9 deletions src/stores/blog.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -81,16 +82,16 @@ pub async fn get_blogposts(
let mut pairs = IndexMap::with_capacity(3);
let mut paging_lines: Vec<String> = Vec::with_capacity(2);
if let Some(ss) = lower_search_tokens {
let search: Vec<EValue> = ss.into_iter().map(|s| EValue::Str(s.into())).collect();
let search: Vec<EValue> = 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 <int64>$offset"));
paging_lines.push(str!("OFFSET <int64>$offset"));
}
if let Some(limit) = limit {
pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One));
paging_lines.push(format!("LIMIT <int64>$limit"));
paging_lines.push(str!("LIMIT <int64>$limit"));
}
let paging_expr = paging_lines.join(" ");
let fields = MediumBlogPost::fields_as_shape();
Expand All @@ -115,11 +116,11 @@ pub async fn get_published_posts(
let mut paging_lines: Vec<String> = Vec::with_capacity(2);
if let Some(offset) = offset {
pairs.insert("offset", (Some(EValue::Int64(offset)), Cd::One));
paging_lines.push(format!("OFFSET <int64>$offset"));
paging_lines.push(str!("OFFSET <int64>$offset"));
}
if let Some(limit) = limit {
pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One));
paging_lines.push(format!("LIMIT <int64>$limit"));
paging_lines.push(str!("LIMIT <int64>$limit"));
}
let paging_expr = paging_lines.join(" ");
let fields = MediumBlogPost::fields_as_shape();
Expand Down Expand Up @@ -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 <int64>$offset"));
paging_lines.push(str!("OFFSET <int64>$offset"));
}
if let Some(limit) = limit {
pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One));
paging_lines.push(format!("LIMIT <int64>$limit"));
paging_lines.push(str!("LIMIT <int64>$limit"));
}
let filter_expr = filter_lines.join(" AND ");
let paging_expr = paging_lines.join(" ");
Expand Down Expand Up @@ -190,11 +191,11 @@ pub async fn get_published_uncategorized_blogposts(
let mut paging_lines: Vec<String> = Vec::with_capacity(2);
if let Some(offset) = offset {
pairs.insert("offset", (Some(EValue::Int64(offset)), Cd::One));
paging_lines.push(format!("OFFSET <int64>$offset"));
paging_lines.push(str!("OFFSET <int64>$offset"));
}
if let Some(limit) = limit {
pairs.insert("limit", (Some(EValue::Int64(limit)), Cd::One));
paging_lines.push(format!("LIMIT <int64>$limit"));
paging_lines.push(str!("LIMIT <int64>$limit"));
}
let paging_expr = paging_lines.join(" ");
let fields = MediumBlogPost::fields_as_shape();
Expand Down
4 changes: 2 additions & 2 deletions src/thingsup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ pub fn get_listening_addr() -> [u8; 4] {
}
}

pub fn get_binding_addr<'a>(bind_opt: &'a str) -> Result<SocketAddr, AddrParseError> {
if bind_opt.contains(":") {
pub fn get_binding_addr(bind_opt: &str) -> Result<SocketAddr, AddrParseError> {
if bind_opt.contains(':') {
bind_opt.parse::<SocketAddr>()
} else {
let auto_addr = format!("127.0.0.1:{bind_opt}");
Expand Down
3 changes: 1 addition & 2 deletions src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Utc> = 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 = [
Expand Down
2 changes: 1 addition & 1 deletion src/utils/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<&str>> {
pub fn split_search_query(query: Option<&str>) -> Option<Vec<&str>> {
let tokens: Option<Vec<&str>> = query.map(|s| s.split_whitespace().filter(|&s| !s.is_empty()).collect());
tokens.and_then(|v| if v.is_empty() { None } else { Some(v) })
}
Loading

0 comments on commit db8e4a7

Please sign in to comment.