From 850c274adc029165f84332b867c8031874054c57 Mon Sep 17 00:00:00 2001 From: beeb Date: Mon, 23 Jan 2023 22:28:48 +0100 Subject: [PATCH] refactor: use globwalk builder pattern --- src/output.rs | 2 +- src/params.rs | 44 ++++++++++++++++---------------------------- src/scanner.rs | 5 ++--- 3 files changed, 19 insertions(+), 32 deletions(-) diff --git a/src/output.rs b/src/output.rs index 22fba91..872b849 100644 --- a/src/output.rs +++ b/src/output.rs @@ -12,7 +12,7 @@ use std::{fs, io}; use unicode_segmentation::UnicodeSegmentation; fn format_path(path: &str, opts: &Params) -> Result { - let display_path = path.replace(&opts.get_directory()?, ""); + let display_path = path.replace(opts.get_directory()?.to_string_lossy().as_ref(), ""); let display_range = if display_path.chars().count() > 32 { display_path .graphemes(true) diff --git a/src/params.rs b/src/params.rs index 4703e02..23817ce 100644 --- a/src/params.rs +++ b/src/params.rs @@ -1,6 +1,8 @@ +use std::{fs, path::PathBuf}; + use anyhow::{anyhow, Result}; use clap::{Parser, ValueHint}; -use std::{fs, path::PathBuf}; +use globwalk::{GlobWalker, GlobWalkerBuilder}; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] @@ -30,35 +32,21 @@ impl Params { } } - pub fn get_directory(&self) -> Result { - let dir_pathbuf: PathBuf = self - .dir - .as_ref() - .unwrap_or(&std::env::current_dir()?) - .as_os_str() - .into(); - - let dir = fs::canonicalize(dir_pathbuf)? - .as_os_str() - .to_str() - .ok_or_else(|| anyhow!("Invalid directory"))? - .to_string(); - + pub fn get_directory(&self) -> Result { + let current_dir = std::env::current_dir()?; + let dir_path = self.dir.as_ref().unwrap_or(¤t_dir).as_path(); + let dir = fs::canonicalize(dir_path)?; Ok(dir) } - pub fn get_glob_patterns(&self) -> PathBuf { - match self.types.as_ref() { - Some(filetypes) => vec![ - self.get_directory().unwrap(), - String::from("**"), - format!("*.{{{filetypes}}}"), - ] - .iter() - .collect::(), - None => vec![self.get_directory().unwrap().as_str(), "**", "*"] - .iter() - .collect::(), - } + pub fn get_glob_walker(&self) -> Result { + let pattern: String = match self.types.as_ref() { + Some(filetypes) => format!("**/*{{{filetypes}}}"), + None => "**/*".to_string(), + }; + // TODO: add params for maximum depth and following symlinks, then pass them to this builder + GlobWalkerBuilder::from_patterns(self.get_directory()?, &[pattern]) + .build() + .map_err(|e| anyhow!(e)) } } diff --git a/src/scanner.rs b/src/scanner.rs index 7f94ed0..eb99b7f 100644 --- a/src/scanner.rs +++ b/src/scanner.rs @@ -39,9 +39,8 @@ pub fn duplicates(app_opts: &Params) -> Result>> { } fn scan(app_opts: &Params) -> Result> { - let glob_patterns = app_opts.get_glob_patterns().display().to_string(); - let glob_iter = globwalk::glob(glob_patterns)?; - let files = glob_iter + let walker = app_opts.get_glob_walker()?; + let files = walker .filter_map(Result::ok) .map(|file| file.into_path()) .filter(|fpath| fpath.is_file())