refactor: apply clippy auto-fixes (162 warnings resolved)

- Fix needless borrows and references
- Collapse nested if statements
- Replace manual strip_prefix with str::strip_prefix()
- Remove redundant closures in map/unwrap_or_else
- Use Iterator::next_back() instead of rev().next()
- Simplify map_or patterns
- Use std::io::Error::other() instead of new(ErrorKind::Other, ..)
- Use div_ceil() instead of manual ceiling division
- Consolidate format! string arguments
- Various other idiomatic Rust improvements

39 files changed, 220 insertions(+), 320 deletions(-)
This commit is contained in:
Dionisio
2026-02-14 01:26:02 +01:00
parent 516b8727d2
commit 67137a3ef2
39 changed files with 220 additions and 320 deletions
@@ -380,8 +380,8 @@ impl ContactUseCase for ContactStorageAdapter {
} else if trimmed.starts_with("NOTE:") {
notes = Some(trimmed[5..].trim().to_string());
} else if trimmed.starts_with("EMAIL") {
if let Some(value) = trimmed.split(':').nth(1) {
if !value.is_empty() {
if let Some(value) = trimmed.split(':').nth(1)
&& !value.is_empty() {
let email_type = if trimmed.contains("TYPE=HOME") { "home" }
else if trimmed.contains("TYPE=WORK") { "work" }
else { "other" };
@@ -391,10 +391,9 @@ impl ContactUseCase for ContactStorageAdapter {
is_primary: emails.is_empty(),
});
}
}
} else if trimmed.starts_with("TEL") {
if let Some(value) = trimmed.split(':').nth(1) {
if !value.is_empty() {
} else if trimmed.starts_with("TEL")
&& let Some(value) = trimmed.split(':').nth(1)
&& !value.is_empty() {
let phone_type = if trimmed.contains("TYPE=CELL") || trimmed.contains("TYPE=MOBILE") { "mobile" }
else if trimmed.contains("TYPE=HOME") { "home" }
else if trimmed.contains("TYPE=WORK") { "work" }
@@ -405,8 +404,6 @@ impl ContactUseCase for ContactStorageAdapter {
is_primary: phones.is_empty(),
});
}
}
}
}
let contact_uid = uid.unwrap_or_else(|| format!("{}@oxicloud", Uuid::new_v4()));
@@ -24,10 +24,10 @@ use crate::domain::errors::{DomainError, ErrorKind};
#[macro_export]
macro_rules! impl_infra_error_to_domain {
($error_type:ty, $entity_type:expr) => {
impl From<$error_type> for crate::domain::errors::DomainError {
impl From<$error_type> for $crate::domain::errors::DomainError {
fn from(err: $error_type) -> Self {
crate::domain::errors::DomainError {
kind: crate::domain::errors::ErrorKind::InternalError,
$crate::domain::errors::DomainError {
kind: $crate::domain::errors::ErrorKind::InternalError,
entity_type: $entity_type,
entity_id: None,
message: format!("{}", err),
@@ -81,7 +81,7 @@ impl IntoDomainError for sqlx::Error {
}
sqlx::Error::Database(db_err) => {
// Handle specific PostgreSQL error codes
if db_err.code().map_or(false, |c| c == "23505") {
if db_err.code().is_some_and(|c| c == "23505") {
DomainError::already_exists(entity_type, "Record already exists")
} else {
DomainError::new(
+1 -2
View File
@@ -73,8 +73,7 @@ pub async fn create_database_pool(config: &AppConfig) -> Result<PgPool> {
async fn tables_exist(pool: &PgPool) -> bool {
sqlx::query("SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'auth' AND tablename = 'users')")
.fetch_one(pool)
.await
.and_then(|row| Ok(row.get::<bool, _>(0)))
.await.map(|row| row.get::<bool, _>(0))
.unwrap_or(false)
}
@@ -83,11 +83,10 @@ impl FileFsReadRepository {
async fn get_file_metadata_raw(&self, abs_path: &PathBuf) -> FileRepositoryResult<(u64, u64, u64)> {
// Cache first
if let Some(cached) = self.metadata_cache.get_metadata(abs_path).await {
if let (Some(s), Some(c), Some(m)) = (cached.size, cached.created_at, cached.modified_at) {
if let Some(cached) = self.metadata_cache.get_metadata(abs_path).await
&& let (Some(s), Some(c), Some(m)) = (cached.size, cached.created_at, cached.modified_at) {
return Ok((s, c, m));
}
}
let metadata = time::timeout(self.config.timeouts.file_timeout(), fs::metadata(abs_path))
.await
.map_err(|_| FileRepositoryError::StorageError(format!("Timeout metadata: {}", abs_path.display())))?
@@ -101,11 +101,10 @@ impl FileFsWriteRepository {
}
async fn get_file_metadata_raw(&self, abs_path: &PathBuf) -> FileRepositoryResult<(u64, u64, u64)> {
if let Some(cached) = self.metadata_cache.get_metadata(abs_path).await {
if let (Some(s), Some(c), Some(m)) = (cached.size, cached.created_at, cached.modified_at) {
if let Some(cached) = self.metadata_cache.get_metadata(abs_path).await
&& let (Some(s), Some(c), Some(m)) = (cached.size, cached.created_at, cached.modified_at) {
return Ok((s, c, m));
}
}
let meta = time::timeout(self.config.timeouts.file_timeout(), fs::metadata(abs_path))
.await
.map_err(|_| FileRepositoryError::StorageError(format!("Timeout: {}", abs_path.display())))?
@@ -177,11 +176,10 @@ impl FileFsWriteRepository {
for attempt in 1..=3 {
match self.id_mapping_service.save_changes().await {
Ok(_) => {
if let Ok(verified) = self.id_mapping_service.get_path_by_id(id).await {
if verified.to_string() == expected_path {
if let Ok(verified) = self.id_mapping_service.get_path_by_id(id).await
&& verified.to_string() == expected_path {
return Ok(());
}
}
if attempt == 3 {
return Err(FileRepositoryError::Other("Failed to verify ID mapping after 3 attempts".into()));
}
@@ -135,7 +135,7 @@ impl FolderFsRepository {
/// Updates a folder path in the ID mapping service
pub async fn update_mapped_folder_path(&self, folder_id: &str, new_path: &PathBuf) -> FolderRepositoryResult<()> {
let storage_path = StoragePath::from_string(&new_path.to_string_lossy().to_string());
let storage_path = StoragePath::from_string(new_path.to_string_lossy().as_ref());
self.id_mapping_service.update_path(folder_id, &storage_path).await
.map_err(|e| FolderRepositoryError::StorageError(format!("Failed to update folder path: {}", e)))
}
@@ -338,10 +338,7 @@ impl FolderRepository for FolderFsRepository {
let parent_id: Option<String> = if parent.is_none() || parent.as_ref().unwrap().is_empty() {
None
} else {
match self.id_mapping_service.get_or_create_id(parent.as_ref().unwrap()).await {
Ok(pid) => Some(pid),
Err(_) => None,
}
self.id_mapping_service.get_or_create_id(parent.as_ref().unwrap()).await.ok()
};
// Create folder entity
@@ -377,10 +374,7 @@ impl FolderRepository for FolderFsRepository {
let parent_id: Option<String> = if parent.is_none() || parent.as_ref().unwrap().is_empty() {
None
} else {
match self.id_mapping_service.get_or_create_id(parent.as_ref().unwrap()).await {
Ok(pid) => Some(pid),
Err(_) => None,
}
self.id_mapping_service.get_or_create_id(parent.as_ref().unwrap()).await.ok()
};
// Get folder metadata
@@ -651,11 +645,10 @@ impl FolderRepository for FolderFsRepository {
current_idx += 1;
}
if !folders.is_empty() {
if let Err(e) = self.id_mapping_service.save_changes().await {
if !folders.is_empty()
&& let Err(e) = self.id_mapping_service.save_changes().await {
tracing::error!("Error saving ID mappings: {}", e);
}
}
Ok((folders, total_count))
}
@@ -771,15 +764,13 @@ impl FolderRepository for FolderFsRepository {
tokio::task::spawn_blocking(move || {
if let Err(e) = std::fs::remove_dir_all(&path_for_large_removal) {
tracing::error!("Error removing large directory: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
return Err(std::io::Error::other(
format!("Failed to remove large directory: {}", e)
));
}
Ok(())
}).await.unwrap_or_else(|e| {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
Err(std::io::Error::other(
format!("Task panicked during directory removal: {}", e)
))
})
@@ -94,15 +94,14 @@ impl FolderFsRepository {
let original_path_buf = PathBuf::from(original_path);
// Ensure the destination parent directory exists
if let Some(parent) = original_path_buf.parent() {
if !parent.exists() {
if let Some(parent) = original_path_buf.parent()
&& !parent.exists() {
fs::create_dir_all(parent).await
.map_err(|e| {
error!("Error creating parent directory for restoration: {}", e);
FolderRepositoryError::StorageError(e.to_string())
})?;
}
}
// Move the folder from the trash to its original location
match fs::rename(&current_path, &original_path_buf).await {
@@ -32,7 +32,7 @@ impl UserPgRepository {
UserRepositoryError::NotFound("User not found".to_string())
},
sqlx::Error::Database(db_err) => {
if db_err.code().map_or(false, |code| code == "23505") {
if db_err.code().is_some_and(|code| code == "23505") {
// PostgreSQL uniqueness violation code
UserRepositoryError::AlreadyExists(
"User or email already exists".to_string()
@@ -268,7 +268,7 @@ impl UserRepository for UserPgRepository {
.bind(user_clone.username())
.bind(user_clone.email())
.bind(user_clone.password_hash())
.bind(&user_clone.role().to_string())
.bind(user_clone.role().to_string())
.bind(user_clone.storage_quota_bytes())
.bind(user_clone.storage_used_bytes())
.bind(user_clone.updated_at())
@@ -80,7 +80,7 @@ pub struct UploadSession {
impl UploadSession {
/// Calculate number of chunks needed
pub fn calculate_chunk_count(total_size: u64, chunk_size: usize) -> usize {
((total_size as usize + chunk_size - 1) / chunk_size).max(1)
(total_size as usize).div_ceil(chunk_size).max(1)
}
/// Get upload progress (0.0 - 1.0)
@@ -212,14 +212,12 @@ impl ChunkedUploadService {
let sessions = sessions.read().await;
if !sessions.contains_key(dir_name) {
// Check if directory is old (>24h)
if let Ok(metadata) = fs::metadata(&path).await {
if let Ok(modified) = metadata.modified() {
if modified.elapsed().unwrap_or_default() > SESSION_EXPIRATION {
if let Ok(metadata) = fs::metadata(&path).await
&& let Ok(modified) = metadata.modified()
&& modified.elapsed().unwrap_or_default() > SESSION_EXPIRATION {
let _ = fs::remove_dir_all(&path).await;
tracing::info!("🧹 Cleaned orphaned upload dir: {:?}", path);
}
}
}
}
}
}
@@ -283,7 +281,7 @@ impl ChunkedUploadService {
bytes_received: 0,
};
let expires_at = (SESSION_EXPIRATION.as_secs()) as u64;
let expires_at = SESSION_EXPIRATION.as_secs();
{
let mut sessions = self.sessions.write().await;
@@ -159,7 +159,7 @@ impl CompressionService for GzipCompressionService {
Ok(compressed)
}).await.unwrap_or_else(|e| {
error!("Compression task error: {}", e);
Err(io::Error::new(io::ErrorKind::Other, e.to_string()))
Err(io::Error::other(e.to_string()))
})
}
@@ -226,7 +226,7 @@ impl CompressionService for GzipCompressionService {
Ok(decompressed)
}).await.unwrap_or_else(|e| {
error!("Decompression task error: {}", e);
Err(io::Error::new(io::ErrorKind::Other, e.to_string()))
Err(io::Error::other(e.to_string()))
})
}
+2 -3
View File
@@ -622,14 +622,13 @@ impl DedupService {
}
// Check size
if let Ok(file_meta) = fs::metadata(&blob_path).await {
if file_meta.len() != metadata.size {
if let Ok(file_meta) = fs::metadata(&blob_path).await
&& file_meta.len() != metadata.size {
corrupted.push(format!(
"{}: size mismatch (expected: {}, actual: {})",
hash, metadata.size, file_meta.len()
));
}
}
}
if corrupted.is_empty() {
@@ -51,13 +51,11 @@ impl FileSystemI18nService {
}
}
if let Some(last_part) = parts.last() {
if let Some(value) = current.get(last_part) {
if value.is_string() {
if let Some(last_part) = parts.last()
&& let Some(value) = current.get(last_part)
&& value.is_string() {
return value.as_str().map(|s| s.to_string());
}
}
}
None
}
@@ -75,13 +73,11 @@ impl I18nService for FileSystemI18nService {
}
// Try to use English as fallback if we couldn't find the key
if locale != Locale::English {
if let Some(english_translations) = cache.get(&Locale::English) {
if let Some(value) = self.get_nested_value(english_translations, key) {
if locale != Locale::English
&& let Some(english_translations) = cache.get(&Locale::English)
&& let Some(value) = self.get_nested_value(english_translations, key) {
return Ok(value);
}
}
}
return Err(I18nError::KeyNotFound(key.to_string()));
}
@@ -98,13 +94,11 @@ impl I18nService for FileSystemI18nService {
}
// Try to use English as fallback
if locale != Locale::English {
if let Some(english_translations) = cache.get(&Locale::English) {
if let Some(value) = self.get_nested_value(english_translations, key) {
if locale != Locale::English
&& let Some(english_translations) = cache.get(&Locale::English)
&& let Some(value) = self.get_nested_value(english_translations, key) {
return Ok(value);
}
}
}
}
}
@@ -25,8 +25,7 @@ impl FileSystemUtils {
Ok(file) => file,
Err(e) => {
error!("Failed to create temporary file in {}: {}", dir.display(), e);
return Err(IoError::new(std::io::ErrorKind::Other,
format!("Failed to create temporary file: {}", e)));
return Err(IoError::other(format!("Failed to create temporary file: {}", e)));
}
};
@@ -60,6 +60,7 @@ pub struct OptimizerStats {
}
/// Queue for batch operations
#[derive(Default)]
struct BatchQueue {
/// Pending paths to get/create ID
path_to_id_requests: HashSet<String>,
@@ -67,14 +68,6 @@ struct BatchQueue {
id_to_path_requests: HashSet<String>,
}
impl Default for BatchQueue {
fn default() -> Self {
Self {
path_to_id_requests: HashSet::new(),
id_to_path_requests: HashSet::new(),
}
}
}
/// Result of a batch operation
struct BatchResult {
@@ -173,13 +173,11 @@ impl IdMappingService {
};
// Ensure directory exists
if let Some(parent) = map_path.parent() {
if !parent.exists() {
if let Err(e) = fs::create_dir_all(parent).await {
if let Some(parent) = map_path.parent()
&& !parent.exists()
&& let Err(e) = fs::create_dir_all(parent).await {
tracing::error!("Failed to create directory for ID map: {}", e);
}
}
}
// Write empty map to file (best-effort: the in-memory map is valid even if disk write fails)
match serde_json::to_string_pretty(&empty_map) {
@@ -413,8 +411,7 @@ impl IdMappingService {
// Try a second save if verification fails
if let Err(retry_err) = self.save_id_map().await {
tracing::error!("Second save attempt also failed: {}", retry_err);
return Err(IdMappingError::IoError(std::io::Error::new(
std::io::ErrorKind::Other,
return Err(IdMappingError::IoError(std::io::Error::other(
format!("Failed to verify and retry save: {}", retry_err)
)));
}
@@ -435,8 +432,7 @@ impl IdMappingService {
},
Err(retry_e) => {
tracing::error!("Second save attempt also failed: {}", retry_e);
Err(IdMappingError::IoError(std::io::Error::new(
std::io::ErrorKind::Other,
Err(IdMappingError::IoError(std::io::Error::other(
format!("Failed to save ID mappings after retry: {}", retry_e)
)))
}
@@ -200,11 +200,7 @@ impl ImageTranscodeService {
// Calculate savings
let original_size = original_content.len();
let transcoded_size = transcoded_bytes.len();
let saved = if transcoded_size < original_size {
original_size - transcoded_size
} else {
0
};
let saved = original_size.saturating_sub(transcoded_size);
// Only use transcoded if it's actually smaller
if transcoded_size >= original_size {
+1 -1
View File
@@ -65,7 +65,7 @@ impl PathService {
/// Checks if a path is at the root
pub fn is_in_root(&self, path: &StoragePath) -> bool {
path.parent().map_or(true, |p| p.is_empty())
path.parent().is_none_or(|p| p.is_empty())
}
/// Gets the root path used by this service
@@ -256,13 +256,12 @@ impl WriteBehindCache {
pending.get(&file_id).cloned()
};
if let Some(entry) = entry {
if let Err(e) = self.flush_single(&file_id, &entry).await {
if let Some(entry) = entry
&& let Err(e) = self.flush_single(&file_id, &entry).await {
tracing::error!("Failed to flush {}: {}", file_id, e);
// Keep in cache for retry
continue;
}
}
}
FlushCommand::FlushAll => {
let entries: Vec<_> = {