use std::cmp::Ordering;
pub fn compare_files(left: &str, right: &str) -> Ordering {
compare(left, right, true)
}
pub fn compare_directories(left: &str, right: &str) -> Ordering {
compare(left, right, false)
}
pub fn sort_files(paths: &mut [String]) {
paths.sort_by(|left, right| compare_files(left, right));
}
pub fn sort_directories(directories: &mut [String]) {
directories.sort_by(|left, right| compare_directories(left, right));
}
fn compare(left: &str, right: &str, leaf_is_file: bool) -> Ordering {
let mut left_components = components(left).peekable();
let mut right_components = components(right).peekable();
loop {
let (left_name, right_name) = match (left_components.next(), right_components.next()) {
(None, None) => return Ordering::Equal,
(None, Some(_)) => return Ordering::Less,
(Some(_), None) => return Ordering::Greater,
(Some(left_name), Some(right_name)) => (left_name, right_name),
};
let left_is_file = leaf_is_file && left_components.peek().is_none();
let right_is_file = leaf_is_file && right_components.peek().is_none();
match (left_is_file, right_is_file) {
(true, false) => return Ordering::Less,
(false, true) => return Ordering::Greater,
_ => {}
}
if left_name != right_name {
return is_visible(left_name)
.cmp(&is_visible(right_name))
.then_with(|| left_name.cmp(right_name));
}
}
}
fn components(path: &str) -> impl Iterator<Item = &str> {
path.split('/').filter(|component| !component.is_empty())
}
fn is_visible(name: &str) -> bool {
!name.starts_with('.')
}