minigre_base 0.1.0

Simple text file search tool
Documentation
use std::{env, error::Error, fs};

pub struct Config {
    file_path: String,
    query: String,
    ignore_case: bool,
}

impl Config {
    pub fn new(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
        // if args.len() < 3 {
        //     return Err("Not enought arguments");
        // }
        // Ok(Config {
        //     file_path: args[1].clone(),
        //     query: args[2].clone(),
        //     ignore_case: env::var("IGNORE_CASE").unwrap() == "true",
        // })
        //
        args.next();

        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err("Not enought info"),
        };

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Not enought info"),
        };

        let ignore_case = env::var("IGNORE_CASE").unwrap() == "true";

        Ok(Config {
            file_path,
            query,
            ignore_case,
        })

        // let path = args.next().unwrap_or_else(f);

        // Ok(Config { file_path: (), query: (), ignore_case: () })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let res: Vec<&str> = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in res {
        println!("{line}")
    }

    Ok(())
}

/// ##Finds all occurences of query in text file and return matching lines
///
/// # Example
/// ```
///  search('hello', 'hello world')
///
/// ````
pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    // let mut v: Vec<&str> = Vec::new();

    // for line in content.lines() {
    //     println!("Searching in line - {} for query - {}", line, query);
    //     if line.contains(query) {
    //         v.push(line);
    //     }
    // }
    content
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}

pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    // let mut v: Vec<&str> = Vec::new();
    //
    // for line in content.lines() {
    //     println!("Searching in line - {} for query - {}", line, query);
    //     if line.to_lowercase().contains(&query.to_lowercase()) {
    //         v.push(line);
    //     }
    // }
    // v

    content
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "dUct";
        let contents = "\
Rust:
safe, fast, prodUctive
Pick there.";
        assert_eq!(vec!["safe, fast, prodUctive"], search(query, contents))
    }

    #[test]
    fn case_insensitive() {
        let query = "pick";
        let contents = "\
Rust:
safe, fast, productive
Pick there.";
        assert_eq!(
            vec!["Pick there."],
            search_case_insensitive(query, contents)
        )
    }
}