summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJoursoir <chat@joursoir.net>2023-03-02 23:22:23 +0400
committerJoursoir <chat@joursoir.net>2023-03-02 23:25:24 +0400
commit1890006df3d79a767bfdc1b981c658f7033d8fd2 (patch)
tree4ae8408f7b11c572a36e9fe3da53d56b27d34f94 /src
parent8e40b9ae042b715785004678b1bb3d3a4fca9838 (diff)
downloadtrgrep-1890006df3d79a767bfdc1b981c658f7033d8fd2.tar.gz
trgrep-1890006df3d79a767bfdc1b981c658f7033d8fd2.tar.bz2
trgrep-1890006df3d79a767bfdc1b981c658f7033d8fd2.zip
accept multiple files and stdin
Diffstat (limited to 'src')
-rw-r--r--src/main.rs34
1 files changed, 28 insertions, 6 deletions
diff --git a/src/main.rs b/src/main.rs
index 76b2543..767914d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,7 @@
use std::error::Error;
use std::process;
use std::fs;
+use std::io::{self, BufReader, BufRead};
use clap::Parser;
@@ -9,12 +10,18 @@ use clap::Parser;
struct Config {
/// The pattern to look for
pattern: String,
- /// The path to the file to read
- file: String,
+ /// The path to files to read. A path of "-" stands for standard input.
+ ///
+ /// If no FILE is given, read standard input.
+ files: Vec<String>,
}
fn main() {
- let config = Config::parse();
+ let mut config = Config::parse();
+
+ if config.files.is_empty() {
+ config.files.push(String::from("-"));
+ }
if let Err(e) = run(config) {
eprintln!("Error: {e}");
@@ -23,10 +30,25 @@ fn main() {
}
fn run(config: Config) -> Result<(), Box<dyn Error>> {
- let contents = fs::read_to_string(config.file)?;
+ for file in config.files {
+ // On-Stack Dynamic Dispatch
+ let (mut stdin_read, mut file_read);
+
+ // We need to ascribe the type to get dynamic dispatch.
+ let reader: &mut dyn BufRead = if file == "-" {
+ stdin_read = BufReader::new(io::stdin());
+ &mut stdin_read
+ } else {
+ file_read = BufReader::new(fs::File::open(&file)?);
+ &mut file_read
+ };
+
+ let mut contents = String::new();
+ reader.read_to_string(&mut contents)?;
- for line in trgrep::search(&config.pattern, &contents) {
- println!("{line}");
+ for line in trgrep::search(&config.pattern, &contents) {
+ println!("{line}");
+ }
}
Ok(())