use std::{borrow::Borrow, fmt::Display};
use regex::Regex;
use crate::modes::{FileInfo, FileKind};
#[derive(Clone)]
pub enum FilterKind {
Extension(String),
Name(String),
Directory,
All,
}
impl FilterKind {
#[must_use]
pub fn from_input(input: &str) -> Self {
let words: Vec<&str> = input.split_whitespace().collect();
match words.first() {
Some(&"d") => Self::Directory,
Some(&"e") if words.len() > 1 => Self::Extension(words[1].to_owned()),
Some(&"n") if words.len() > 1 => Self::Name(words[1].to_owned()),
_ => Self::All,
}
}
#[must_use]
pub fn filter_by(&self, fileinfo: &FileInfo, keep_dirs: bool) -> bool {
match self {
Self::Extension(ext) => Self::filter_by_extension(fileinfo, ext, keep_dirs),
Self::Name(filename) => Self::filter_by_name(fileinfo, filename, keep_dirs),
Self::Directory => Self::filter_directory(fileinfo),
Self::All => true,
}
}
fn filter_by_extension(fileinfo: &FileInfo, ext: &str, keep_dirs: bool) -> bool {
let file_ext: &str = fileinfo.extension.borrow();
file_ext == ext || keep_dirs && fileinfo.is_dir()
}
fn filter_by_name(fileinfo: &FileInfo, filename: &str, keep_dirs: bool) -> bool {
if keep_dirs && fileinfo.is_dir() {
true
} else {
let Ok(re) = Regex::new(filename) else {
return false;
};
re.is_match(&fileinfo.filename)
}
}
fn filter_directory(fileinfo: &FileInfo) -> bool {
matches!(fileinfo.file_kind, FileKind::Directory)
}
}
impl Display for FilterKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::Directory => write!(f, "Filter: Directory only"),
Self::Extension(s) => write!(f, "Filter: by extension \"{s}\""),
Self::Name(s) => write!(f, "Filter: by name \"{s}\""),
Self::All => write!(f, ""),
}
}
}