Skip to content
Myr

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

3 files+42 added−31 removed

modified:src/exec/job.rs+2 added-2 removed
24 unmodified lines
2526 // 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 lines
52 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 lines
modified:src/output.rs+14 added-14 removed
1use std::borrow::Cow;2use std::io::{self, StdoutLock, Write};2use std::io::{self, Write};3use std::path::Path;4use std::sync::atomic::{AtomicBool, Ordering};5use std::sync::Arc;56use lscolors::{Indicator, LsColors, Style};78use crate::config::Config;
5 unmodified lines
14 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)15}1617// TODO: this function is performance critical and can probably be optimized19pub fn print_entry(20 stdout: &mut StdoutLock,18pub 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 lines
44 }45}4647// TODO: this function is performance critical and can probably be optimized49fn print_entry_colorized(50 stdout: &mut StdoutLock,48fn 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 lines
92 writeln!(stdout)?;93 }9495 if wants_to_quit.load(Ordering::Relaxed) {96 stdout.flush()?;97 ExitCode::KilledBySigint.exit();98 }99100 Ok(())101}102103// TODO: this function is performance critical and can probably be optimized104fn print_entry_uncolorized_base(105 stdout: &mut StdoutLock,104fn 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 lines
115 write!(stdout, "{}{}", path_string, separator)116}117118#[cfg(not(unix))]119fn print_entry_uncolorized(120 stdout: &mut StdoutLock,119fn 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}126127#[cfg(unix)]128fn print_entry_uncolorized(129 stdout: &mut StdoutLock,128fn 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 lines
modified:src/walk.rs+26 added-15 removed
1use std::borrow::Cow;1use std::ffi::OsStr;2use std::fs::{FileType, Metadata};3use std::io;4use std::path::{Path, PathBuf};5use std::sync::atomic::{AtomicBool, Ordering};7use std::sync::mpsc::{channel, Receiver, Sender};6use std::sync::mpsc::{sync_channel, Receiver, SyncSender as Sender};7use std::sync::{Arc, Mutex};8use std::thread;9use std::time;10use std::{borrow::Cow, io::Write};1112use anyhow::{anyhow, Result};13use ignore::overrides::OverrideBuilder;14use ignore::{self, WalkBuilder};
6 unmodified lines
21use crate::exit_codes::{merge_exitcodes, ExitCode};22use crate::filesystem;23use crate::output;2425pub const WORKER_CHANNEL_DEFAULT_BOUND: usize = 1000;2627pub fn make_worker_channel() -> (Sender<WorkerResult>, Receiver<WorkerResult>) {28 sync_channel(WORKER_CHANNEL_DEFAULT_BOUND)29}3031/// The receiver thread can either be buffering results or directly streaming to the console.32enum ReceiverMode {33 /// Receiver is still buffering in order to sort the results, if the search finishes fast34 /// enough.
23 unmodified lines
58 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();6364 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());6566 for pattern in &config.exclude_patterns {
158 unmodified lines
225 }226 } else {227 let start = time::Instant::now();228223 let mut buffer = vec![];224229 // Start in buffering mode230 let mut mode = ReceiverMode::Buffering;231232 // 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);234235 let stdout = io::stdout();232 let mut stdout = stdout.lock();236 let stdout = stdout.lock();237 let mut stdout = io::BufWriter::new(stdout);238239 let mut num_results = 0;235240 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 }248249 match mode {250 ReceiverMode::Buffering => {245 buffer.push(value);251 buffer.push(path);252253 // 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();261267 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 }270283 num_results += 1;284 if let Some(max_results) = config.max_results {285 if num_results >= max_results {286 break;
6 unmodified lines
293 }294 }295 }296 }285297 // 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