Skip to content

Commit

Permalink
Fix #100: allow buffered input
Browse files Browse the repository at this point in the history
  • Loading branch information
vtronko committed Mar 14, 2023
1 parent ac76b2d commit 358e8b7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ pub(crate) struct Options {
/// Recursively replace files
pub recursive: bool,

#[structopt(short = "b", long = "buffered-mode")]
/// Buffered output. Doesn't support multiline matching
pub buffered: bool,

#[structopt(short = "n")]
/// Limit the number of replacements
pub replacements: Option<usize>,
Expand Down
31 changes: 31 additions & 0 deletions src/input.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use crate::{Replacer, Result};
use std::io::{BufRead, Write};
use std::{fs::File, io::prelude::*, path::PathBuf};

#[derive(Debug)]
pub(crate) enum Source {
Stdin,
StdinBuffered,
Files(Vec<PathBuf>),
}

Expand Down Expand Up @@ -54,6 +56,35 @@ impl App {

Ok(())
}
(Source::StdinBuffered, _) => {
let stdin = std::io::stdin();
let stdout = std::io::stdout();
let mut handle = stdout.lock();

let mut buffer = String::new();

loop {
let bytes_read = stdin
.lock()
.read_line(&mut buffer)
.expect("Error reading from standard input");
if bytes_read == 0 {
break;
}
let output = if is_tty {
self.replacer.replace_preview(buffer.as_bytes())
} else {
self.replacer.replace(buffer.as_bytes())
};
handle
.write_all(output.as_ref())
.expect("Error writing to standard output");
handle.flush().expect("Error flushing output");
buffer.clear();
}

Ok(())
}
(Source::Files(paths), false) => {
use rayon::prelude::*;

Expand Down
2 changes: 2 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ fn main() -> Result<()> {
Source::recursive()?
} else if options.files.len() > 0 {
Source::Files(options.files)
} else if options.buffered {
Source::StdinBuffered
} else {
Source::Stdin
};
Expand Down

0 comments on commit 358e8b7

Please sign in to comment.