From c2ee3996be7c18ccfcf61371fa906edfba40969e Mon Sep 17 00:00:00 2001 From: Cameron Date: Sat, 18 Apr 2026 16:50:15 -0400 Subject: [PATCH] chore: apply cargo fmt + clippy cleanup across crate Silence forward-looking dead_code on unused DAO modules, annotate individual placeholder items, rewrite tautological assert!(true/false) in token tests as panic! arms, and pick up fmt drift. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/ai/handlers.rs | 5 ++- src/ai/insight_generator.rs | 54 +++++++++++++++---------------- src/ai/ollama.rs | 4 ++- src/bin/backfill_hashes.rs | 17 ++++------ src/content_hash.rs | 7 +++- src/data/mod.rs | 15 +++------ src/database/calendar_dao.rs | 2 ++ src/database/daily_summary_dao.rs | 2 ++ src/database/insights_dao.rs | 2 ++ src/database/knowledge_dao.rs | 5 +-- src/database/location_dao.rs | 2 ++ src/database/mod.rs | 5 ++- src/database/preview_dao.rs | 2 ++ src/database/search_dao.rs | 2 ++ src/files.rs | 2 +- src/lib.rs | 2 ++ src/libraries.rs | 12 ++++--- src/main.rs | 2 ++ src/memories.rs | 11 +++---- src/tags.rs | 3 ++ src/testhelpers.rs | 12 +++++++ src/video/ffmpeg.rs | 5 ++- 22 files changed, 106 insertions(+), 67 deletions(-) diff --git a/src/ai/handlers.rs b/src/ai/handlers.rs index a49c229..abf2369 100644 --- a/src/ai/handlers.rs +++ b/src/ai/handlers.rs @@ -503,7 +503,10 @@ pub async fn export_training_data_handler( HttpResponse::Ok() .content_type("application/jsonl") - .insert_header(("Content-Disposition", "attachment; filename=\"training_data.jsonl\"")) + .insert_header(( + "Content-Disposition", + "attachment; filename=\"training_data.jsonl\"", + )) .body(jsonl) } Err(e) => { diff --git a/src/ai/insight_generator.rs b/src/ai/insight_generator.rs index 0e2ab94..ecc387d 100644 --- a/src/ai/insight_generator.rs +++ b/src/ai/insight_generator.rs @@ -1827,32 +1827,32 @@ Return ONLY the summary, nothing else."#, // For each linked entity, fetch its facts for entity_id in entity_ids { - if let Ok(entity) = kdao.get_entity_by_id(cx, entity_id) { - if let Some(e) = entity { - let role = links - .iter() - .find(|l| l.entity_id == entity_id) - .map(|l| l.role.as_str()) - .unwrap_or("subject"); - output_lines.push(format!( - "Entity: {} ({}, role: {})", - e.name, e.entity_type, role - )); - if let Ok(facts) = kdao.get_facts_for_entity(cx, entity_id) { - for f in facts.iter().filter(|f| f.status == "active") { - let obj = if let Some(ref v) = f.object_value { - v.clone() - } else if let Some(oid) = f.object_entity_id { - kdao.get_entity_by_id(cx, oid) - .ok() - .flatten() - .map(|e| format!("{} (entity ID: {})", e.name, e.id)) - .unwrap_or_else(|| format!("entity:{}", oid)) - } else { - "(unknown)".to_string() - }; - output_lines.push(format!(" - {} {}", f.predicate, obj)); - } + if let Ok(entity) = kdao.get_entity_by_id(cx, entity_id) + && let Some(e) = entity + { + let role = links + .iter() + .find(|l| l.entity_id == entity_id) + .map(|l| l.role.as_str()) + .unwrap_or("subject"); + output_lines.push(format!( + "Entity: {} ({}, role: {})", + e.name, e.entity_type, role + )); + if let Ok(facts) = kdao.get_facts_for_entity(cx, entity_id) { + for f in facts.iter().filter(|f| f.status == "active") { + let obj = if let Some(ref v) = f.object_value { + v.clone() + } else if let Some(oid) = f.object_entity_id { + kdao.get_entity_by_id(cx, oid) + .ok() + .flatten() + .map(|e| format!("{} (entity ID: {})", e.name, e.id)) + .unwrap_or_else(|| format!("entity:{}", oid)) + } else { + "(unknown)".to_string() + }; + output_lines.push(format!(" - {} {}", f.predicate, obj)); } } } @@ -1902,8 +1902,8 @@ Return ONLY the summary, nothing else."#, // those already). Results are appended to the tool response so the // model can choose to use an existing entity's ID instead. let similar_entities: Vec = { + use crate::database::EntityFilter; use crate::database::knowledge_dao::normalize_entity_type; - use crate::database::{EntityFilter, KnowledgeDao}; let normalised_type = normalize_entity_type(&entity_type); let first_token = name.split_whitespace().next().unwrap_or(&name).to_string(); let filter = EntityFilter { diff --git a/src/ai/ollama.rs b/src/ai/ollama.rs index 1f42b6c..184bc61 100644 --- a/src/ai/ollama.rs +++ b/src/ai/ollama.rs @@ -120,6 +120,7 @@ impl OllamaClient { /// Replace the HTTP client with one using a custom request timeout. /// Useful for slow models where the default 120s may be insufficient. + #[allow(dead_code)] pub fn with_request_timeout(mut self, secs: u64) -> Self { self.client = Client::builder() .connect_timeout(Duration::from_secs(5)) @@ -174,6 +175,7 @@ impl OllamaClient { } /// Clear the model list cache for a specific URL or all URLs + #[allow(dead_code)] pub fn clear_model_cache(url: Option<&str>) { let mut cache = MODEL_LIST_CACHE.lock().unwrap(); if let Some(url) = url { @@ -186,6 +188,7 @@ impl OllamaClient { } /// Clear the model capabilities cache for a specific URL or all URLs + #[allow(dead_code)] pub fn clear_capabilities_cache(url: Option<&str>) { let mut cache = MODEL_CAPABILITIES_CACHE.lock().unwrap(); if let Some(url) = url { @@ -992,7 +995,6 @@ struct OllamaEmbedResponse { #[cfg(test)] mod tests { - use super::*; #[test] fn generate_photo_description_prompt_is_concise() { diff --git a/src/bin/backfill_hashes.rs b/src/bin/backfill_hashes.rs index 807c386..ad9b20f 100644 --- a/src/bin/backfill_hashes.rs +++ b/src/bin/backfill_hashes.rs @@ -68,8 +68,7 @@ fn main() -> anyhow::Result<()> { .join(", ") ); - let dao: Arc>> = - Arc::new(Mutex::new(Box::new(SqliteExifDao::new()))); + let dao: Arc>> = Arc::new(Mutex::new(Box::new(SqliteExifDao::new()))); let ctx = opentelemetry::Context::new(); let mut total_hashed = 0u64; @@ -98,15 +97,13 @@ fn main() -> anyhow::Result<()> { .get(&library_id) .map(|lib| Path::new(&lib.root_path).join(&rel_path)); match abs { - Some(abs_path) if abs_path.exists() => { - match content_hash::compute(&abs_path) { - Ok(id) => (library_id, rel_path, Some(id)), - Err(e) => { - eprintln!("hash error for {}: {:?}", abs_path.display(), e); - (library_id, rel_path, None) - } + Some(abs_path) if abs_path.exists() => match content_hash::compute(&abs_path) { + Ok(id) => (library_id, rel_path, Some(id)), + Err(e) => { + eprintln!("hash error for {}: {:?}", abs_path.display(), e); + (library_id, rel_path, None) } - } + }, Some(_) => (library_id, rel_path, None), // file missing on disk None => { eprintln!("Row refers to unknown library_id {}", library_id); diff --git a/src/content_hash.rs b/src/content_hash.rs index 63be295..7f05f06 100644 --- a/src/content_hash.rs +++ b/src/content_hash.rs @@ -53,13 +53,18 @@ pub fn thumbnail_path(thumbs_dir: &Path, hash: &str) -> PathBuf { /// Hash-keyed HLS output directory: `///`. /// The playlist lives at `playlist.m3u8` inside this directory and its /// segments are co-located so HLS relative references Just Work. +#[allow(dead_code)] pub fn hls_dir(video_dir: &Path, hash: &str) -> PathBuf { let shard = shard_prefix(hash); video_dir.join(shard).join(hash) } fn shard_prefix(hash: &str) -> &str { - let end = hash.char_indices().nth(2).map(|(i, _)| i).unwrap_or(hash.len()); + let end = hash + .char_indices() + .nth(2) + .map(|(i, _)| i) + .unwrap_or(hash.len()); &hash[..end] } diff --git a/src/data/mod.rs b/src/data/mod.rs index b6ba795..e953f4d 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -191,6 +191,7 @@ pub struct ThumbnailRequest { #[allow(dead_code)] // Part of API contract, may be used in future pub(crate) format: Option, #[serde(default)] + #[allow(dead_code)] // Part of API contract, may be used in future pub(crate) shape: Option, /// Optional library filter. Accepts a library id (e.g. "1") or name /// (e.g. "main"). When omitted, defaults to the primary library. @@ -434,11 +435,8 @@ mod tests { ); match err.unwrap_err().into_kind() { - ErrorKind::ExpiredSignature => assert!(true), - kind => { - println!("Unexpected error: {:?}", kind); - assert!(false) - } + ErrorKind::ExpiredSignature => {} + kind => panic!("Unexpected error: {:?}", kind), } } @@ -447,11 +445,8 @@ mod tests { let err = Claims::from_str("uni-֍ՓՓՓՓՓՓՓՓՓՓՓՓՓՓՓ"); match err.unwrap_err().into_kind() { - ErrorKind::InvalidToken => assert!(true), - kind => { - println!("Unexpected error: {:?}", kind); - assert!(false) - } + ErrorKind::InvalidToken => {} + kind => panic!("Unexpected error: {:?}", kind), } } diff --git a/src/database/calendar_dao.rs b/src/database/calendar_dao.rs index 82eea20..b70a9f6 100644 --- a/src/database/calendar_dao.rs +++ b/src/database/calendar_dao.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use serde::Serialize; diff --git a/src/database/daily_summary_dao.rs b/src/database/daily_summary_dao.rs index 5b1126f..6ea560a 100644 --- a/src/database/daily_summary_dao.rs +++ b/src/database/daily_summary_dao.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use chrono::NaiveDate; use diesel::prelude::*; use diesel::sqlite::SqliteConnection; diff --git a/src/database/insights_dao.rs b/src/database/insights_dao.rs index d54904f..553b579 100644 --- a/src/database/insights_dao.rs +++ b/src/database/insights_dao.rs @@ -31,6 +31,7 @@ pub trait InsightDao: Sync + Send { paths: &[String], ) -> Result, DbError>; + #[allow(dead_code)] fn get_insight_history( &mut self, context: &opentelemetry::Context, @@ -79,6 +80,7 @@ impl SqliteInsightDao { } #[cfg(test)] + #[allow(dead_code)] pub fn from_connection(conn: Arc>) -> Self { SqliteInsightDao { connection: conn } } diff --git a/src/database/knowledge_dao.rs b/src/database/knowledge_dao.rs index a9f75fe..f0d6c12 100644 --- a/src/database/knowledge_dao.rs +++ b/src/database/knowledge_dao.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use std::ops::DerefMut; @@ -230,7 +232,7 @@ impl SqliteKnowledgeDao { } fn deserialize_embedding(bytes: &[u8]) -> Result, DbError> { - if bytes.len() % 4 != 0 { + if !bytes.len().is_multiple_of(4) { return Err(DbError::new(DbErrorKind::QueryError)); } Ok(bytes @@ -535,7 +537,6 @@ impl KnowledgeDao for SqliteKnowledgeDao { conn.transaction::<(i64, i64), diesel::result::Error, _>(|conn| { use schema::entity_facts::dsl as ef; - use schema::entity_photo_links::dsl as epl; // 1. Re-point facts where source is subject let facts_updated = diff --git a/src/database/location_dao.rs b/src/database/location_dao.rs index 73e1c10..95f5d8f 100644 --- a/src/database/location_dao.rs +++ b/src/database/location_dao.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use serde::Serialize; diff --git a/src/database/mod.rs b/src/database/mod.rs index 2e3dca1..f29a212 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -155,7 +155,9 @@ pub trait FavoriteDao: Sync + Send { fn add_favorite(&mut self, user_id: i32, favorite_path: &str) -> Result; fn remove_favorite(&mut self, user_id: i32, favorite_path: String); fn get_favorites(&mut self, user_id: i32) -> Result, DbError>; + #[allow(dead_code)] fn update_path(&mut self, old_path: &str, new_path: &str) -> Result<(), DbError>; + #[allow(dead_code)] fn get_all_paths(&mut self) -> Result, DbError>; } @@ -239,6 +241,7 @@ impl FavoriteDao for SqliteFavoriteDao { } } +#[allow(dead_code)] pub trait ExifDao: Sync + Send { fn store_exif( &mut self, @@ -306,6 +309,7 @@ pub trait ExifDao: Sync + Send { /// Get all photos with GPS coordinates /// Returns Vec<(file_path, latitude, longitude, date_taken)> + #[allow(clippy::type_complexity)] fn get_all_with_gps( &mut self, context: &opentelemetry::Context, @@ -680,7 +684,6 @@ impl ExifDao for SqliteExifDao { .map_err(|_| DbError::new(DbErrorKind::QueryError)) } - fn get_all_with_gps( &mut self, context: &opentelemetry::Context, diff --git a/src/database/preview_dao.rs b/src/database/preview_dao.rs index 6098c60..c528327 100644 --- a/src/database/preview_dao.rs +++ b/src/database/preview_dao.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use std::ops::DerefMut; diff --git a/src/database/search_dao.rs b/src/database/search_dao.rs index 04d0d2f..a74fd92 100644 --- a/src/database/search_dao.rs +++ b/src/database/search_dao.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use serde::Serialize; diff --git a/src/files.rs b/src/files.rs index d83325e..20ea001 100644 --- a/src/files.rs +++ b/src/files.rs @@ -16,7 +16,6 @@ use crate::file_types; use crate::geo::{gps_bounding_box, haversine_distance}; use crate::memories::extract_date_from_filename; use crate::{AppState, create_thumbnails}; -use actix_web::dev::ResourcePath; use actix_web::web::Data; use actix_web::{ HttpRequest, HttpResponse, @@ -1242,6 +1241,7 @@ mod tests { } impl FakeFileSystem { + #[allow(dead_code)] fn with_error() -> FakeFileSystem { FakeFileSystem { files: HashMap::new(), diff --git a/src/lib.rs b/src/lib.rs index d74fc2b..cf0ba10 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::too_many_arguments)] + #[macro_use] extern crate diesel; diff --git a/src/libraries.rs b/src/libraries.rs index 22a4214..3cfc0be 100644 --- a/src/libraries.rs +++ b/src/libraries.rs @@ -32,6 +32,7 @@ impl Library { /// Resolve a library-relative path into an absolute `PathBuf` under the /// library root. Does not validate traversal — use `is_valid_full_path` /// for untrusted input. + #[allow(dead_code)] pub fn resolve(&self, rel_path: &str) -> PathBuf { Path::new(&self.root_path).join(rel_path) } @@ -39,6 +40,7 @@ impl Library { /// Inverse of `resolve`: given an absolute path under this library's /// root, return the root-relative portion. Returns `None` if the path /// is not under the library. + #[allow(dead_code)] pub fn strip_root(&self, abs_path: &Path) -> Option { abs_path .strip_prefix(&self.root_path) @@ -99,10 +101,7 @@ pub fn seed_or_patch_from_env(conn: &mut SqliteConnection, base_path: &str) { // If no rows exist at all (e.g. table created outside the seeded migration), // insert a primary library pointing at BASE_PATH. - let total: i64 = libraries::table - .count() - .get_result(conn) - .unwrap_or(0); + let total: i64 = libraries::table.count().get_result(conn).unwrap_or(0); if total == 0 { let now = Utc::now().timestamp(); let result = diesel::insert_into(libraries::table) @@ -113,7 +112,10 @@ pub fn seed_or_patch_from_env(conn: &mut SqliteConnection, base_path: &str) { }) .execute(conn); match result { - Ok(_) => info!("Seeded primary library 'main' with BASE_PATH='{}'", base_path), + Ok(_) => info!( + "Seeded primary library 'main' with BASE_PATH='{}'", + base_path + ), Err(e) => warn!("Failed to seed primary library: {:?}", e), } } diff --git a/src/main.rs b/src/main.rs index 53e96cf..d03bf31 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +#![allow(clippy::too_many_arguments)] + #[macro_use] extern crate diesel; extern crate rayon; diff --git a/src/memories.rs b/src/memories.rs index 23086f6..64a4c95 100644 --- a/src/memories.rs +++ b/src/memories.rs @@ -539,10 +539,7 @@ pub async fn list_memories( // Resolve the optional library filter. Unknown values are a 400; None // means "all libraries" — currently equivalent to the primary library // while only one is configured. - let library = match crate::libraries::resolve_library_param( - &app_state, - q.library.as_deref(), - ) { + let library = match crate::libraries::resolve_library_param(&app_state, q.library.as_deref()) { Ok(lib) => lib, Err(msg) => { warn!("Rejecting /memories request: {}", msg); @@ -823,7 +820,7 @@ mod tests { // Verify timestamp is within expected range (should be around 1422489671) let timestamp = date_time.timestamp(); - assert!(timestamp >= 1422480000 && timestamp <= 1422576000); // Jan 28-29, 2015 + assert!((1422480000..=1422576000).contains(×tamp)); // Jan 28-29, 2015 } #[test] @@ -841,7 +838,7 @@ mod tests { // Verify timestamp is within expected range (should be around 1422489664) let timestamp = date_time.timestamp(); - assert!(timestamp >= 1422480000 && timestamp <= 1422576000); // Jan 28-29, 2015 + assert!((1422480000..=1422576000).contains(×tamp)); // Jan 28-29, 2015 } #[test] @@ -1120,7 +1117,7 @@ mod tests { .and_utc() .timestamp(); - let mut memories_with_dates = vec![ + let mut memories_with_dates = [ ( MemoryItem { path: "photo1.jpg".to_string(), diff --git a/src/tags.rs b/src/tags.rs index 95e303f..b94cb3b 100644 --- a/src/tags.rs +++ b/src/tags.rs @@ -342,12 +342,14 @@ pub trait TagDao: Send + Sync { exclude_tag_ids: Vec, context: &opentelemetry::Context, ) -> anyhow::Result>; + #[allow(dead_code)] fn update_photo_name( &mut self, old_name: &str, new_name: &str, context: &opentelemetry::Context, ) -> anyhow::Result<()>; + #[allow(dead_code)] fn get_all_photo_names( &mut self, context: &opentelemetry::Context, @@ -364,6 +366,7 @@ pub struct SqliteTagDao { } impl SqliteTagDao { + #[allow(dead_code)] pub(crate) fn new(connection: Arc>) -> Self { SqliteTagDao { connection } } diff --git a/src/testhelpers.rs b/src/testhelpers.rs index f4150e4..1536dbb 100644 --- a/src/testhelpers.rs +++ b/src/testhelpers.rs @@ -14,6 +14,12 @@ pub struct TestUserDao { pub user_map: RefCell>, } +impl Default for TestUserDao { + fn default() -> Self { + Self::new() + } +} + impl TestUserDao { pub fn new() -> Self { Self { @@ -71,6 +77,12 @@ pub struct TestPreviewDao { next_id: StdMutex, } +impl Default for TestPreviewDao { + fn default() -> Self { + Self::new() + } +} + impl TestPreviewDao { pub fn new() -> Self { Self { diff --git a/src/video/ffmpeg.rs b/src/video/ffmpeg.rs index b40b175..5ed9308 100644 --- a/src/video/ffmpeg.rs +++ b/src/video/ffmpeg.rs @@ -40,7 +40,10 @@ pub struct Ffmpeg; pub enum GifType { Overview, - OverviewVideo { duration: u32 }, + #[allow(dead_code)] + OverviewVideo { + duration: u32, + }, } impl Ffmpeg {