Skip to content
Myr

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

1 file+87 added−10 removed

modified:src/main.rs+87 added-10 removed
13 unmodified lines
14use std::io::Write;15use std::ops::Deref;16#[cfg(target_family = "unix")]17use std::os::unix::fs::PermissionsExt;18use std::path::{Path, Component};18use std::path::{Path, PathBuf, Component};19use std::process;20use std::sync::Arc;21use std::sync::mpsc::channel;22use std::time;2324use clap::{App, AppSettings, Arg};25use atty::Stream;26use regex::{Regex, RegexBuilder};
37 unmodified lines
64 /// 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>,6768 /// The number of threads to use.69 threads: Option<usize>,7071 /// 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>,7576 /// Display results as relative or absolute path.77 path_display: PathDisplay,7879 /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines
7 unmodified lines
87/// Parent directory88static PARENT_DIR : &'static str = "..";8990/// Print a search result to the console.81fn print_entry(base: &Path, entry: &Path, config: &FdOptions) {91fn print_entry(base: &Path, entry: &PathBuf, config: &FdOptions) {92 let path_full = base.join(entry);9394 let path_str = entry.to_string_lossy();95
56 unmodified lines
152 .unwrap_or(&default_style)153 }154 };155146 write!(handle, "{}", style.paint(comp_str));156 write!(handle, "{}", style.paint(comp_str)).ok();157158 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 }163153 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 output175176 let prefix = if config.path_display == PathDisplay::Absolute { ROOT_DIR } else { "" };177 let separator = if config.null_separator { "\0" } else { "\n" };178164 let r = writeln!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator);179 let r = write!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator);180181 if r.is_err() {182 // Probably a broken pipe. Exit gracefully.183 process::exit(0);
2 unmodified lines
186}187188/// Recursively scan the given search path and search for files / pathnames matching the pattern.189fn scan(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {190 let (tx, rx) = channel();191192 let walker = WalkBuilder::new(root)193 .hidden(config.ignore_hidden)194 .ignore(config.read_ignore)195 .git_ignore(config.read_ignore)
1 unmodified line
197 .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();203204 walker.run(|| {205 let base = base.to_owned();206 let config = config.clone();207 let pattern = pattern.clone();208 let tx_thread = tx.clone();209210 Box::new(move |entry_o| {211 let entry = match entry_o {212 Ok(e) => e,
14 unmodified lines
227 .map(|f| f.to_string_lossy())228 };229230 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 }235236 ignore::WalkState::Continue237 })238 });239240 // 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);243244 let start = time::Instant::now();245246 let mut buffer = vec!();247248 // Are we still buffering (or streaming to the console)?249 let mut buffering = true;250251 // 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));254255 for value in rx {256 if buffering {257 buffer.push(value);258259 // 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();266267 // Start streaming268 buffering = false;269 }270 } else {271 print_entry(base, &value, &config);272 }273 }274275 // 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}282283/// Print error message to stderr and exit with status `1`.284fn error(message: &str) -> ! {
45 unmodified lines
330 .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 lines
405 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::Relative
17 unmodified lines