From 0aa26466a39b71308c9b53a3ff263a3bac554b79 Mon Sep 17 00:00:00 2001 From: euzu Date: Fri, 16 May 2025 14:11:33 +0200 Subject: [PATCH] clippy optimizations --- src/api/config_watch.rs | 10 ++++----- src/api/endpoints/xmltv_api.rs | 2 +- src/api/main_api.rs | 4 ++-- src/api/scheduler.rs | 23 +++++++++------------ src/auth/access_token.rs | 4 ++-- src/foundation/filter.rs | 22 ++++++++------------ src/processing/parser/xmltv.rs | 4 ++-- src/processing/processor/sort.rs | 4 ++-- src/repository/indexed_document.rs | 4 ++-- src/repository/storage.rs | 2 +- src/repository/target_id_mapping.rs | 2 +- src/repository/user_repository.rs | 2 +- src/repository/xtream_repository.rs | 2 +- src/tools/directed_graph.rs | 4 ++-- src/tuliprox_error.rs | 4 ++-- src/utils/crypto_utils.rs | 2 +- src/utils/file/csv_input_reader.rs | 32 ++++++++++++++--------------- 17 files changed, 60 insertions(+), 67 deletions(-) diff --git a/src/api/config_watch.rs b/src/api/config_watch.rs index 7067787c1..403419910 100644 --- a/src/api/config_watch.rs +++ b/src/api/config_watch.rs @@ -47,8 +47,8 @@ impl ConfigFile { } Ok(()) } - pub(crate) fn reload(&self, file_path: &PathBuf, app_state: &Arc) -> Result<(), TuliproxError> { - debug!("File change detected {file_path:?}"); + pub(crate) fn reload(&self, file_path: &Path, app_state: &Arc) -> Result<(), TuliproxError> { + debug!("File change detected {}", file_path.display()); match self { ConfigFile::ApiProxy => ConfigFile::load_api_proxy(app_state), ConfigFile::Mapping => ConfigFile::load_mappping(app_state), @@ -80,7 +80,7 @@ pub async fn exec_config_watch(app_state: &Arc) -> Result<(), Tuliprox let path = Path::new(app_state.config.t_config_path.as_str()); let recursive_mode = if utils::is_directory(&app_state.config.t_mapping_file_path) { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive }; watcher.watch(path, recursive_mode).map_err(|err| TuliproxError::new(TuliproxErrorKind::Info, format!("Failed to start config file watcher {err}")))?; - info!("Watching config file changes {path:?}"); + info!("Watching config file changes {}", path.display()); let watcher_app_state = Arc::clone(app_state); tokio::spawn(async move { @@ -92,13 +92,13 @@ pub async fn exec_config_watch(app_state: &Arc) -> Result<(), Tuliprox for path in event.paths { if let Some((config_file, _is_dir)) = files.get(&path) { if let Err(err) = config_file.reload(&path, &watcher_app_state) { - error!("Failed to reload config file {path:?}: {err}"); + error!("Failed to reload config file {}: {err}", path.display()); } } else if recursive_mode == RecursiveMode::Recursive && path.extension().is_some_and(|ext| ext == "yml") { for (key, (config_file, is_dir)) in &files { if *is_dir && path.starts_with(key) { if let Err(err) = config_file.reload(&path, &watcher_app_state) { - error!("Failed to reload config file {path:?}: {err}"); + error!("Failed to reload config file {}: {err}", path.display()); } } } diff --git a/src/api/endpoints/xmltv_api.rs b/src/api/endpoints/xmltv_api.rs index b77f8b9c5..b661a4d34 100644 --- a/src/api/endpoints/xmltv_api.rs +++ b/src/api/endpoints/xmltv_api.rs @@ -237,7 +237,7 @@ mod tests { assert_eq!(parse_timeshift(Some(&String::from("-0:10"))), Some(-10)); assert_eq!(parse_timeshift(Some(&String::from("invalid"))), None); assert_eq!(parse_timeshift(Some(&String::from("+abc"))), None); - assert_eq!(parse_timeshift(Some(&String::from(""))), None); + assert_eq!(parse_timeshift(Some(&String::new())), None); assert_eq!(parse_timeshift(None), None); } } \ No newline at end of file diff --git a/src/api/main_api.rs b/src/api/main_api.rs index fd78b5892..8e6332a2b 100644 --- a/src/api/main_api.rs +++ b/src/api/main_api.rs @@ -36,7 +36,7 @@ fn get_web_dir_path(web_ui_enabled: bool, web_root: &str) -> Result, targets: Arc) -> fut Err(err) => return Err(err) }; if web_ui_enabled { - infos.push(format!("Web root: {web_dir_path:?}")); + infos.push(format!("Web root: {}", web_dir_path.display())); } let app_shared_data = create_shared_data(&cfg).await; let app_state = Arc::new(app_shared_data); diff --git a/src/api/scheduler.rs b/src/api/scheduler.rs index 38ce178b9..052c52cdf 100644 --- a/src/api/scheduler.rs +++ b/src/api/scheduler.rs @@ -57,21 +57,18 @@ mod tests { let run_me = || runs.fetch_add(1, Ordering::SeqCst); let start = std::time::Instant::now(); - match Schedule::from_str(expression) { - Ok(schedule) => { - let offset = *Local::now().offset(); - loop { - let mut upcoming = schedule.upcoming(offset).take(1); - if let Some(datetime) = upcoming.next() { - tokio::time::sleep_until(tokio::time::Instant::from(datetime_to_instant(datetime))).await; - run_me(); - } - if runs.load(Ordering::SeqCst) == 6 { - break; - } + if let Ok(schedule) = Schedule::from_str(expression) { + let offset = *Local::now().offset(); + loop { + let mut upcoming = schedule.upcoming(offset).take(1); + if let Some(datetime) = upcoming.next() { + tokio::time::sleep_until(tokio::time::Instant::from(datetime_to_instant(datetime))).await; + run_me(); + } + if runs.load(Ordering::SeqCst) == 6 { + break; } } - Err(_) => {} } let duration = start.elapsed(); diff --git a/src/auth/access_token.rs b/src/auth/access_token.rs index c2eab8a20..4735b1fc7 100644 --- a/src/auth/access_token.rs +++ b/src/auth/access_token.rs @@ -63,8 +63,8 @@ mod tests { fn test_valid_token() { let secret = b"37c30f739e83ba27b4c17b174c31f3a9"; let token = create_access_token(secret, 1); - assert_eq!(verify_access_token(token.as_str(), secret), true); + assert!(verify_access_token(token.as_str(), secret)); thread::sleep(std::time::Duration::from_secs(2)); - assert_eq!(verify_access_token(token.as_str(), secret), false); + assert!(!verify_access_token(token.as_str(), secret)); } } \ No newline at end of file diff --git a/src/foundation/filter.rs b/src/foundation/filter.rs index 856290894..67618a7b5 100644 --- a/src/foundation/filter.rs +++ b/src/foundation/filter.rs @@ -761,29 +761,26 @@ mod tests { }) .collect(); assert_eq!(filtered.len(), 2); - assert_eq!( + assert!( filtered.iter().any(|&chan| { let group = chan.header.group.to_string(); let name = chan.header.name.to_string(); name.eq("24/7: Cars") && group.eq("FR Channels") - }), - true + }) ); - assert_eq!( + assert!( filtered.iter().any(|&chan| { let group = chan.header.group.to_string(); let name = chan.header.name.to_string(); name.eq("Entertainment") && group.eq("US Channels") - }), - true + }) ); - assert_eq!( - filtered.iter().any(|&chan| { + assert!( + !filtered.iter().any(|&chan| { let group = chan.header.group.to_string(); let name = chan.header.name.to_string(); name.eq("24/7: Cars") && group.eq("US Channels") - }), - false + }) ); } Err(e) => { @@ -879,13 +876,12 @@ mod tests { }) .collect(); assert_eq!(filtered.len(), 1); - assert_eq!( + assert!( filtered.iter().any(|&chan| { let group = chan.header.group.to_string(); let name = chan.header.name.to_string(); name.eq("Entertainment") && group.eq("US Channels") - }), - true + }) ); } Err(e) => { diff --git a/src/processing/parser/xmltv.rs b/src/processing/parser/xmltv.rs index fb8b106bb..9534e9621 100644 --- a/src/processing/parser/xmltv.rs +++ b/src/processing/parser/xmltv.rs @@ -520,7 +520,7 @@ mod tests { epg_smart_cfg.enabled = true; epg_smart_cfg.name_prefix = EpgNamePrefix::Suffix(".".to_string()); let _ = epg_smart_cfg.prepare(); - println!("{:?}", epg_smart_cfg); + println!("{epg_smart_cfg:?}"); assert_eq!("supersport6.ru", normalize_channel_name("RU: SUPERSPORT 6 ᴿᴬᵂ", &epg_smart_cfg)); assert_eq!("odisea.sat", normalize_channel_name("SAT: ODISEA ᴿᴬᵂ", &epg_smart_cfg)); assert_eq!("odisea.4k", normalize_channel_name("4K: ODISEA ᵁᴴᴰ ³⁸⁴⁰ᴾ", &epg_smart_cfg)); @@ -549,7 +549,7 @@ mod tests { epg_smart_cfg.enabled = true; epg_smart_cfg.name_prefix = EpgNamePrefix::Suffix(".".to_string()); let _ = epg_smart_cfg.prepare(); - println!("{:?}", epg_smart_cfg); + println!("{epg_smart_cfg:?}"); // assert_eq!("supersport6.ru", metaphone.encode(&normalize_channel_name("RU: SUPERSPORT 6 ᴿᴬᵂ", &epg_normalize_cfg))); // assert_eq!("odisea.sat", metaphone.encode(&normalize_channel_name("SAT: ODISEA ᴿᴬᵂ", &epg_normalize_cfg))); // assert_eq!("odisea", metaphone.encode(&normalize_channel_name("4K: ODISEA ᵁᴴᴰ ³⁸⁴⁰ᴾ", &epg_normalize_cfg))); diff --git a/src/processing/processor/sort.rs b/src/processing/processor/sort.rs index 9a7e6e7b9..2cae63eec 100644 --- a/src/processing/processor/sort.rs +++ b/src/processing/processor/sort.rs @@ -147,7 +147,7 @@ mod tests { let mut channels: Vec = vec![ ("D", "HD"), ("A", "FHD"), ("Z", "HD"), ("K", "HD"), ("B", "HD"), ("A", "HD"), ("K", "UHD"), ("C", "HD"), ("L", "FHD"), ("R", "UHD"), ("T", "SD"), ("A", "FHD"), - ].into_iter().map(|(name, quality)| PlaylistItem { header: PlaylistItemHeader { title: format!("Chanel {name} [{quality}]"), ..Default::default() } }).collect::>().into(); + ].into_iter().map(|(name, quality)| PlaylistItem { header: PlaylistItemHeader { title: format!("Chanel {name} [{quality}]"), ..Default::default() } }).collect::>(); let channel_sort = ConfigSortChannel { field: ItemField::Caption, @@ -195,7 +195,7 @@ mod tests { "US| East d", "US| West e", "US| West f", - ].into_iter().map(|name| PlaylistItem { header: PlaylistItemHeader { title: name.to_string(), ..Default::default() } }).collect::>().into(); + ].into_iter().map(|name| PlaylistItem { header: PlaylistItemHeader { title: name.to_string(), ..Default::default() } }).collect::>(); let channel_sort = ConfigSortChannel { field: ItemField::Caption, diff --git a/src/repository/indexed_document.rs b/src/repository/indexed_document.rs index b753e2f09..034f3059b 100644 --- a/src/repository/indexed_document.rs +++ b/src/repository/indexed_document.rs @@ -115,7 +115,7 @@ where // Initialize the index tree (BPlusTree) - either by deserializing an existing one or creating a new one let index_tree = if append_mode && index_path.exists() { IndexedDocumentIndex::::load(&index_path).unwrap_or_else(|err| { - error!("Failed to load index {index_path:?}: {err}"); + error!("Failed to load index {}: {err}", index_path.display()); IndexedDocumentIndex::::new() }) } else { @@ -257,7 +257,7 @@ where t_type: PhantomData, }) } else { - Err(Error::new(ErrorKind::NotFound, format!("File not found {main_path:?}"))) + Err(Error::new(ErrorKind::NotFound, format!("File not found {}", main_path.display()))) } } pub fn get(&mut self, doc_id: &K) -> Result { diff --git a/src/repository/storage.rs b/src/repository/storage.rs index b9a35406d..d35ef38ef 100644 --- a/src/repository/storage.rs +++ b/src/repository/storage.rs @@ -57,7 +57,7 @@ pub(in crate::repository) fn get_target_id_mapping_file(target_path: &Path) -> P pub fn ensure_target_storage_path(cfg: &Config, target_name: &str) -> Result { if let Some(path) = get_target_storage_path(cfg, target_name) { if std::fs::create_dir_all(&path).is_err() { - let msg = format!("Failed to save target data, can't create directory {path:?}"); + let msg = format!("Failed to save target data, can't create directory {}", path.display()); return Err(notify_err!(msg)); } Ok(path) diff --git a/src/repository/target_id_mapping.rs b/src/repository/target_id_mapping.rs index a89f64a84..80971258a 100644 --- a/src/repository/target_id_mapping.rs +++ b/src/repository/target_id_mapping.rs @@ -119,7 +119,7 @@ impl TargetIdMapping { impl Drop for TargetIdMapping { fn drop(&mut self) { if let Err(err) = self.persist() { - error!("Failed to persist target id mapping {:?} err:{err}", &self.path); + error!("Failed to persist target id mapping {} err:{err}", &self.path.display()); } } } diff --git a/src/repository/user_repository.rs b/src/repository/user_repository.rs index 3311f311b..cd2caf00f 100644 --- a/src/repository/user_repository.rs +++ b/src/repository/user_repository.rs @@ -474,6 +474,6 @@ mod tests { let user_list = load_api_user(&cfg); assert!(user_list.is_ok()); assert_eq!(user_list.as_ref().unwrap().len(), 1); - assert_eq!(user_list.as_ref().unwrap().get(0).unwrap().credentials.len(), 4); + assert_eq!(user_list.as_ref().unwrap().first().unwrap().credentials.len(), 4); } } \ No newline at end of file diff --git a/src/repository/xtream_repository.rs b/src/repository/xtream_repository.rs index d23d0c72f..dd099efe5 100644 --- a/src/repository/xtream_repository.rs +++ b/src/repository/xtream_repository.rs @@ -253,7 +253,7 @@ pub async fn xtream_write_playlist( match json_write_documents_to_file(&col_path, data) { Ok(()) => {} Err(err) => { - errors.push(format!("Persisting collection failed: {col_path:?}: {err}")); + errors.push(format!("Persisting collection failed: {}: {err}", col_path.display())); } } } diff --git a/src/tools/directed_graph.rs b/src/tools/directed_graph.rs index f6cbd1ca5..f264c7a78 100644 --- a/src/tools/directed_graph.rs +++ b/src/tools/directed_graph.rs @@ -211,8 +211,8 @@ mod tests { use std::collections::HashSet; fn are_vecs_equal(vec1: &Vec<&str>, vec2: Vec<&str>) -> bool { - let set1: HashSet = vec1.iter().map(|s| s.to_string()).collect(); - let set2: HashSet = vec2.iter().map(|s| s.to_string()).collect(); + let set1: HashSet = vec1.iter().map(|s| (*s).to_string()).collect(); + let set2: HashSet = vec2.iter().map(|s| (*s).to_string()).collect(); set1 == set2 } diff --git a/src/tuliprox_error.rs b/src/tuliprox_error.rs index 48e5ad54f..c1fb8dc05 100644 --- a/src/tuliprox_error.rs +++ b/src/tuliprox_error.rs @@ -120,8 +120,8 @@ impl Error for TuliproxError {} pub fn to_io_error(err: E) -> std::io::Error where E: std::error::Error, -{ std::io::Error::new(std::io::ErrorKind::Other, err.to_string()) } +{ std::io::Error::other(err.to_string()) } pub fn str_to_io_error(err: &str) -> std::io::Error { - std::io::Error::new(std::io::ErrorKind::Other, err.to_string()) + std::io::Error::other(err.to_string()) } diff --git a/src/utils/crypto_utils.rs b/src/utils/crypto_utils.rs index c118dbf53..44f3c8807 100644 --- a/src/utils/crypto_utils.rs +++ b/src/utils/crypto_utils.rs @@ -78,7 +78,7 @@ mod tests { fn test_obfuscate() { let secret: [u8; 16] = rand::rng().random(); // Random IV (AES-CBC 16 Bytes) let plain = "hello world"; - let encrypted = obfuscate_text(&secret, &plain); + let encrypted = obfuscate_text(&secret, plain); let decrypted = deobfuscate_text(&secret, &encrypted.unwrap()).unwrap(); assert_eq!(decrypted, plain); diff --git a/src/utils/file/csv_input_reader.rs b/src/utils/file/csv_input_reader.rs index f1fb29a7b..a4ec54dbc 100644 --- a/src/utils/file/csv_input_reader.rs +++ b/src/utils/file/csv_input_reader.rs @@ -185,29 +185,29 @@ mod tests { use crate::utils::resolve_env_var; use std::io::{BufReader, Cursor}; - const M3U_BATCH: &str = r#" + const M3U_BATCH: &str = r" #url;name;max_connections;priority http://hd.providerline.com:8080/get.php?username=user1&password=user1&type=m3u_plus;input_1 http://hd.providerline.com/get.php?username=user2&password=user2&type=m3u_plus;input_2;1;2 http://hd.providerline.com/get.php?username=user3&password=user3&type=m3u_plus;input_3;1;2 http://hd.providerline.com/get.php?username=user4&password=user4&type=m3u_plus;input_4 -"#; +"; - const XTREAM_BATCH: &str = r#" + const XTREAM_BATCH: &str = r" #name;username;password;url;max_connections input_1;desanocra;eyCG8SN523KQ;http://provider_1.tv:80;1 input_2;desanocra;eyCG8SN523KQ;http://provider_2.tv:8080;1 -"#; +"; #[test] fn test_read_inputs_xtream_as_m3u() { let reader = BufReader::new(Cursor::new(XTREAM_BATCH)); let result = csv_read_inputs_from_reader(InputType::M3uBatch, reader); - assert_eq!(result.is_ok(), true); + assert!(result.is_ok()); let aliases = result.unwrap(); - assert_eq!(aliases.is_empty(), false); + assert!(!aliases.is_empty()); for config in aliases { - assert_eq!(config.url.contains("username"), true); + assert!(config.url.contains("username")); } } @@ -215,11 +215,11 @@ input_2;desanocra;eyCG8SN523KQ;http://provider_2.tv:8080;1 fn test_read_inputs_m3u_as_m3u() { let reader = BufReader::new(Cursor::new(M3U_BATCH)); let result = csv_read_inputs_from_reader(InputType::M3uBatch, reader); - assert_eq!(result.is_ok(), true); + assert!(result.is_ok()); let aliases = result.unwrap(); - assert_eq!(aliases.is_empty(), false); + assert!(!aliases.is_empty()); for config in aliases { - assert_eq!(config.url.contains("username"), true); + assert!(config.url.contains("username")); } } @@ -227,11 +227,11 @@ input_2;desanocra;eyCG8SN523KQ;http://provider_2.tv:8080;1 fn test_read_inputs_xtream_as_xtream() { let reader = BufReader::new(Cursor::new(XTREAM_BATCH)); let result = csv_read_inputs_from_reader(InputType::XtreamBatch, reader); - assert_eq!(result.is_ok(), true); + assert!(result.is_ok()); let aliases = result.unwrap(); - assert_eq!(aliases.is_empty(), false); + assert!(!aliases.is_empty()); for config in aliases { - assert_eq!(config.url.contains("username"), false); + assert!(!config.url.contains("username")); } } @@ -239,11 +239,11 @@ input_2;desanocra;eyCG8SN523KQ;http://provider_2.tv:8080;1 fn test_read_inputs_m3u_as_xtream() { let reader = BufReader::new(Cursor::new(M3U_BATCH)); let result = csv_read_inputs_from_reader(InputType::XtreamBatch, reader); - assert_eq!(result.is_ok(), true); + assert!(result.is_ok()); let aliases = result.unwrap(); - assert_eq!(aliases.is_empty(), false); + assert!(!aliases.is_empty()); for config in aliases { - assert_eq!(config.url.contains("username"), false); + assert!(!config.url.contains("username")); } }