xuko 0.10.0

Rust utility library
Documentation
//! Path module
//!
//! Provides utilities for [`std::path::Path`]s

use std::fs::read_dir;
use std::path::{Path, PathBuf};

/// Search for file or directory `stub` in `search_locations`
pub fn search_in_paths(search_locations: &[&Path], stub: &str) -> Option<PathBuf> {
    for location in search_locations {
        let p = Path::new(location).join(stub);

        match p.try_exists() {
            Ok(true) => return Some(p),
            _ => continue,
        }
    }

    None
}

/// Search for `stub` in `default_dir` and its parents.
pub fn search_parents(default_dir: &Path, stub: &str) -> Option<PathBuf> {
    let f = default_dir.join(stub);
    if f.exists() {
        Some(f)
    } else {
        search_parents(default_dir.parent()?, stub)
    }
}

/// Search for `stub` in `default_dir` and its children.
pub fn search_recursive(default_dir: &Path, stub: &str) -> Option<PathBuf> {
    let first_try = default_dir.join(stub);
    if first_try.exists() {
        return Some(first_try);
    }

    let mut readdir = read_dir(default_dir).ok()?;

    while let Some(r) = readdir.next().map(|v| v.ok()) {
        let entry = r?;

        if entry.file_type().ok()?.is_dir()
            && let Some(p) = search_recursive(&entry.path(), stub)
        {
            return Some(p);
        }
    }

    None
}