1use clap::Parser;
2use colored::Colorize;
3use std::fs::File;
4use std::io::{BufRead, BufReader};
5
6#[derive(Parser)]
7pub struct Args {
8 pub pattern: String,
10 pub path: std::path::PathBuf,
12 #[clap(short, long, default_value = "1")]
14 pub depth: usize,
15 #[clap(short, long, default_value = "false")]
17 pub stats: bool,
18}
19
20pub fn find_matches(args: &Args, reader: BufReader<File>, buf: &mut String) {
21 for line_result in reader.lines() {
22 match line_result {
23 Ok(line) => {
24 if line.contains(args.pattern.as_str()) {
25 let line = line.replace(
26 args.pattern.as_str(),
27 args.pattern.bright_red().bold().to_string().as_str(),
28 );
29 buf.push_str(&line);
30 buf.push_str("\n");
31 }
32 }
33 Err(_) => return,
38 }
39 }
40}
41
42pub fn process_file(
43 args: &Args,
44 path: &std::path::Path,
45 buf: &mut String,
46) -> Result<(), Box<dyn std::error::Error>> {
47 let file = File::open(path);
48 let file = match file {
49 Ok(file) => file,
50 Err(e) => {
51 return Err(e.into());
52 }
53 };
54 let reader = BufReader::new(file);
55
56 let mut current_file_buf = String::new();
57 find_matches(args, reader, &mut current_file_buf);
58 if current_file_buf.len() > 0 {
59 buf.push_str(&format!("\n\n{}:\n", path.display().to_string().green()));
60 buf.push_str(¤t_file_buf);
61 }
62 Ok(())
63}