Skip to content
Myr

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

authored by Dock · committed by David Peter · parent 8914b43 · Browse files · 7 files+115 added−82 removed
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

7 files+115 added−82 removed

modified:src/app.rs+1 added-1 removed
122 unmodified lines
123 .takes_value(true)124 .hidden(true),125 )126 .arg(arg("pattern"))127 .arg(arg("path"))127 .arg(arg("path").multiple(true))128}129130#[cfg_attr(rustfmt, rustfmt_skip)]131fn usage() -> HashMap<&'static str, Help> {
91 unmodified lines
modified:src/internal.rs-13 removed
13 unmodified lines
14use lscolors::LsColors;15use walk::FileType;16use regex_syntax::{Expr, ExprBuilder};1718/// Defines how to display search result paths.19#[derive(PartialEq)]20pub enum PathDisplay {21 /// As an absolute path22 Absolute,2324 /// As a relative path25 Relative,26}2718/// Configuration options for *fd*.19pub struct FdOptions {20 /// Whether the search is case-sensitive or case-insensitive.21 pub case_sensitive: bool,
30 unmodified lines
52 /// provide a sorted output, in case the total execution time is shorter than53 /// `max_buffer_time`.54 pub max_buffer_time: Option<time::Duration>,5566 /// Display results as relative or absolute path.67 pub path_display: PathDisplay,6856 /// `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 lines
modified:src/main.rs+25 added-22 removed
38 unmodified lines
39use atty::Stream;40use regex::RegexBuilder;4142use exec::CommandTemplate;43use internal::{error, pattern_has_uppercase_char, FdOptions, PathDisplay};43use internal::{error, pattern_has_uppercase_char, FdOptions};44use lscolors::LsColors;45use walk::FileType;4647fn main() {
7 unmodified lines
55 if !fshelper::is_dir(current_dir) {56 error("Error: could not get current directory.");57 }5859 // 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 }7771 let path_display = if matches.is_present("absolute-path") || root_dir_buf.is_absolute() {72 PathDisplay::Absolute73 } else {74 PathDisplay::Relative75 };7677 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();8485 // 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 lines
134 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 lines
152 .map(|v| v.map(|p| String::from("!") + p).collect())153 .unwrap_or_else(|| vec![]),154 };155156157 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 lines
12use fshelper;13use internal::{error, FdOptions};14use output;1516use std::path::Path;16use std::path::PathBuf;17use std::sync::{Arc, Mutex};18use std::sync::atomic::{AtomicBool, Ordering};19use std::sync::mpsc::channel;20use std::thread;
26 unmodified lines
47///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.51pub fn scan(root: &Path, pattern: Arc<Regex>, config: Arc<FdOptions>) {51pub 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;5855 let mut override_builder = OverrideBuilder::new(root);59 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());6061 for pattern in &config.exclude_patterns {62 let res = override_builder.add(pattern);63 if res.is_err() {
3 unmodified lines
67 let overrides = override_builder.build().unwrap_or_else(|_| {68 error("Mismatch in exclude patterns");69 });7067 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);8280 let wants_to_quit = Arc::new(AtomicBool::new(false));83 for path_entry in path_iter {84 walker.add(path_entry.as_path());85 }8687 let parallel_walker = walker.threads(threads).build_parallel();8889 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 }9495 // 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 lines
172 }173 });174175 // 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();180181 Box::new(move |entry_o| {182 let entry = match entry_o {183 Ok(e) => e,
1 unmodified line
185 };186187 let entry_path = entry.path();188181 if entry_path == root {189 if entry.depth() == 0 {190 return ignore::WalkState::Continue;191 }192193 // Filter out unwanted file types.
56 unmodified lines
modified:tests/testenv/mod.rs+12 added-14 removed
33 unmodified lines
34 fd_exe: PathBuf,35}3637/// Create the working directory and the test files.38fn create_working_directory() -> Result<TempDir, io::Error> {38fn create_working_directory(39 directories: &[&'static str],40 files: &[&'static str],41) -> Result<TempDir, io::Error> {42 let temp_dir = TempDir::new("fd-tests")?;4344 {45 let root = temp_dir.path();4647 for directory in directories {44 fs::create_dir_all(root.join("one/two/three"))?;48 fs::create_dir_all(root.join(directory))?;49 }5046 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 }5455 #[cfg(unix)] unix::fs::symlink(root.join("one/two"), root.join("symlink"))?;5657 // Note: creating symlinks on Windows requires the `SeCreateSymbolicLinkPrivilege` which
77 unmodified lines
135 lines.join("\n")136}137138impl 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();142143 TestEnv {144 temp_dir: temp_dir,
51 unmodified lines
modified:tests/tests.rs+58 added-20 removed
13 unmodified lines
1415use testenv::TestEnv;16use regex::escape;1718static DEFAULT_DIRS: &'static [&'static str] = &["one/two/three", "one/two/three/directory_foo"];1920static 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];3132fn get_absolute_root_path(env: &TestEnv) -> String {33 let path = env.test_root()34 .canonicalize()35 .expect("absolute path")
9 unmodified lines
4546/// Simple tests47#[test]48fn test_simple() {35 let te = TestEnv::new();49 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);5051 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 lines
77 symlink",78 );79}8081/// Test multiple directory searches82#[test]83fn 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 );9293 te.assert_output(94 &["", "test1", "test2"],95 "test1/a.foo96 test2/a.foo97 test1/b.foo",98 );99100 te.assert_output(&["a.foo", "test1"], "test1/a.foo");101102 te.assert_output(&["b.foo", "test1", "test2"], "test1/b.foo");103}104105/// Explicit root path106#[test]107fn test_explicit_root_path() {70 let te = TestEnv::new();108 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);109110 te.assert_output(111 &["foo", "one"],112 "one/b.foo
33 unmodified lines
146147/// Regex searches148#[test]149fn test_regex_searches() {112 let te = TestEnv::new();150 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);151152 te.assert_output(153 &["[a-c].foo"],154 "a.foo
12 unmodified lines
167168/// Smart case169#[test]170fn test_smart_case() {133 let te = TestEnv::new();171 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);172173 te.assert_output(174 &["c.foo"],175 "one/two/c.foo
15 unmodified lines
191192/// Case sensitivity (--case-sensitive)193#[test]194fn test_case_sensitive() {157 let te = TestEnv::new();195 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);196197 te.assert_output(&["--case-sensitive", "c.foo"], "one/two/c.foo");198199 te.assert_output(&["--case-sensitive", "C.Foo"], "one/two/C.Foo2");
6 unmodified lines
206207/// Case insensitivity (--ignore-case)208#[test]209fn test_case_insensitive() {172 let te = TestEnv::new();210 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);211212 te.assert_output(213 &["--ignore-case", "C.Foo"],214 "one/two/c.foo
9 unmodified lines
224225/// Full path search (--full-path)226#[test]227fn test_full_path() {190 let te = TestEnv::new();228 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);229230 let root = te.system_root();231 let prefix = escape(&root.to_string_lossy());232
9 unmodified lines
242243/// Hidden files (--hidden)244#[test]245fn test_hidden() {208 let te = TestEnv::new();246 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);247248 te.assert_output(249 &["--hidden", "foo"],250 ".hidden.foo
8 unmodified lines
259260/// Ignored files (--no-ignore)261#[test]262fn test_no_ignore() {225 let te = TestEnv::new();263 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);264265 te.assert_output(266 &["--no-ignore", "foo"],267 "a.foo
22 unmodified lines
290291/// VCS ignored files (--no-ignore-vcs)292#[test]293fn test_no_ignore_vcs() {256 let te = TestEnv::new();294 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);295296 te.assert_output(297 &["--no-ignore-vcs", "foo"],298 "a.foo
8 unmodified lines
307308/// Ignored files with ripgrep aliases (-u / -uu)309#[test]310fn test_no_ignore_aliases() {273 let te = TestEnv::new();311 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);312313 te.assert_output(314 &["-u", "foo"],315 "a.foo
22 unmodified lines
338339/// Symlinks (--follow)340#[test]341fn test_follow() {304 let te = TestEnv::new();342 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);343344 te.assert_output(345 &["--follow", "c.foo"],346 "one/two/c.foo
5 unmodified lines
352353/// Null separator (--print0)354#[test]355fn test_print0() {318 let te = TestEnv::new();356 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);357358 te.assert_output(359 &["--print0", "foo"],360 "a.fooNULL
7 unmodified lines
368369/// Maximum depth (--max-depth)370#[test]371fn test_max_depth() {334 let te = TestEnv::new();372 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);373374 te.assert_output(375 &["--max-depth", "3"],376 "a.foo
28 unmodified lines
405406/// Absolute paths (--absolute-path)407#[test]408fn test_absolute_path() {371 let te = TestEnv::new();409 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);410411 let abs_path = get_absolute_root_path(&te);412413 te.assert_output(
43 unmodified lines
457458/// File type filter (--type)459#[test]460fn test_type() {423 let te = TestEnv::new();461 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);462463 te.assert_output(464 &["--type", "f"],465 "a.foo
17 unmodified lines
483484/// File extension (--extension)485#[test]486fn test_extension() {449 let te = TestEnv::new();487 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);488489 te.assert_output(490 &["--extension", "foo"],491 "a.foo
15 unmodified lines
507508/// Symlinks misc509#[test]510fn test_symlink() {473 let te = TestEnv::new();511 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);512513 let abs_path = get_absolute_root_path(&te);514515 // From: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html
91 unmodified lines
607608/// Exclude patterns (--exclude)609#[test]610fn test_excludes() {573 let te = TestEnv::new();611 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);612613 te.assert_output(614 &["--exclude", "*.foo"],615 "one
41 unmodified lines
657658/// Shell script execution (--exec)659#[test]660fn test_exec() {623 let te = TestEnv::new();661 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);662663 let abs_path = get_absolute_root_path(&te);664665 // TODO Windows tests: D:file.txt \file.txt \\server\share\file.txt ...
67 unmodified lines
modified:Cargo.toml-1 removed