Thomas 7 hónapja
szülő
commit
9157716ac1
1 módosított fájl, 41 hozzáadás és 0 törlés
  1. 41 0
      src/helpers.rs

+ 41 - 0
src/helpers.rs

@@ -585,3 +585,44 @@ pub fn find_matching_file(dir: &Path, starts_with: &str, ends_with: &str) -> Opt
         })
 }
 
+/// Searches for the first file in the given directory whose file name
+/// satisfies the provided condition.
+///
+/// # Arguments
+///
+/// * `dir` - Path to the directory to search.
+/// * `condition` - A closure that takes a file name (`&str`) and returns `true`
+///   if the file matches the desired condition.
+///
+/// # Returns
+///
+/// An `Option<PathBuf>` containing the path to the first matching file,
+/// or `None` if no file matches or the directory can't be read.
+///
+/// # Examples
+///
+/// ```
+/// use std::path::Path;
+/// let result = find_file(Path::new("."), |name| name.ends_with(".rs"));
+/// ```
+pub fn find_file<F>(dir: &Path, condition: F) -> Option<PathBuf>
+where
+    F: Fn(&str) -> bool,
+{
+    fs::read_dir(dir).ok()?.find_map(|entry| {
+        let path = entry.ok()?.path();
+
+        if path.is_file()
+            && path
+                .file_name()
+                .and_then(|name| name.to_str())
+                .map(&condition)
+                .unwrap_or(false)
+        {
+            Some(path)
+        } else {
+            None
+        }
+    })
+}
+