Implement short-time buffering for sorted output
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by sharkdp · committed by David Peter · parent e06189e · Browse files · 1 file·+87 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+87 added−10 removed
- other:+87 added−10 removed
Provenance
- Commit
550e3b3- Tree
5ad9dac- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
e06189e
1 file changed+87 added−10 removed
modified:src/main.rs+87 added-10 removed
13 unmodified lines14 use std::io::Write;15 use std::ops::Deref;16 #[cfg(target_family = "unix")]17 use std::os::unix::fs::PermissionsExt;18-use std::path::{Path, Component};18+use std::path::{Path, PathBuf, Component};19 use std::process;20 use std::sync::Arc;21+use std::sync::mpsc::channel;22+use std::time;23 24 use clap::{App, AppSettings, Arg};25 use atty::Stream;26 use regex::{Regex, RegexBuilder};37 unmodified lines64 /// A depth of `1` includes all files under the current directory, a depth of `2` also includes65 /// all files under subdirectories of the current directory, etc.66 max_depth: Option<usize>,67 68+ /// The number of threads to use.69+ threads: Option<usize>,70+71+ /// Time to buffer results internally before streaming to the console. This is useful to72+ /// provide a sorted output, in case the total execution time is shorter than73+ /// `max_buffer_time`.74+ max_buffer_time: Option<time::Duration>,75+76 /// Display results as relative or absolute path.77 path_display: PathDisplay,78 79 /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines7 unmodified lines87 /// Parent directory88 static PARENT_DIR : &'static str = "..";89 90 /// Print a search result to the console.81-fn print_entry(base: &Path, entry: &Path, config: &FdOptions) {91+fn print_entry(base: &Path, entry: &PathBuf, config: &FdOptions) {92 let path_full = base.join(entry);93 94 let path_str = entry.to_string_lossy();95 56 unmodified lines152 .unwrap_or(&default_style)153 }154 };155 146- write!(handle, "{}", style.paint(comp_str));156+ write!(handle, "{}", style.paint(comp_str)).ok();157 158 if component_path.is_dir() && component_path != path_full {159 let sep = std::path::MAIN_SEPARATOR.to_string();150- write!(handle, "{}", style.paint(sep));160+ write!(handle, "{}", style.paint(sep)).ok();161 }162 }163+153- if config.null_separator {154- writeln!(handle, "{}", '\0');164+ let r = if config.null_separator {165+ write!(handle, "{}", '\0')166 } else {156- writeln!(handle);167+ writeln!(handle, "")168+ };169+ if r.is_err() {170+ // Probably a broken pipe. Exit gracefully.171+ process::exit(0);172 }173 } else {174 // Uncolorized output175 176 let prefix = if config.path_display == PathDisplay::Absolute { ROOT_DIR } else { "" };177 let separator = if config.null_separator { "\0" } else { "\n" };178 164- let r = writeln!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator);179+ let r = write!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator);180 181 if r.is_err() {182 // Probably a broken pipe. Exit gracefully.183 process::exit(0);2 unmodified lines186 }187 188 /// Recursively scan the given search path and search for files / pathnames matching the pattern.189 fn scan(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {190+ let (tx, rx) = channel();191+192 let walker = WalkBuilder::new(root)193 .hidden(config.ignore_hidden)194 .ignore(config.read_ignore)195 .git_ignore(config.read_ignore)1 unmodified line197 .git_global(config.read_ignore)198 .git_exclude(config.read_ignore)199 .follow_links(config.follow_links)200 .max_depth(config.max_depth)201+ .threads(config.threads.unwrap_or(0))202 .build_parallel();203 204 walker.run(|| {205 let base = base.to_owned();206 let config = config.clone();207 let pattern = pattern.clone();208+ let tx_thread = tx.clone();209 210 Box::new(move |entry_o| {211 let entry = match entry_o {212 Ok(e) => e,14 unmodified lines227 .map(|f| f.to_string_lossy())228 };229 230 if let Some(search_str) = search_str_o {231+ // TODO: take care of the unwrap call232 pattern.find(&*search_str)213- .map(|_| print_entry(&base, path_rel, &config));233+ .map(|_| tx_thread.send(path_rel_buf.to_owned()).unwrap());234 }235 236 ignore::WalkState::Continue237 })238 });239+240+ // Drop the initial sender. If we don't do this, the receiver will block even241+ // if all threads have finished, since there is still one sender around.242+ drop(tx);243+244+ let start = time::Instant::now();245+246+ let mut buffer = vec!();247+248+ // Are we still buffering (or streaming to the console)?249+ let mut buffering = true;250+251+ // Maximum time to wait before we start streaming to the console.252+ let max_buffer_time = config.max_buffer_time253+ .unwrap_or_else(|| time::Duration::from_millis(100));254+255+ for value in rx {256+ if buffering {257+ buffer.push(value);258+259+ // Have we reached the maximum time?260+ if time::Instant::now() - start > max_buffer_time {261+ // Flush the buffer262+ for v in &buffer {263+ print_entry(base, v, &config);264+ }265+ buffer.clear();266+267+ // Start streaming268+ buffering = false;269+ }270+ } else {271+ print_entry(base, &value, &config);272+ }273+ }274+275+ // If we have finished fast enough (faster than max_buffer_time), we haven't streamed276+ // anything to the console, yet. In this case, sort the output and print it:277+ buffer.sort();278+ for value in buffer {279+ print_entry(base, &value, &config);280+ }281 }282 283 /// Print error message to stderr and exit with status `1`.284 fn error(message: &str) -> ! {45 unmodified lines330 .long("max-depth")331 .short("d")332 .takes_value(true)333 .help("Set maximum search depth (default: none)"))334+ .arg(Arg::with_name("threads")335+ .long("threads")336+ .short("j")337+ .takes_value(true)338+ .help("the number of threads to use"))339+ .arg(Arg::with_name("max-buffer-time")340+ .long("max-buffer-time")341+ .takes_value(true)342+ .help("the time to buffer in milliseconds before streaming to the console")343+ .hidden(true))344 .arg(Arg::with_name("pattern")345 .help("the search pattern, a regular expression (optional)"))346 .arg(Arg::with_name("path")347 .help("the root directory for the filesystem search (optional)"))57 unmodified lines405 read_ignore: !matches.is_present("no-ignore"),406 follow_links: matches.is_present("follow"),407 null_separator: matches.is_present("null_separator"),408 max_depth: matches.value_of("depth")337- .and_then(|ds| usize::from_str_radix(ds, 10).ok()),409+ .and_then(|n| usize::from_str_radix(n, 10).ok()),410+ threads: matches.value_of("threads")411+ .and_then(|n| usize::from_str_radix(n, 10).ok()),412+ max_buffer_time: matches.value_of("max-buffer-time")413+ .and_then(|n| u64::from_str_radix(n, 10).ok())414+ .map(time::Duration::from_millis),415 path_display: if matches.is_present("absolute-path") || root_dir_is_absolute {416 PathDisplay::Absolute417 } else {418 PathDisplay::Relative17 unmodified lines