Skip to content
Myr

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

authored by sharkdp · committed by David Peter · parent ee673c9 · Browse files · 8 files+80 added−8 removed
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

8 files+80 added−8 removed

modified:doc/fd.1+3 added
78 unmodified lines
79.B \-0, \-\-print080Separate search results by the null character (instead of newlines). Useful for piping results to81.IR xargs .82.TP83.B \-\-max\-results count84Limit the number of search results to 'count' and quit immediately.85.TP86.B \-\-show-errors87Enable the display of filesystem errors for situations such as insufficient88permissions or dead symlinks.89.TP
182 unmodified lines
modified:src/internal/opts.rs+3 added
79 unmodified lines
80 pub show_filesystem_errors: bool,8182 /// The separator used to print file paths.83 pub path_separator: Option<String>,8485 /// The maximum number of search results86 pub max_results: Option<usize>,87}
modified:src/app.rs+11 added
250 unmodified lines
251 .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 lines
464 '--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 lines
modified:src/main.rs+4 added
277 unmodified lines
278 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 };287288 match RegexBuilder::new(&pattern_regex)289 .case_insensitive(!config.case_sensitive)
16 unmodified lines
modified:src/walk.rs+10 added
197 unmodified lines
198199 let stdout = io::stdout();200 let mut stdout = stdout.lock();201202 let mut num_results = 0;203204 for worker_result in rx {205 match worker_result {206 WorkerResult::Entry(value) => {207 match mode {
22 unmodified lines
230 ReceiverMode::Streaming => {231 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);232 }233 }234235 num_results += 1;236 }237 WorkerResult::Error(err) => {238 if show_filesystem_errors {239 print_error!("{}", err);240 }241 }242 }243244 if let Some(max_results) = config.max_results {245 if num_results >= max_results {246 break;247 }248 }249 }250251 // 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 lines
modified:tests/testenv/mod.rs+20 added-8 removed
190 unmodified lines
191 let mut components = self.temp_dir.path().components();192 PathBuf::from(components.next().expect("root directory").as_os_str())193 }194195 /// 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 }199195 /// 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 lines
211 if !output.status.success() {212 panic!(format_exit_error(args, &output));213 }214215 output216 }217218 /// 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 }222223 /// 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);232233 // 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 lines
modified:tests/tests.rs+25 added
1468 unmodified lines
1469 abs_path = &abs_path1470 ),1471 );1472}14731474#[test]1475fn test_max_results() {1476 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);14771478 // Unrestricted1479 te.assert_output(1480 &["--max-results=0", "c.foo"],1481 "one/two/C.Foo21482 one/two/c.foo",1483 );14841485 // Limited to two results1486 te.assert_output(1487 &["--max-results=2", "c.foo"],1488 "one/two/C.Foo21489 one/two/c.foo",1490 );14911492 // 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 release23## Features45- 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.1011## Bugfixes12
409 unmodified lines