summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 3111766babee5f9dbad88788c7f8cf8a04c4636c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use std::error::Error;
use std::process;
use std::fs;
use std::io::{self, BufReader, BufRead};

use clap::Parser;

#[derive(Parser)]
#[command(author, version, about, long_about = None)] // Read from `Cargo.toml`
struct Config {
    /// The pattern to look for
    pattern: 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>,

    /// Ignores the case of the search string
    #[arg(short, long)]
    ignore_case: bool,
}

fn main() {
    let mut config = Config::parse();

    if config.files.is_empty() {
        config.files.push(String::from("-"));
    }

    if let Err(e) = run(config) {
        eprintln!("Error: {e}");
        process::exit(1);
    }
}

fn run(config: Config) -> Result<(), Box<dyn Error>> {
    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
        };

        for line in reader.lines().map(|l| l.unwrap()) {
            if !trgrep::contains_pattern(&line, &config.pattern, config.ignore_case) {
                continue;
            }
            println!("{line}");
        }
    }

    Ok(())
}