Add buffering to stdout when it's not a terminal
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This is based on the work of #736 by @sourlemon207. I've added the suggestion I recommended on that PR.
authored by Thayne McCombs · committed by David Peter · parent fba6db5 · Browse files · 3 files·+42 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+42 added−31 removed
- other:+42 added−31 removed
Provenance
- Commit
feac240- Tree
4294d41- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
fba6db5
3 files changed+42 added−31 removed
modified:src/exec/job.rs+2 added-2 removed
24 unmodified lines25 26 // Obtain the next result from the receiver, else if the channel27 // has closed, exit from the loop28 let value: PathBuf = match lock.recv() {29- Ok(WorkerResult::Entry(val)) => val,29+ Ok(WorkerResult::Entry(path)) => path,30 Ok(WorkerResult::Error(err)) => {31 if show_filesystem_errors {32 print_error(err.to_string());33 }18 unmodified lines52 buffer_output: bool,53 limit: usize,54 ) -> ExitCode {55 let paths = rx.iter().filter_map(|value| match value {56- WorkerResult::Entry(val) => Some(val),56+ WorkerResult::Entry(path) => Some(path),57 WorkerResult::Error(err) => {58 if show_filesystem_errors {59 print_error(err.to_string());60 }17 unmodified linesmodified:src/output.rs+14 added-14 removed
1 use std::borrow::Cow;2-use std::io::{self, StdoutLock, Write};2+use std::io::{self, Write};3 use std::path::Path;4 use std::sync::atomic::{AtomicBool, Ordering};5-use std::sync::Arc;5 6 use lscolors::{Indicator, LsColors, Style};7 8 use crate::config::Config;5 unmodified lines14 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)15 }16 17 // TODO: this function is performance critical and can probably be optimized19-pub fn print_entry(20- stdout: &mut StdoutLock,18+pub fn print_entry<W: Write>(19+ stdout: &mut W,20 entry: &Path,21 config: &Config,23- wants_to_quit: &Arc<AtomicBool>,22+ wants_to_quit: &AtomicBool,23 ) {24 let path = if config.strip_cwd_prefix {25 strip_current_dir(entry)26 } else {17 unmodified lines44 }45 }46 47 // TODO: this function is performance critical and can probably be optimized49-fn print_entry_colorized(50- stdout: &mut StdoutLock,48+fn print_entry_colorized<W: Write>(49+ stdout: &mut W,50 path: &Path,51 config: &Config,52 ls_colors: &LsColors,54- wants_to_quit: &Arc<AtomicBool>,53+ wants_to_quit: &AtomicBool,54 ) -> io::Result<()> {55 // Split the path between the parent and the last component56 let mut offset = 0;57 let path_str = path.to_string_lossy();34 unmodified lines92 writeln!(stdout)?;93 }94 95 if wants_to_quit.load(Ordering::Relaxed) {96+ stdout.flush()?;97 ExitCode::KilledBySigint.exit();98 }99 100 Ok(())101 }102 103 // TODO: this function is performance critical and can probably be optimized104-fn print_entry_uncolorized_base(105- stdout: &mut StdoutLock,104+fn print_entry_uncolorized_base<W: Write>(105+ stdout: &mut W,106 path: &Path,107 config: &Config,108 ) -> io::Result<()> {109 let separator = if config.null_separator { "\0" } else { "\n" };5 unmodified lines115 write!(stdout, "{}{}", path_string, separator)116 }117 118 #[cfg(not(unix))]119-fn print_entry_uncolorized(120- stdout: &mut StdoutLock,119+fn print_entry_uncolorized<W: Write>(120+ stdout: &mut W,121 path: &Path,122 config: &Config,123 ) -> io::Result<()> {124 print_entry_uncolorized_base(stdout, path, config)125 }126 127 #[cfg(unix)]128-fn print_entry_uncolorized(129- stdout: &mut StdoutLock,128+fn print_entry_uncolorized<W: Write>(129+ stdout: &mut W,130 path: &Path,131 config: &Config,132 ) -> io::Result<()> {133 use std::os::unix::ffi::OsStrExt;11 unmodified linesmodified:src/walk.rs+26 added-15 removed
1-use std::borrow::Cow;1 use std::ffi::OsStr;2 use std::fs::{FileType, Metadata};3 use std::io;4 use std::path::{Path, PathBuf};5 use std::sync::atomic::{AtomicBool, Ordering};7-use std::sync::mpsc::{channel, Receiver, Sender};6+use std::sync::mpsc::{sync_channel, Receiver, SyncSender as Sender};7 use std::sync::{Arc, Mutex};8 use std::thread;9 use std::time;10+use std::{borrow::Cow, io::Write};11 12 use anyhow::{anyhow, Result};13 use ignore::overrides::OverrideBuilder;14 use ignore::{self, WalkBuilder};6 unmodified lines21 use crate::exit_codes::{merge_exitcodes, ExitCode};22 use crate::filesystem;23 use crate::output;24 25+pub const WORKER_CHANNEL_DEFAULT_BOUND: usize = 1000;26+27+pub fn make_worker_channel() -> (Sender<WorkerResult>, Receiver<WorkerResult>) {28+ sync_channel(WORKER_CHANNEL_DEFAULT_BOUND)29+}30+31 /// The receiver thread can either be buffering results or directly streaming to the console.32 enum ReceiverMode {33 /// Receiver is still buffering in order to sort the results, if the search finishes fast34 /// enough.23 unmodified lines58 let mut path_iter = path_vec.iter();59 let first_path_buf = path_iter60 .next()61 .expect("Error: Path vector can not be empty");56- let (tx, rx) = channel();62+ let (tx, rx) = make_worker_channel();63 64 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());65 66 for pattern in &config.exclude_patterns {158 unmodified lines225 }226 } else {227 let start = time::Instant::now();228 223- let mut buffer = vec![];224-229 // Start in buffering mode230 let mut mode = ReceiverMode::Buffering;231 232 // Maximum time to wait before we start streaming to the console.233 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);234 235 let stdout = io::stdout();232- let mut stdout = stdout.lock();236+ let stdout = stdout.lock();237+ let mut stdout = io::BufWriter::new(stdout);238 239 let mut num_results = 0;235-240+ let is_interactive = config.interactive_terminal;241+ let mut buffer = Vec::with_capacity(MAX_BUFFER_LENGTH);242 for worker_result in rx {243 match worker_result {238- WorkerResult::Entry(value) => {244+ WorkerResult::Entry(path) => {245 if config.quiet {246 return ExitCode::HasResults(true);247 }248 249 match mode {250 ReceiverMode::Buffering => {245- buffer.push(value);251+ buffer.push(path);252 253 // Have we reached the maximum buffer size or maximum buffering time?254 if buffer.len() > MAX_BUFFER_LENGTH255 || start.elapsed() > max_buffer_time256 {257 // Flush the buffer252- for v in &buffer {258+ for path in &buffer {259 output::print_entry(260 &mut stdout,255- v,261+ path,262 &config,263 &wants_to_quit,264 );265 }266 buffer.clear();261-267+ if is_interactive && stdout.flush().is_err() {268+ // Probably a broken pipe. Exit gracefully.269+ return ExitCode::GeneralError;270+ }271 // Start streaming272 mode = ReceiverMode::Streaming;273 }274 }275 ReceiverMode::Streaming => {267- output::print_entry(&mut stdout, &value, &config, &wants_to_quit);276+ output::print_entry(&mut stdout, &path, &config, &wants_to_quit);277+ if is_interactive && stdout.flush().is_err() {278+ // Probably a broken pipe. Exit gracefully.279+ return ExitCode::GeneralError;280+ }281 }282 }270-283 num_results += 1;284 if let Some(max_results) = config.max_results {285 if num_results >= max_results {286 break;6 unmodified lines293 }294 }295 }296 }285-297 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed298 // anything to the console, yet. In this case, sort the results and print them:299 buffer.sort();300 for value in buffer {233 unmodified lines