refactor: apply clippy tips

This commit is contained in:
Max Hohlfeld 2025-01-29 14:08:27 +01:00
parent 6a70345b88
commit ec5e4cc23d
30 changed files with 85 additions and 113 deletions

View File

@ -64,12 +64,8 @@ pub fn load_config(env: &Environment) -> Result<Config, anyhow::Error> {
hostname: env::var("HOSTNAME")?,
smtp_server: env::var("SMTP_SERVER")?,
smtp_port: env::var("SMTP_PORT")?.parse()?,
smtp_login: env::var("SMTP_LOGIN")
.and_then(|x| Ok(Some(x)))
.unwrap_or(None),
smtp_password: env::var("SMTP_PASSWORD")
.and_then(|x| Ok(Some(x)))
.unwrap_or(None),
smtp_login: env::var("SMTP_LOGIN").map(Some).unwrap_or(None),
smtp_password: env::var("SMTP_PASSWORD").map(Some).unwrap_or(None),
smtp_tlstype: SmtpTlsType::from(env::var("SMTP_TLSTYPE")?),
};

View File

@ -27,7 +27,7 @@ pub async fn delete(
Area::delete(pool.get_ref(), path.id).await?;
return Ok(HttpResponse::Ok().finish());
Ok(HttpResponse::Ok().finish())
}
#[db_test]

View File

@ -24,8 +24,8 @@ async fn get(
area: Some(area_in_db),
};
return Ok(HttpResponse::Ok().body(template.render()?))
Ok(HttpResponse::Ok().body(template.render()?))
} else {
return Ok(HttpResponse::NotFound().finish());
Ok(HttpResponse::NotFound().finish())
}
}

View File

@ -25,11 +25,11 @@ pub async fn post(
Area::update(pool.get_ref(), path.id, &form.name).await?;
}
return Ok(HttpResponse::Found()
Ok(HttpResponse::Found()
.insert_header((LOCATION, "/locations"))
.insert_header(("HX-LOCATION", "/locations"))
.finish());
.finish())
} else {
return Ok(HttpResponse::NotFound().finish());
Ok(HttpResponse::NotFound().finish())
}
}

View File

