Add multiple path support (#182)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Adding support for multiple paths. (panic) - Started adding multiple file support - fd panics with multiple files right now * Moved the ctrlc handler to main. - Moved the ctrlc handler to main so we can search multiple files * Tests now allow custom directory setup - TestEnv::new() now takes two arguments, the directories to create and the files to create inside those directories. * rust-fmt changes * rust-fmt changes * Moving code around, no need to do everything in one big loop - PathDisplay was never actually used for anything, removed it during refactor of main - Removed redundant logic for absolute paths - Moved code placed needlessly inside a loop in the last commit outside of that loop. * Moving code around, no need to do everything in one big loop - PathDisplay was never actually used for anything, removed it during refactor of main - Removed redundant logic for absolute paths - Moved code placed needlessly inside a loop in the last commit outside of that loop. * Removed commented code in testenv * Refactored walk::scan to accept the path buffer vector. Using the ParallelWalker allows for multithreaded searching of multiple directories * Moved ctrlc handler back into walker, it is only called once from main now. * Moved the colored output check back to it's original place * Removing shell-escape, not sure how it got added... * Added test for `fd 'a.foo' test1` to show that a.foo is only found in the test1 and not the test2 direcotry * Removing side effect from walk::scan, `dir_vec` is no longer a mutable reference and an iterator is being used instead. * Running rustfmt to format code correctly
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+115 added−82 removed
- tests:+70 added−34 removed
- other:+45 added−48 removed
Provenance
- Commit
51aea57- Tree
9a3bf8e- Author
Dock <dockconnellyoneal@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
8914b43
7 files changed+115 added−82 removed
modified:src/app.rs+1 added-1 removed
122 unmodified lines123 .takes_value(true)124 .hidden(true),125 )126 .arg(arg("pattern"))127- .arg(arg("path"))127+ .arg(arg("path").multiple(true))128 }129 130 #[cfg_attr(rustfmt, rustfmt_skip)]131 fn usage() -> HashMap<&'static str, Help> {91 unmodified linesmodified:src/internal.rs-13 removed
13 unmodified lines14 use lscolors::LsColors;15 use walk::FileType;16 use regex_syntax::{Expr, ExprBuilder};17 18-/// Defines how to display search result paths.19-#[derive(PartialEq)]20-pub enum PathDisplay {21- /// As an absolute path22- Absolute,23-24- /// As a relative path25- Relative,26-}27-18 /// Configuration options for *fd*.19 pub struct FdOptions {20 /// Whether the search is case-sensitive or case-insensitive.21 pub case_sensitive: bool,30 unmodified lines52 /// provide a sorted output, in case the total execution time is shorter than53 /// `max_buffer_time`.54 pub max_buffer_time: Option<time::Duration>,55 66- /// Display results as relative or absolute path.67- pub path_display: PathDisplay,68-56 /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines57 /// how to style different filetypes.58 pub ls_colors: Option<LsColors>,59 45 unmodified linesmodified:src/main.rs+25 added-22 removed
38 unmodified lines39 use atty::Stream;40 use regex::RegexBuilder;41 42 use exec::CommandTemplate;43-use internal::{error, pattern_has_uppercase_char, FdOptions, PathDisplay};43+use internal::{error, pattern_has_uppercase_char, FdOptions};44 use lscolors::LsColors;45 use walk::FileType;46 47 fn main() {7 unmodified lines55 if !fshelper::is_dir(current_dir) {56 error("Error: could not get current directory.");57 }58 59- // Get the root directory for the search60- let mut root_dir_buf = match matches.value_of("path") {61- Some(path) => PathBuf::from(path),62- None => current_dir.to_path_buf(),59+ //Get one or more root directories to search.60+ let mut dir_vec: Vec<_> = match matches.values_of("path") {61+ Some(paths) => {62+ paths63+ .map(|path| {64+ let path_buffer = PathBuf::from(path);65+ if !fshelper::is_dir(&path_buffer) {66+ error(&format!(67+ "Error: '{}' is not a directory.",68+ path_buffer.to_string_lossy()69+ ));70+ }71+ path_buffer72+ })73+ .collect::<Vec<_>>()74+ }75+ None => vec![current_dir.to_path_buf()],76 };64- if !fshelper::is_dir(&root_dir_buf) {65- error(&format!(66- "Error: '{}' is not a directory.",67- root_dir_buf.to_string_lossy()68- ));69- }77 71- let path_display = if matches.is_present("absolute-path") || root_dir_buf.is_absolute() {72- PathDisplay::Absolute73- } else {74- PathDisplay::Relative75- };76-77- if path_display == PathDisplay::Absolute && root_dir_buf.is_relative() {78- root_dir_buf = fshelper::absolute_path(root_dir_buf.as_path()).unwrap();78+ if matches.is_present("absolute-path") {79+ dir_vec = dir_vec80+ .iter()81+ .map(|path_buffer| fshelper::absolute_path(&path_buffer).unwrap())82+ .collect();83 }80- let root_dir = root_dir_buf.as_path();84 85 // The search will be case-sensitive if the command line flag is set or86 // if the pattern has an uppercase character (smart case).87 let case_sensitive = !matches.is_present("ignore-case") &&46 unmodified lines134 max_buffer_time: matches135 .value_of("max-buffer-time")136 .and_then(|n| u64::from_str_radix(n, 10).ok())137 .map(time::Duration::from_millis),135- path_display,138 ls_colors,139 file_type: match matches.value_of("file-type") {140 Some("f") | Some("file") => FileType::RegularFile,141 Some("d") |10 unmodified lines152 .map(|v| v.map(|p| String::from("!") + p).collect())153 .unwrap_or_else(|| vec![]),154 };155 156+157 match RegexBuilder::new(pattern)158 .case_insensitive(!config.case_sensitive)159 .dot_matches_new_line(true)160 .build() {158- Ok(re) => walk::scan(root_dir, Arc::new(re), Arc::new(config)),161+ Ok(re) => walk::scan(&dir_vec, Arc::new(re), Arc::new(config)),162 Err(err) => error(err.description()),163 }164 }modified:src/walk.rs+19 added-11 removed
11 unmodified lines12 use fshelper;13 use internal::{error, FdOptions};14 use output;15 16-use std::path::Path;16+use std::path::PathBuf;17 use std::sync::{Arc, Mutex};18 use std::sync::atomic::{AtomicBool, Ordering};19 use std::sync::mpsc::channel;20 use std::thread;26 unmodified lines47 ///48 /// If the `--exec` argument was supplied, this will create a thread pool for executing49 /// jobs in parallel from a given command line and the discovered paths. Otherwise, each50 /// path will simply be written to standard output.51-pub fn scan(root: &Path, pattern: Arc<Regex>, config: Arc<FdOptions>) {51+pub fn scan(path_vec: &Vec<PathBuf>, pattern: Arc<Regex>, config: Arc<FdOptions>) {52+ let mut path_iter = path_vec.iter();53+ let first_path_buf = path_iter.next().expect(54+ "Error: Path vector can not be empty",55+ );56 let (tx, rx) = channel();57 let threads = config.threads;58 55- let mut override_builder = OverrideBuilder::new(root);59+ let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());60 61 for pattern in &config.exclude_patterns {62 let res = override_builder.add(pattern);63 if res.is_err() {3 unmodified lines67 let overrides = override_builder.build().unwrap_or_else(|_| {68 error("Mismatch in exclude patterns");69 });70 67- let walker = WalkBuilder::new(root)71+ let mut walker = WalkBuilder::new(first_path_buf.as_path());72+ walker73 .hidden(config.ignore_hidden)74 .ignore(config.read_ignore)75 .git_ignore(config.read_gitignore)76 .parents(config.read_ignore || config.read_gitignore)77 .git_global(config.read_gitignore)78 .git_exclude(config.read_gitignore)79 .overrides(overrides)80 .follow_links(config.follow_links)76- .max_depth(config.max_depth)77- .threads(threads)78- .build_parallel();81+ .max_depth(config.max_depth);82 80- let wants_to_quit = Arc::new(AtomicBool::new(false));83+ for path_entry in path_iter {84+ walker.add(path_entry.as_path());85+ }86 87+ let parallel_walker = walker.threads(threads).build_parallel();88+89+ let wants_to_quit = Arc::new(AtomicBool::new(false));90 if let Some(_) = config.ls_colors {91 let wq = Arc::clone(&wants_to_quit);92 ctrlc::set_handler(move || { wq.store(true, Ordering::Relaxed); }).unwrap();93 }94+95 // Spawn the thread that receives all results through the channel.96 let rx_config = Arc::clone(&config);97 let receiver_thread = thread::spawn(move || {98 // This will be set to `Some` if the `--exec` argument was supplied.73 unmodified lines172 }173 });174 175 // Spawn the sender threads.167- walker.run(|| {176+ parallel_walker.run(|| {177 let config = Arc::clone(&config);178 let pattern = Arc::clone(&pattern);179 let tx_thread = tx.clone();171- let root = root.to_owned();180 181 Box::new(move |entry_o| {182 let entry = match entry_o {183 Ok(e) => e,1 unmodified line185 };186 187 let entry_path = entry.path();188 181- if entry_path == root {189+ if entry.depth() == 0 {190 return ignore::WalkState::Continue;191 }192 193 // Filter out unwanted file types.56 unmodified linesmodified:tests/testenv/mod.rs+12 added-14 removed
33 unmodified lines34 fd_exe: PathBuf,35 }36 37 /// Create the working directory and the test files.38-fn create_working_directory() -> Result<TempDir, io::Error> {38+fn create_working_directory(39+ directories: &[&'static str],40+ files: &[&'static str],41+) -> Result<TempDir, io::Error> {42 let temp_dir = TempDir::new("fd-tests")?;43 44 {45 let root = temp_dir.path();46 47+ for directory in directories {44- fs::create_dir_all(root.join("one/two/three"))?;48+ fs::create_dir_all(root.join(directory))?;49+ }50 46- fs::File::create(root.join("a.foo"))?;47- fs::File::create(root.join("one/b.foo"))?;48- fs::File::create(root.join("one/two/c.foo"))?;49- fs::File::create(root.join("one/two/C.Foo2"))?;50- fs::File::create(root.join("one/two/three/d.foo"))?;51- fs::create_dir(root.join("one/two/three/directory_foo"))?;52- fs::File::create(root.join("ignored.foo"))?;53- fs::File::create(root.join("gitignored.foo"))?;54- fs::File::create(root.join(".hidden.foo"))?;55- fs::File::create(root.join("e1 e2"))?;51+ for file in files {52+ fs::File::create(root.join(file))?;53+ }54 55 #[cfg(unix)] unix::fs::symlink(root.join("one/two"), root.join("symlink"))?;56 57 // Note: creating symlinks on Windows requires the `SeCreateSymbolicLinkPrivilege` which77 unmodified lines135 lines.join("\n")136 }137 138 impl TestEnv {141- pub fn new() -> TestEnv {142- let temp_dir = create_working_directory().expect("working directory");139+ pub fn new(directories: &[&'static str], files: &[&'static str]) -> TestEnv {140+ let temp_dir = create_working_directory(directories, files).expect("working directory");141 let fd_exe = find_fd_exe();142 143 TestEnv {144 temp_dir: temp_dir,51 unmodified linesmodified:tests/tests.rs+58 added-20 removed
13 unmodified lines14 15 use testenv::TestEnv;16 use regex::escape;17 18+static DEFAULT_DIRS: &'static [&'static str] = &["one/two/three", "one/two/three/directory_foo"];19+20+static DEFAULT_FILES: &'static [&'static str] = &[21+ "a.foo",22+ "one/b.foo",23+ "one/two/c.foo",24+ "one/two/C.Foo2",25+ "one/two/three/d.foo",26+ "ignored.foo",27+ "gitignored.foo",28+ ".hidden.foo",29+ "e1 e2",30+];31+32 fn get_absolute_root_path(env: &TestEnv) -> String {33 let path = env.test_root()34 .canonicalize()35 .expect("absolute path")9 unmodified lines45 46 /// Simple tests47 #[test]48 fn test_simple() {35- let te = TestEnv::new();49+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);50 51 te.assert_output(&["a.foo"], "a.foo");52 te.assert_output(&["b.foo"], "one/b.foo");53 te.assert_output(&["d.foo"], "one/two/three/d.foo");23 unmodified lines77 symlink",78 );79 }80 81+/// Test multiple directory searches82+#[test]83+fn test_multi_file() {84+ let dirs = &["test1", "test2"];85+ let files = &["test1/a.foo", "test1/b.foo", "test2/a.foo"];86+ let te = TestEnv::new(dirs, files);87+ te.assert_output(88+ &["a.foo", "test1", "test2"],89+ "test1/a.foo90+ test2/a.foo",91+ );92+93+ te.assert_output(94+ &["", "test1", "test2"],95+ "test1/a.foo96+ test2/a.foo97+ test1/b.foo",98+ );99+100+ te.assert_output(&["a.foo", "test1"], "test1/a.foo");101+102+ te.assert_output(&["b.foo", "test1", "test2"], "test1/b.foo");103+}104+105 /// Explicit root path106 #[test]107 fn test_explicit_root_path() {70- let te = TestEnv::new();108+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);109 110 te.assert_output(111 &["foo", "one"],112 "one/b.foo33 unmodified lines146 147 /// Regex searches148 #[test]149 fn test_regex_searches() {112- let te = TestEnv::new();150+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);151 152 te.assert_output(153 &["[a-c].foo"],154 "a.foo12 unmodified lines167 168 /// Smart case169 #[test]170 fn test_smart_case() {133- let te = TestEnv::new();171+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);172 173 te.assert_output(174 &["c.foo"],175 "one/two/c.foo15 unmodified lines191 192 /// Case sensitivity (--case-sensitive)193 #[test]194 fn test_case_sensitive() {157- let te = TestEnv::new();195+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);196 197 te.assert_output(&["--case-sensitive", "c.foo"], "one/two/c.foo");198 199 te.assert_output(&["--case-sensitive", "C.Foo"], "one/two/C.Foo2");6 unmodified lines206 207 /// Case insensitivity (--ignore-case)208 #[test]209 fn test_case_insensitive() {172- let te = TestEnv::new();210+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);211 212 te.assert_output(213 &["--ignore-case", "C.Foo"],214 "one/two/c.foo9 unmodified lines224 225 /// Full path search (--full-path)226 #[test]227 fn test_full_path() {190- let te = TestEnv::new();228+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);229 230 let root = te.system_root();231 let prefix = escape(&root.to_string_lossy());232 9 unmodified lines242 243 /// Hidden files (--hidden)244 #[test]245 fn test_hidden() {208- let te = TestEnv::new();246+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);247 248 te.assert_output(249 &["--hidden", "foo"],250 ".hidden.foo8 unmodified lines259 260 /// Ignored files (--no-ignore)261 #[test]262 fn test_no_ignore() {225- let te = TestEnv::new();263+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);264 265 te.assert_output(266 &["--no-ignore", "foo"],267 "a.foo22 unmodified lines290 291 /// VCS ignored files (--no-ignore-vcs)292 #[test]293 fn test_no_ignore_vcs() {256- let te = TestEnv::new();294+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);295 296 te.assert_output(297 &["--no-ignore-vcs", "foo"],298 "a.foo8 unmodified lines307 308 /// Ignored files with ripgrep aliases (-u / -uu)309 #[test]310 fn test_no_ignore_aliases() {273- let te = TestEnv::new();311+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);312 313 te.assert_output(314 &["-u", "foo"],315 "a.foo22 unmodified lines338 339 /// Symlinks (--follow)340 #[test]341 fn test_follow() {304- let te = TestEnv::new();342+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);343 344 te.assert_output(345 &["--follow", "c.foo"],346 "one/two/c.foo5 unmodified lines352 353 /// Null separator (--print0)354 #[test]355 fn test_print0() {318- let te = TestEnv::new();356+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);357 358 te.assert_output(359 &["--print0", "foo"],360 "a.fooNULL7 unmodified lines368 369 /// Maximum depth (--max-depth)370 #[test]371 fn test_max_depth() {334- let te = TestEnv::new();372+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);373 374 te.assert_output(375 &["--max-depth", "3"],376 "a.foo28 unmodified lines405 406 /// Absolute paths (--absolute-path)407 #[test]408 fn test_absolute_path() {371- let te = TestEnv::new();409+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);410 411 let abs_path = get_absolute_root_path(&te);412 413 te.assert_output(43 unmodified lines457 458 /// File type filter (--type)459 #[test]460 fn test_type() {423- let te = TestEnv::new();461+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);462 463 te.assert_output(464 &["--type", "f"],465 "a.foo17 unmodified lines483 484 /// File extension (--extension)485 #[test]486 fn test_extension() {449- let te = TestEnv::new();487+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);488 489 te.assert_output(490 &["--extension", "foo"],491 "a.foo15 unmodified lines507 508 /// Symlinks misc509 #[test]510 fn test_symlink() {473- let te = TestEnv::new();511+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);512 513 let abs_path = get_absolute_root_path(&te);514 515 // From: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html91 unmodified lines607 608 /// Exclude patterns (--exclude)609 #[test]610 fn test_excludes() {573- let te = TestEnv::new();611+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);612 613 te.assert_output(614 &["--exclude", "*.foo"],615 "one41 unmodified lines657 658 /// Shell script execution (--exec)659 #[test]660 fn test_exec() {623- let te = TestEnv::new();661+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);662 663 let abs_path = get_absolute_root_path(&te);664 665 // TODO Windows tests: D:file.txt \file.txt \\server\share\file.txt ...67 unmodified linesmodified:Cargo.toml-1 removed
39 unmodified lines4041424344444546477 unmodified lines39 unmodified linesnum_cpus = "1.6.2"regex = "0.2"regex-syntax = "0.4"ctrlc = "3.0"shell-escape = "0.1.3"
[target.'cfg(all(unix, not(target_os = "redox")))'.dependencies]libc = "0.2"
7 unmodified lines