normal_paths/
lib.rs

1//! Performs path normalization for *nix and Windows systems.
2//!
3//! Windows and Unix-like systems handle glob patterns completely differently.
4//! This library is meant to paper over the differences between the two in order
5//! to simplify the construction of cross-platform applications.
6
7use glob::Paths;
8use std::io;
9use std::path::{Path, PathBuf};
10use walkdir::WalkDir;
11
12pub enum PathIter {
13    Directory(walkdir::IntoIter),
14    File(Option<PathBuf>),
15    Glob(Paths),
16}
17
18impl Iterator for PathIter {
19    type Item = io::Result<PathBuf>;
20
21    fn next(&mut self) -> Option<Self::Item> {
22        match self {
23            PathIter::Directory(dir) => {
24                let next = dir.next()?;
25                Some(next.map(|x| x.into_path()).map_err(|e| e.into()))
26            }
27            PathIter::File(path) => path.take().map(Ok),
28            PathIter::Glob(paths) => {
29                let next = paths.next()?;
30                Some(
31                    next.map(|x| x.as_path().into())
32                        .map_err(|e| io::Error::new(io::ErrorKind::Other, e)),
33                )
34            }
35        }
36    }
37}
38
39pub fn extract_paths(path: &str) -> io::Result<PathIter> {
40    {
41        let path: &Path = path.as_ref();
42
43        // Not a glob
44        if path.exists() {
45            if path.is_file() {
46                return Ok(PathIter::File(Some(path.into())));
47            } else {
48                let iter = WalkDir::new(path).into_iter();
49                return Ok(PathIter::Directory(iter));
50            }
51        }
52    }
53
54    glob::glob(path)
55        .map(PathIter::Glob)
56        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
57}