Skip to content

Commit

Permalink
Refactor dirlike into FileType.
Browse files Browse the repository at this point in the history
  • Loading branch information
Allen Hsu committed Aug 17, 2020
1 parent 99b2bb3 commit e3bb742
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 15 deletions.
7 changes: 7 additions & 0 deletions src/meta/filetype.rs
Expand Up @@ -79,6 +79,13 @@ impl FileType {
FileType::Special
}
}

pub fn is_dirlike(&self) -> bool {
match self {
FileType::Directory { .. } | FileType::SymLink { is_dir: true } => true,
_ => false,
}
}
}

impl FileType {
Expand Down
23 changes: 8 additions & 15 deletions src/sort.rs
@@ -1,17 +1,19 @@
use crate::flags::{DirOrderFlag, Flags, SortFlag, SortOrder};
use crate::meta::{FileType, Meta};
use crate::meta::Meta;
use std::cmp::Ordering;

pub type Sorter = Box<dyn Fn(&Meta, &Meta) -> Ordering>;

pub fn create_sorter(flags: &Flags) -> Sorter {
let mut sorters: Vec<(SortOrder, Sorter)> = vec![];
type SortFn = fn(&Meta, &Meta) -> Ordering;

let mut sorters: Vec<(SortOrder, SortFn)> = vec![];
match flags.directory_order {
DirOrderFlag::First => {
sorters.push((SortOrder::Default, Box::new(with_dirs_first)));
sorters.push((SortOrder::Default, with_dirs_first));
}
DirOrderFlag::Last => {
sorters.push((SortOrder::Reverse, Box::new(with_dirs_first)));
sorters.push((SortOrder::Reverse, with_dirs_first));
}
DirOrderFlag::None => {}
};
Expand All @@ -20,7 +22,7 @@ pub fn create_sorter(flags: &Flags) -> Sorter {
SortFlag::Size => by_size,
SortFlag::Time => by_date,
};
sorters.push((flags.sort_order, Box::new(other_sort)));
sorters.push((flags.sort_order, other_sort));

Box::new(move |a, b| {
for (direction, sorter) in sorters.iter() {
Expand All @@ -39,16 +41,7 @@ pub fn create_sorter(flags: &Flags) -> Sorter {
}

fn with_dirs_first(a: &Meta, b: &Meta) -> Ordering {
match (a.file_type, b.file_type) {
(FileType::Directory { .. }, FileType::Directory { .. }) => Ordering::Equal,
(FileType::Directory { .. }, FileType::SymLink { is_dir: true }) => Ordering::Equal,
(FileType::SymLink { is_dir: true }, FileType::Directory { .. }) => Ordering::Equal,
(FileType::Directory { .. }, _) => Ordering::Less,
(_, FileType::Directory { .. }) => Ordering::Greater,
(FileType::SymLink { is_dir: true }, _) => Ordering::Less,
(_, FileType::SymLink { is_dir: true }) => Ordering::Greater,
_ => Ordering::Equal,
}
b.file_type.is_dirlike().cmp(&a.file_type.is_dirlike())
}

fn by_size(a: &Meta, b: &Meta) -> Ordering {
Expand Down

0 comments on commit e3bb742

Please sign in to comment.