r4_grrs 0.1.1

A tool to search files
Documentation
#![allow(unused)]

use anyhow::{Context, Result};
use clap::Parser;
use r4_grrs::find_matches;

// Instead of text, it pays off to think of CLI arguments as a custom data type.
/// Search for a pattern in a file and display the lines that contain it.
#[derive(Parser)]
struct CliArgs {
    /// The pattern to look for
    pattern: String,
    /// The path to the file to read
    path: std::path::PathBuf, // like a String but for file system paths (cross-platform)
}

fn main() -> Result<()> {
    // let pattern = std::env::args().nth(1).expect("no pattern given");
    // let path = std::env::args().nth(2).expect("no path given");
    // let args = CliArgs {
    //     pattern,
    //     path: std::path::PathBuf::from(path),
    // };

    let args = CliArgs::parse(); // automatically generated by the derive macro
    let read_content = std::fs::read_to_string(&args.path)
        .with_context(|| format!("could not read file `{}`", &args.path.display()))?;

    find_matches(&read_content, &args.pattern, &mut std::io::stdout());

    Ok(())
}

#[cfg(test)]
mod tests{
    use r4_grrs::find_matches;

    #[test]
    fn find_a_match() {
        let mut result = Vec::new();
        find_matches("lorem ipsum\ndolor sit amet", "lorem", &mut result);
        assert_eq!(result, b"lorem ipsum\n");
    }
}