Add --max-results=<count> option
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This new option can be used instead of piping to `head -n <count>` for improved performance: | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |:---|---:|---:|---:|---:| | `fd --max-buffer-time=0 flow.yaml` | 153.9 ± 2.5 | 151.3 | 170.3 | 4.21 ± 5.86 | | `fd --max-buffer-time=0 flow.yaml \| head -n 1` | 145.3 ± 17.4 | 111.0 | 180.2 | 3.98 ± 5.55 | | `fd --max-results=1 flow.yaml` | 36.5 ± 50.8 | 7.2 | 145.7 | 1.00 | Note: there is a large standard deviation on the last result due to the non-deterministic file system traversal. With `--max-results`, we don't have to traverse the whole filesystem tree, so it's all about luck. closes #472 closes #476
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+80 added−8 removed
- tests:+45 added−8 removed
- other:+35 added−0 removed
Provenance
- Commit
d43827f- Tree
6858599- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
ee673c9
8 files changed+80 added−8 removed
modified:doc/fd.1+3 added
78 unmodified lines79 .B \-0, \-\-print080 Separate search results by the null character (instead of newlines). Useful for piping results to81 .IR xargs .82 .TP83+.B \-\-max\-results count84+Limit the number of search results to 'count' and quit immediately.85+.TP86 .B \-\-show-errors87 Enable the display of filesystem errors for situations such as insufficient88 permissions or dead symlinks.89 .TP182 unmodified linesmodified:src/internal/opts.rs+3 added
79 unmodified lines80 pub show_filesystem_errors: bool,81 82 /// The separator used to print file paths.83 pub path_separator: Option<String>,84+85+ /// The maximum number of search results86+ pub max_results: Option<usize>,87 }modified:src/app.rs+11 added
250 unmodified lines251 .value_name("date|dur")252 .number_of_values(1),253 )254 .arg(255+ arg("max-results")256+ .long("max-results")257+ .takes_value(true)258+ .value_name("count")259+ .conflicts_with_all(&["exec", "exec-batch"])260+ .hidden_short_help(true),261+ )262+ .arg(263 arg("show-errors")264 .long("show-errors")265 .hidden_short_help(true)266 .overrides_with("show-errors"),197 unmodified lines464 '--change-older-than' can be used as an alias.\n\465 Examples:\n \466 --changed-before '2018-10-27 10:00:00'\n \467 --change-older-than 2weeks");468+ doc!(h, "max-results"469+ , "(hidden)"470+ , "Limit the number of search results to 'count' and quit immediately.");471 doc!(h, "show-errors"472 , "Enable display of filesystem errors"473 , "Enable the display of filesystem errors for situations such as insufficient permissions \474 or dead symlinks.");21 unmodified linesmodified:src/main.rs+4 added
277 unmodified lines278 size_constraints: size_limits,279 time_constraints,280 show_filesystem_errors: matches.is_present("show-errors"),281 path_separator,282+ max_results: matches283+ .value_of("max-results")284+ .and_then(|n| usize::from_str_radix(n, 10).ok())285+ .filter(|&n| n != 0),286 };287 288 match RegexBuilder::new(&pattern_regex)289 .case_insensitive(!config.case_sensitive)16 unmodified linesmodified:src/walk.rs+10 added
197 unmodified lines198 199 let stdout = io::stdout();200 let mut stdout = stdout.lock();201 202+ let mut num_results = 0;203+204 for worker_result in rx {205 match worker_result {206 WorkerResult::Entry(value) => {207 match mode {22 unmodified lines230 ReceiverMode::Streaming => {231 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);232 }233 }234+235+ num_results += 1;236 }237 WorkerResult::Error(err) => {238 if show_filesystem_errors {239 print_error!("{}", err);240 }241 }242 }243+244+ if let Some(max_results) = config.max_results {245+ if num_results >= max_results {246+ break;247+ }248+ }249 }250 251 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed252 // anything to the console, yet. In this case, sort the results and print them:198 unmodified linesmodified:tests/testenv/mod.rs+20 added-8 removed
190 unmodified lines191 let mut components = self.temp_dir.path().components();192 PathBuf::from(components.next().expect("root directory").as_os_str())193 }194 195- /// Assert that calling *fd* with the specified arguments produces the expected output.196- pub fn assert_output(&self, args: &[&str], expected: &str) {197- self.assert_output_subdirectory(".", args, expected)198- }199-195 /// Assert that calling *fd* in the specified path under the root working directory,196 /// and with the specified arguments produces the expected output.202- pub fn assert_output_subdirectory<P: AsRef<Path>>(197+ pub fn assert_success_and_get_output<P: AsRef<Path>>(198 &self,199 path: P,200 args: &[&str],206- expected: &str,207- ) {201+ ) -> process::Output {202 // Setup *fd* command.203 let mut cmd = process::Command::new(&self.fd_exe);204 cmd.current_dir(self.temp_dir.path().join(path));205 cmd.args(args);5 unmodified lines211 if !output.status.success() {212 panic!(format_exit_error(args, &output));213 }214 215+ output216+ }217+218+ /// Assert that calling *fd* with the specified arguments produces the expected output.219+ pub fn assert_output(&self, args: &[&str], expected: &str) {220+ self.assert_output_subdirectory(".", args, expected)221+ }222+223+ /// Assert that calling *fd* in the specified path under the root working directory,224+ /// and with the specified arguments produces the expected output.225+ pub fn assert_output_subdirectory<P: AsRef<Path>>(226+ &self,227+ path: P,228+ args: &[&str],229+ expected: &str,230+ ) {231+ let output = self.assert_success_and_get_output(path, args);232+233 // Normalize both expected and actual output.234 let expected = normalize_output(expected, true, self.normalize_line);235 let actual = normalize_output(236 &String::from_utf8_lossy(&output.stdout),38 unmodified linesmodified:tests/tests.rs+25 added
1468 unmodified lines1469 abs_path = &abs_path1470 ),1471 );1472 }1473+1474+#[test]1475+fn test_max_results() {1476+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1477+1478+ // Unrestricted1479+ te.assert_output(1480+ &["--max-results=0", "c.foo"],1481+ "one/two/C.Foo21482+ one/two/c.foo",1483+ );1484+1485+ // Limited to two results1486+ te.assert_output(1487+ &["--max-results=2", "c.foo"],1488+ "one/two/C.Foo21489+ one/two/c.foo",1490+ );1491+1492+ // Limited to one result. We could find either C.Foo2 or c.foo1493+ let output = te.assert_success_and_get_output(".", &["--max-results=1", "c.foo"]);1494+ let stdout = String::from_utf8_lossy(&output.stdout);1495+ let stdout = stdout.trim();1496+ assert!(stdout == "one/two/C.Foo2" || stdout == "one/two/c.foo");1497+}modified:CHANGELOG.md+4 added
1 # Upcoming release2 3 ## Features4 5+- Added `--max-results=<count>` option to limit the number of search results, see #472 and #4766+ This can be useful to speed up searches in cases where you know that there are only N results.7+ Using this option is also (slightly) faster than piping to `head -n <count>` where `fd` can only8+ exit when it finds the search results `<count> + 1`.9 - Support additional ANSI font styles in `LS_COLORS`: faint, slow blink, rapid blink, dimmed, hidden and strikethrough.10 11 ## Bugfixes12 409 unmodified lines