Collapse a few nested if now that we have if let chains

This commit is contained in:
Quentin Gliech
2025-08-18 10:29:30 +02:00
parent d44b3eedd3
commit 78933acb3c
18 changed files with 199 additions and 203 deletions

View File

@@ -12,15 +12,15 @@ fn main() -> anyhow::Result<()> {
// At build time, we override the version through the environment variable
// VERGEN_GIT_DESCRIBE. In some contexts, it means this variable is set but
// empty, so we unset it here.
if let Ok(ver) = std::env::var("VERGEN_GIT_DESCRIBE") {
if ver.is_empty() {
if let Ok(ver) = std::env::var("VERGEN_GIT_DESCRIBE")
&& ver.is_empty()
{
#[allow(unsafe_code)]
// SAFETY: This is safe because the build script is running a single thread
unsafe {
std::env::remove_var("VERGEN_GIT_DESCRIBE");
}
}
}
let gitcl = GitclBuilder::default()
.describe(true, false, Some("v*.*.*"))

View File

@@ -275,11 +275,11 @@ fn infer_client_ip(
let peer = if let Some(info) = connection_info {
// We can always trust the proxy protocol to give us the correct IP address
if let Some(proxy) = info.get_proxy_ref() {
if let Some(source) = proxy.source() {
if let Some(proxy) = info.get_proxy_ref()
&& let Some(source) = proxy.source()
{
return Some(source.ip());
}
}
info.get_peer_addr().map(|addr| addr.ip())
} else {

View File

@@ -619,14 +619,13 @@ impl Options {
let txn = conn.begin().await?;
let mut repo = PgRepository::from_conn(txn);
if let Some(password) = &password {
if !ignore_password_complexity
if let Some(password) = &password
&& !ignore_password_complexity
&& !password_manager.is_password_complex_enough(password)?
{
error!("That password is too weak.");
return Ok(ExitCode::from(1));
}
}
// If the username is provided, check if it's available and normalize it.
let localpart = if let Some(username) = username {

View File

@@ -208,12 +208,12 @@ pub async fn config_sync(
// private key to hold the content of the private key file.
// private key (raw) takes precedence so both can be defined
// without issues
if siwa.private_key.is_none() {
if let Some(private_key_file) = siwa.private_key_file.take() {
if siwa.private_key.is_none()
&& let Some(private_key_file) = siwa.private_key_file.take()
{
let key = tokio::fs::read_to_string(private_key_file).await?;
siwa.private_key = Some(key);
}
}
let encoded = serde_json::to_vec(&siwa)?;
Some(encrypter.encrypt_to_string(&encoded)?)
} else {

View File

@@ -198,35 +198,35 @@ impl ConfigurationSection for TelemetryConfig {
&self,
_figment: &figment::Figment,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
if let Some(sample_rate) = self.sentry.sample_rate {
if !(0.0..=1.0).contains(&sample_rate) {
if let Some(sample_rate) = self.sentry.sample_rate
&& !(0.0..=1.0).contains(&sample_rate)
{
return Err(figment::error::Error::custom(
"Sentry sample rate must be between 0.0 and 1.0",
)
.with_path("sentry.sample_rate")
.into());
}
}
if let Some(sample_rate) = self.sentry.traces_sample_rate {
if !(0.0..=1.0).contains(&sample_rate) {
if let Some(sample_rate) = self.sentry.traces_sample_rate
&& !(0.0..=1.0).contains(&sample_rate)
{
return Err(figment::error::Error::custom(
"Sentry sample rate must be between 0.0 and 1.0",
)
.with_path("sentry.traces_sample_rate")
.into());
}
}
if let Some(sample_rate) = self.tracing.sample_rate {
if !(0.0..=1.0).contains(&sample_rate) {
if let Some(sample_rate) = self.tracing.sample_rate
&& !(0.0..=1.0).contains(&sample_rate)
{
return Err(figment::error::Error::custom(
"Tracing sample rate must be between 0.0 and 1.0",
)
.with_path("tracing.sample_rate")
.into());
}
}
Ok(())
}

View File

@@ -129,8 +129,9 @@ where
field_fromatter.format_fields(writer.by_ref(), event)?;
// If we have a OTEL span, we can add the trace ID to the end of the log line
if let Some(span) = ctx.lookup_current() {
if let Some(otel) = span.extensions().get::<OtelData>() {
if let Some(span) = ctx.lookup_current()
&& let Some(otel) = span.extensions().get::<OtelData>()
{
let parent_cx_span = otel.parent_cx.span();
let sc = parent_cx_span.span_context();
@@ -156,7 +157,6 @@ where
}
}
}
}
writeln!(&mut writer)
}

View File

@@ -88,8 +88,8 @@ impl UserAgent {
#[must_use]
pub fn parse(user_agent: String) -> Self {
if !user_agent.contains("Mozilla/") {
if let Some((name, version, model, os, os_version)) =
if !user_agent.contains("Mozilla/")
&& let Some((name, version, model, os, os_version)) =
UserAgent::parse_custom(&user_agent)
{
let mut device_type = DeviceType::Unknown;
@@ -114,7 +114,6 @@ impl UserAgent {
raw: user_agent,
};
}
}
let mut model = None;
let Some(mut result) = Parser::new().parse(&user_agent) else {
@@ -205,12 +204,12 @@ impl UserAgent {
}
// Special handling for Electron applications e.g. Element Desktop
if user_agent.contains("Electron/") {
if let Some(app) = UserAgent::parse_electron(&user_agent) {
if user_agent.contains("Electron/")
&& let Some(app) = UserAgent::parse_electron(&user_agent)
{
result.name = app.0;
result.version = app.1;
}
}
Self {
name: (result.name != VALUE_UNKNOWN).then(|| result.name.to_owned()),

View File

@@ -223,18 +223,18 @@ impl UserRegistrationToken {
}
// Check if expired
if let Some(expires_at) = self.expires_at {
if now >= expires_at {
if let Some(expires_at) = self.expires_at
&& now >= expires_at
{
return false;
}
}
// Check if usage limit exceeded
if let Some(usage_limit) = self.usage_limit {
if self.times_used >= usage_limit {
if let Some(usage_limit) = self.usage_limit
&& self.times_used >= usage_limit
{
return false;
}
}
true
}

View File

@@ -187,11 +187,11 @@ where
};
// If there is a user for this session, check that it is not locked
if let Some(user) = &user {
if !user.is_valid() {
if let Some(user) = &user
&& !user.is_valid()
{
return Err(Rejection::UserLocked);
}
}
if !session.is_valid() {
return Err(Rejection::SessionRevoked);

View File

@@ -475,14 +475,14 @@ fn recover_error(
) -> axum::response::Response {
// Error responses should have an ErrorContext attached to them
let ext = response.extensions().get::<ErrorContext>();
if let Some(ctx) = ext {
if let Ok(res) = templates.render_error(ctx) {
if let Some(ctx) = ext
&& let Ok(res) = templates.render_error(ctx)
{
let (mut parts, _original_body) = response.into_parts();
parts.headers.remove(CONTENT_TYPE);
parts.headers.remove(CONTENT_LENGTH);
return (parts, Html(res)).into_response();
}
}
response
}

View File

@@ -288,11 +288,11 @@ pub(crate) async fn post(
let token = &form.token;
let token_type = TokenType::check(token)?;
if let Some(hint) = form.token_type_hint {
if token_type != hint {
if let Some(hint) = form.token_type_hint
&& token_type != hint
{
return Err(RouteError::UnexpectedTokenType);
}
}
// Not all device IDs can be encoded as scope. On OAuth 2.0 sessions, we
// don't have this problem, as the device ID *is* already encoded as a scope.

View File

@@ -241,35 +241,35 @@ pub(crate) async fn post(
// Some extra validation that is hard to do in OPA and not done by the
// `validate` method either
if let Some(client_uri) = &metadata.client_uri {
if localised_url_has_public_suffix(client_uri) {
if let Some(client_uri) = &metadata.client_uri
&& localised_url_has_public_suffix(client_uri)
{
return Err(RouteError::UrlIsPublicSuffix("client_uri"));
}
}
if let Some(logo_uri) = &metadata.logo_uri {
if localised_url_has_public_suffix(logo_uri) {
if let Some(logo_uri) = &metadata.logo_uri
&& localised_url_has_public_suffix(logo_uri)
{
return Err(RouteError::UrlIsPublicSuffix("logo_uri"));
}
}
if let Some(policy_uri) = &metadata.policy_uri {
if localised_url_has_public_suffix(policy_uri) {
if let Some(policy_uri) = &metadata.policy_uri
&& localised_url_has_public_suffix(policy_uri)
{
return Err(RouteError::UrlIsPublicSuffix("policy_uri"));
}
}
if let Some(tos_uri) = &metadata.tos_uri {
if localised_url_has_public_suffix(tos_uri) {
if let Some(tos_uri) = &metadata.tos_uri
&& localised_url_has_public_suffix(tos_uri)
{
return Err(RouteError::UrlIsPublicSuffix("tos_uri"));
}
}
if let Some(initiate_login_uri) = &metadata.initiate_login_uri {
if host_is_public_suffix(initiate_login_uri) {
if let Some(initiate_login_uri) = &metadata.initiate_login_uri
&& host_is_public_suffix(initiate_login_uri)
{
return Err(RouteError::UrlIsPublicSuffix("initiate_login_uri"));
}
}
for redirect_uri in metadata.redirect_uris() {
if host_is_public_suffix(redirect_uri) {

View File

@@ -93,9 +93,9 @@ pub(crate) async fn get(
// Forward the raw login hint upstream for the provider to handle however it
// sees fit
if provider.forward_login_hint {
if let Some(PostAuthAction::ContinueAuthorizationGrant { id }) = &query.post_auth_action {
if let Some(login_hint) = repo
if provider.forward_login_hint
&& let Some(PostAuthAction::ContinueAuthorizationGrant { id }) = &query.post_auth_action
&& let Some(login_hint) = repo
.oauth2_authorization_grant()
.lookup(*id)
.await?
@@ -103,8 +103,6 @@ pub(crate) async fn get(
{
data = data.with_login_hint(login_hint);
}
}
}
let data = if let Some(methods) = lazy_metadata.pkce_methods().await? {
data.with_code_challenge_methods_supported(methods)

View File

@@ -33,8 +33,9 @@ pub(crate) async fn post(
if let Some(session_id) = session_info.current_session_id() {
let maybe_session = repo.browser_session().lookup(session_id).await?;
if let Some(session) = maybe_session {
if session.finished_at.is_none() {
if let Some(session) = maybe_session
&& session.finished_at.is_none()
{
activity_tracker
.record_browser_session(&clock, &session)
.await;
@@ -42,7 +43,6 @@ pub(crate) async fn post(
repo.browser_session().finish(&clock, session).await?;
}
}
}
repo.save().await?;

View File

@@ -110,8 +110,9 @@ fn find_in_call<'a>(
call: &'a Spanned<Call<'a>>,
) -> Result<(), minijinja::Error> {
let span = call.span();
if let Expr::Var(var_) = &call.expr {
if var_.id == context.func() {
if let Expr::Var(var_) = &call.expr
&& var_.id == context.func()
{
let key = call
.args
.first()
@@ -140,7 +141,6 @@ fn find_in_call<'a>(
context.record(key);
}
}
find_in_expr(context, &call.expr)?;
find_in_call_args(context, &call.args)?;

View File

@@ -279,12 +279,12 @@ where
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
if let Poll::Ready(()) = this.cancellation_future.poll(cx) {
if !*this.did_start_shutdown {
if let Poll::Ready(()) = this.cancellation_future.poll(cx)
&& !*this.did_start_shutdown
{
*this.did_start_shutdown = true;
this.connection.as_mut().graceful_shutdown();
}
}
this.connection.poll(cx)
}

View File

@@ -680,11 +680,11 @@ impl ProviderMetadata {
validate_url("registration_endpoint", url, ExtraUrlRestrictions::None)?;
}
if let Some(scopes) = &metadata.scopes_supported {
if !scopes.iter().any(|s| s == "openid") {
if let Some(scopes) = &metadata.scopes_supported
&& !scopes.iter().any(|s| s == "openid")
{
return Err(ProviderMetadataVerificationError::ScopesMissingOpenid);
}
}
validate_signing_alg_values_supported(
"token_endpoint",

View File

@@ -120,15 +120,15 @@ impl Config {
pub fn all_oidc_providers(&self) -> BTreeMap<String, OidcProvider> {
let mut out = BTreeMap::new();
if let Some(provider) = &self.oidc_config {
if provider.has_required_fields() {
if let Some(provider) = &self.oidc_config
&& provider.has_required_fields()
{
let mut provider = provider.clone();
// The legacy configuration has an implied IdP ID of `oidc`.
let idp_id = provider.idp_id.take().unwrap_or("oidc".to_owned());
provider.idp_id = Some(idp_id.clone());
out.insert(idp_id, provider);
}
}
for provider in &self.oidc_providers {
let mut provider = provider.clone();