Sorting Glob Result


#1

How does one sort the results of a glob before processing in the given example (i.e. I want to sort files by some sort of filter)

use glob::glob;

for entry in glob("/media/**/*.jpg").expect("Failed to read glob pattern") {
 match entry {
     Ok(path) => println!("{:?}", path.display()),
     Err(e) => println!("{:?}", e),
 }
}

#2

You can collect the results of the glob into a Vec and sort that:

let mut v: Vec<_> = glob("/media/**/*.jpg").expect("Failed to read glob pattern").collect();
v.sort_by(...); // or sort_unstable_by() or any other sorting flavor
for entry in v {
   ...
}

#3

Awesome thanks. The sorting is a little odd though?

 files.sort_by(|a, b| a.unwrap().to_str().unwrap().cmp(b.unwrap().to_str().unwrap()));

#4

Oh, that iterator returns a Result. You can collect into a Result<Vec<PathBuf, GlobError>>:

let mut v: Result<Vec<_>, _> = glob("/media/**/*.jpg").expect("Failed to read glob pattern").collect();
let v = v.unwrap(); // now you have a Vec<PathBuf>
v.sort_by(...);
for entry in v {
   ...
}

Collecting into a Result<Vec<PathBuf>, GlobError>> here means that if any of the glob iterator items is an error, then you’ll get an Err value back; if no errors encountered, then you get the Ok variant with the PathBufs.