@ -15,14 +15,14 @@ pub async fn post(
match Area::create(pool.get_ref(), &form.name).await {
Ok(_) => {
return HttpResponse::Found()
HttpResponse::Found()
.insert_header((LOCATION, "/locations"))
.insert_header(("HX-LOCATION", "/locations"))
.finish()
}
Err(err) => {
println!("{}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
}
}

View File

@ -28,9 +28,9 @@ pub async fn get(
Availability::read_by_user_and_date(pool.get_ref(), user.id, &query.date).await?;
let free_slots = find_free_time_slots(&availabilities_from_user);
let user_can_create_availabillity = availabilities_from_user.len() == 0
let user_can_create_availabillity = availabilities_from_user.is_empty()
|| !only_one_availability_exists_and_is_whole_day(&availabilities_from_user)
|| free_slots.len() > 0;
|| !free_slots.is_empty();
if !user_can_create_availabillity {
return Ok(HttpResponse::BadRequest().finish());

View File

@ -73,13 +73,13 @@ async fn get(
Availability::read_by_user_and_date(pool.get_ref(), user.id, &date).await?;
println!("{availabilities_from_user:#?}");
let user_can_create_availabillity = availabilities_from_user.len() == 0
let user_can_create_availabillity = availabilities_from_user.is_empty()
|| !only_one_availability_exists_and_is_whole_day(&availabilities_from_user)
|| find_free_time_slots(&availabilities_from_user).len() > 0;
|| !find_free_time_slots(&availabilities_from_user).is_empty();
println!("{} || {} || {} = {user_can_create_availabillity}", availabilities_from_user.len() == 0,
println!("{} || {} || {} = {user_can_create_availabillity}", availabilities_from_user.is_empty(),
!only_one_availability_exists_and_is_whole_day(&availabilities_from_user),
find_free_time_slots(&availabilities_from_user).len() > 0);
!find_free_time_slots(&availabilities_from_user).is_empty());
let mut events_and_assignments = Vec::new();
for e in Event::read_all_by_date_and_area_including_location(
@ -116,9 +116,7 @@ async fn get(
.clone()
})
.collect(),
fuehrungsassistent.first().and_then(|fa| {
Some(
availabillities
fuehrungsassistent.first().map(|fa| availabillities
.iter()
.find(|a| a.id == fa.availabillity_id)
.unwrap()
@ -126,12 +124,8 @@ async fn get(
.as_ref()
.unwrap()
.name
.clone(),
)
}),
wachhabender.first().and_then(|wh| {
Some(
availabillities
.clone()),
wachhabender.first().map(|wh| availabillities
.iter()
.find(|a| a.id == wh.availabillity_id)
.unwrap()
@ -139,9 +133,7 @@ async fn get(
.as_ref()
.unwrap()
.name
.clone(),
)
}),
.clone()),
assigned_vehicle,
));
}

View File

@ -27,7 +27,7 @@ pub async fn delete(
let assignments_for_event = Assignment::read_all_by_event(pool.get_ref(), event.id).await?;
if assignments_for_event.len() > 0 {
if !assignments_for_event.is_empty() {
return Ok(HttpResponse::BadRequest().body("Can't delete event when people are assigned"));
}

View File

@ -68,7 +68,7 @@ pub async fn post(
note: form
.note
.clone()
.and_then(|n| if n.len() != 0 { Some(n) } else { None }),
.and_then(|n| if !n.is_empty() { Some(n) } else { None }),
voluntary_wachhabender: form.voluntarywachhabender.unwrap_or(false),
voluntary_fuehrungsassistent: form.voluntaryfuehrungsassistent.unwrap_or(false),
};
@ -161,7 +161,7 @@ pub async fn post(
for a in assignments_for_event {
let c = AssignmentChangeset {
function: a.function,
time: changeset.time.clone(),
time: changeset.time,
};
Assignment::update(pool.get_ref(), a.event_id, a.availabillity_id, c).await?;
}

View File

@ -51,7 +51,7 @@ pub async fn post(
note: form
.note
.clone()
.and_then(|n| if n.len() != 0 { Some(n) } else { None }),
.and_then(|n| if !n.is_empty() { Some(n) } else { None }),
voluntary_wachhabender: form.voluntarywachhabender.unwrap_or(false),
voluntary_fuehrungsassistent: form.voluntaryfuehrungsassistent.unwrap_or(false),
};

View File

@ -105,8 +105,8 @@ pub async fn get(
};
let out = match query.format.as_str() {
"xml" => quick_xml::se::to_string(&export).unwrap_or(String::new()),
"json" => serde_json::to_string(&export).unwrap_or(String::new()),
"xml" => quick_xml::se::to_string(&export).unwrap_or_default(),
"json" => serde_json::to_string(&export).unwrap_or_default(),
_ => return HttpResponse::BadRequest().finish(),
};

View File

@ -29,10 +29,10 @@ pub async fn post(
Location::create(pool.get_ref(), &form.name, area_id).await?;
return Ok(HttpResponse::Found()
Ok(HttpResponse::Found()
.insert_header((LOCATION, "/locations"))
.insert_header(("HX-LOCATION", "/locations"))
.finish());
.finish())
}
#[db_test]

View File

@ -10,7 +10,7 @@ struct LoginTemplate {}
#[actix_web::get("/login")]
async fn get(user: Option<Identity>) -> Result<impl Responder, ApplicationError> {
if let Some(_) = user {
if user.is_some() {
Ok(HttpResponse::Found()
.insert_header((LOCATION, "/"))
.finish())

View File

@ -23,7 +23,7 @@ pub async fn get(
pool: web::Data<PgPool>,
query: web::Query<TokenQuery>,
) -> Result<impl Responder, ApplicationError> {
if let Some(_) = user {
if user.is_some() {
return Ok(HttpResponse::Found()
.insert_header((LOCATION, "/"))
.finish());

View File

@ -36,5 +36,5 @@ async fn post(
)
.await?;
return Ok(response);
Ok(response)
}

View File

@ -35,5 +35,5 @@ async fn post(
}
}
return HttpResponse::BadRequest().body("E-Mail oder Passwort falsch.");
HttpResponse::BadRequest().body("E-Mail oder Passwort falsch.")
}

View File

@ -34,7 +34,7 @@ async fn post(
mailer.send_forgot_password_mail(&user, &reset.token).await?;
}
return Ok(HttpResponse::Ok().body("E-Mail versandt!"));
Ok(HttpResponse::Ok().body("E-Mail versandt!"))
} else if form.email.is_none()
&& form.token.is_some()
&& form.password.is_some()
@ -44,7 +44,7 @@ async fn post(
let is_dry = form.dry.is_some_and(|b| b);
let token = if let Some(token) =
PasswordReset::does_token_exist(pool.get_ref(), &form.token.as_ref().unwrap()).await?
PasswordReset::does_token_exist(pool.get_ref(), form.token.as_ref().unwrap()).await?
{
token
} else {

View File

@ -4,18 +4,18 @@ pub fn show_area_query(a: &Option<i32>, first: bool) -> rinja::Result<String> {
let char = if first { '?' } else { '&' };
if let Some(a) = a {
return Ok(format!("{}area={}", char, a));
Ok(format!("{}area={}", char, a))
} else {
return Ok(String::new());
Ok(String::new())
}
}
pub fn cond_show(show: &bool, text: &str) -> rinja::Result<String> {
return if *show {
if *show {
Ok(String::from(text))
} else {
Ok(String::new())
};
}
}
pub fn insert_value(option: &Option<String>) -> rinja::Result<String> {
@ -35,7 +35,7 @@ where
}
pub fn invert(b: &bool) -> rinja::Result<bool> {
return Ok(!b);
Ok(!b)
}
pub fn show_tree(f: &Function) -> rinja::Result<String> {

View File

@ -48,20 +48,20 @@ impl AsyncTransport for Transports {
'life2: 'async_trait,
Self: 'async_trait,
{
return Box::pin(async move {
Box::pin(async move {
match self {
Transports::SmtpTransport(smtp_transport) => smtp_transport
.send_raw(envelope, email)
.await
.map(|_| ())
.map_err(|err| ApplicationError::EmailTransport(err)),
.map_err(ApplicationError::EmailTransport),
Transports::StubTransport(stub_transport) => stub_transport
.send_raw(envelope, email)
.await
.map(|_| ())
.map_err(|err| ApplicationError::EmailStubTransport(err)),
.map_err(ApplicationError::EmailStubTransport),
}
});
})
}
}

View File

@ -124,15 +124,13 @@ impl Assignment {
.fetch_optional(pool)
.await?;
let assignemnet = record.and_then(|r| {
Some(Assignment {
let assignemnet = record.map(|r| Assignment {
event_id: r.eventid,
availabillity_id: r.availabillityid,
function: r.function,
start_time: r.starttime,
end_time: r.endtime,
})
});
});
Ok(assignemnet)
}

View File

@ -34,15 +34,13 @@ fn time_is_not_already_made_available(
return Err(garde::Error::new("cant create a availability while an other availability for the whole day is already present"));
}
if context.existing_availabilities.len() > 0 && find_free_time_slots(&context.existing_availabilities).len() == 0 {
if !context.existing_availabilities.is_empty() && find_free_time_slots(&context.existing_availabilities).is_empty() {
return Err(garde::Error::new(
"cant create a availability as every time slot is already filled",
));
}
} else {
if context.existing_availabilities.len() > 0 {
return Err(garde::Error::new("cant create a availability for the whole day while an other availability is already present"));
}
} else if !context.existing_availabilities.is_empty() {
return Err(garde::Error::new("cant create a availability for the whole day while an other availability is already present"));
}
Ok(())
@ -68,7 +66,7 @@ pub fn find_free_time_slots(availabilities: &[Availability]) -> Vec<(NaiveTime,
}
}
if times.len() == 0 {
if times.is_empty() {
return Vec::new();
}
println!("zeiten {times:?}");
@ -82,7 +80,7 @@ pub fn find_free_time_slots(availabilities: &[Availability]) -> Vec<(NaiveTime,
changed = false;
for i in 0..(times.len() - 1) {
let b = times[i + 1].clone();
let b = times[i + 1];
let a = times.get_mut(i).unwrap();
if a.1 == b.0 {

View File

@ -114,8 +114,8 @@ impl Availability {
email: r.email.clone(),
password: r.password.clone(),
salt: r.salt.clone(),
role: r.role.clone(),
function: r.function.clone(),
role: r.role,
function: r.function,
area_id: r.areaid,
area: None,
locked: r.locked,
@ -164,8 +164,7 @@ impl Availability {
.fetch_optional(pool)
.await?;
let availabillity = record.and_then(|r| {
Some(Availability {
let availabillity = record.map(|r| Availability {
id: r.id,
user_id: r.userid,
user: Some(User {
@ -174,8 +173,8 @@ impl Availability {
email: r.email.clone(),
password: r.password.clone(),
salt: r.salt.clone(),
role: r.role.clone(),
function: r.function.clone(),
role: r.role,
function: r.function,
area_id: r.areaid,
area: None,
locked: r.locked,
@ -188,8 +187,7 @@ impl Availability {
(_, _) => AvailabilityTime::WholeDay,
},
comment: r.comment.clone(),
})
});
});
Ok(availabillity)
}
@ -199,8 +197,7 @@ impl Availability {
.fetch_optional(pool)
.await?;
let availabillity = record.and_then(|record| {
Some(Availability {
let availabillity = record.map(|record| Availability {
id: record.id,
user_id: record.userid,
user: None,
@ -210,8 +207,7 @@ impl Availability {
(_, _) => AvailabilityTime::WholeDay,
},
comment: record.comment.clone(),
})
});
});
Ok(availabillity)
}
@ -266,8 +262,8 @@ impl Availability {
email: r.email.clone(),
password: r.password.clone(),
salt: r.salt.clone(),
role: r.role.clone(),
function: r.function.clone(),
role: r.role,
function: r.function,
area_id: r.areaid,
area: Some(Area {
id: r.areaid,

View File

@ -120,8 +120,7 @@ impl Event {
.fetch_optional(pool)
.await?;
let event = record.and_then(|record| {
Some(Event {
let event = record.map(|record| Event {
id: record.eventid,
date: record.date,
start_time: record.starttime,
@ -140,8 +139,7 @@ impl Event {
clothing: record.clothing.to_string(),
canceled: record.canceled,
note: record.note,
})
});
});
Ok(event)
}

View File

@ -22,7 +22,7 @@ pub struct EventChangeset {
pub voluntary_wachhabender: bool,
#[garde(custom(can_unset_fuehrungsassistent))]
pub voluntary_fuehrungsassistent: bool,
#[garde(range(min = ctx.as_ref().and_then(|c: &EventContext| Some(c.amount_of_assigned_posten)).unwrap_or(1), max = 100))]
#[garde(range(min = ctx.as_ref().map(|c: &EventContext| c.amount_of_assigned_posten).unwrap_or(1), max = 100))]
pub amount_of_posten: i16,
pub clothing: String,
pub note: Option<String>,

View File

@ -106,14 +106,12 @@ impl Location {
.fetch_optional(pool)
.await?;
let location = record.and_then(|r| {
Some(Location {
let location = record.map(|r| Location {
id: r.id,
name: r.name,
area_id: r.areaid,
area: None,
})
});
});
Ok(location)
}

View File

@ -41,8 +41,7 @@ impl User {
area_id
)
.fetch_one(pool)
.await
.and_then(|r| Ok(r.id))
.await.map(|r| r.id)
}
pub async fn create_with_password(
@ -55,7 +54,9 @@ impl User {
function: Function,
area_id: i32,
) -> Result<i32> {
let b = sqlx::query!(
sqlx::query!(
r#"
INSERT INTO user_ (name, email, password, salt, role, function, areaId)
VALUES ($1, $2, $3, $4, $5, $6, $7)
@ -70,10 +71,7 @@ impl User {
area_id
)
.fetch_one(pool)
.await
.and_then(|r| Ok(r.id));
b
.await.map(|r| r.id)
}
pub async fn read_by_id(pool: &PgPool, id: i32) -> Result<Option<User>> {
@ -98,7 +96,7 @@ impl User {
.fetch_optional(pool)
.await?;
let user = record.and_then(|u| Some(User {
let user = record.map(|u| User {
id: u.id,
name: u.name,
email: u.email,
@ -111,7 +109,7 @@ impl User {
locked: u.locked,
last_login: u.lastlogin,
receive_notifications: u.receivenotifications,
}));
});
Ok(user)
}
@ -184,8 +182,8 @@ impl User {
email: record.email.clone(),
password: record.password.clone(),
salt: record.salt.clone(),
role: record.role.clone(),
function: record.function.clone(),
role: record.role,
function: record.function,
area_id: record.areaid,
area: None,
locked: record.locked,
@ -229,8 +227,8 @@ impl User {
email: record.email.clone(),
password: record.password.clone(),
salt: record.salt.clone(),
role: record.role.clone(),
function: record.function.clone(),
role: record.role,
function: record.function,
area_id: record.areaid,
area: Some(Area {
id: record.areaid,
@ -275,8 +273,8 @@ impl User {
email: record.email.clone(),
password: record.password.clone(),
salt: record.salt.clone(),
role: record.role.clone(),
function: record.function.clone(),
role: record.role,
function: record.function,
area_id: record.areaid,
area: None,
locked: record.locked,

View File

@ -41,13 +41,11 @@ impl Vehicle {
.fetch_optional(pool)
.await?;
let vehicle = record.and_then(|v| {
Some(Vehicle {
let vehicle = record.map(|v| Vehicle {
id: v.id,
radio_call_name: v.radiocallname,
station: v.station,
})
});
});
Ok(vehicle)
}

View File

@ -39,12 +39,12 @@ impl VehicleAssignement {
let record = query!("SELECT * FROM vehicleAssignement WHERE vehicleAssignement.eventId = $1 AND vehicleAssignement.vehicleId = $2;", event_id, vehicle_id).fetch_optional(pool)
.await?;
let vehicle_assignment = record.and_then(|r| Some(VehicleAssignement {
let vehicle_assignment = record.map(|r| VehicleAssignement {
event_id: r.eventid,
vehicle_id: r.vehicleid,
start_time: r.starttime,
end_time: r.endtime,
}));
});
Ok(vehicle_assignment)
}

View File

@ -84,7 +84,7 @@ pub async fn handle_command(
let (hash, salt) = generate_salt_and_hash_plain_password(&password)?;
User::create_with_password(
&pool,
pool,
&name,
&email,
&hash,

View File

@ -7,9 +7,9 @@ pub fn generate_token_and_expiration(token_length_bytes: usize, validity: TimeDe
.take(token_length_bytes)
.collect::<Vec<_>>();
let token = String::from_utf8(value).unwrap().try_into().unwrap();
let token = String::from_utf8(value).unwrap();
let expires = Utc::now().naive_utc() + validity;
return (token, expires);
(token, expires)
}