From 8b4b53a9fc4ca65c3335a9e36f93364a687d7268 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cyryl=20P=C5=82otnicki?= Date: Fri, 22 Oct 2021 22:14:51 +0100 Subject: [PATCH] cleanup lock acquisition --- src/index/lock.rs | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/index/lock.rs b/src/index/lock.rs index ddb4ffd..a886cfc 100644 --- a/src/index/lock.rs +++ b/src/index/lock.rs @@ -71,26 +71,25 @@ impl Lock { fn sole_lock(lock_id: Uuid, index_directory: &Path) -> Result { let my_lock_file_path = Lock::lock_file_path(index_directory, lock_id)?; - let walker = WalkDir::new(index_directory); - let all_locks: Vec<_> = walker - .into_iter() - .filter_map(|e| e.ok()) - .filter(|e| e.file_name().to_string_lossy().ends_with(FILE_EXTENSION)) - .collect(); - if all_locks.len() != 1 { + let all_locks_count = + Lock::count_files(|e| e.file_name().to_string_lossy().ends_with(FILE_EXTENSION), index_directory)?; + if all_locks_count != 1 { return Ok(false); } - let walker = WalkDir::new(index_directory); - let my_locks: Vec<_> = walker - .into_iter() - .filter_map(|e| e.ok()) - .filter(|e| e.path() == my_lock_file_path) - .collect(); - if my_locks.len() != 1 { + let my_locks_count = Lock::count_files(|e| e.path() == my_lock_file_path, index_directory)?; + if my_locks_count != 1 { return Ok(false); } - let result = all_locks.first().unwrap().path() == my_locks.first().unwrap().path(); - Ok(result) + Ok(true) + } + + fn count_files

(predicate: P, directory: &Path) -> Result + where + P: Fn(&walkdir::DirEntry) -> bool, + { + let walker = WalkDir::new(directory); + let matching = walker.into_iter().filter_map(|e| e.ok()).filter(predicate); + Ok(matching.count()) } fn create_lock_file(lock_id: Uuid, index_directory: &Path) -> Result<()> {