makogrep 0.1.0

mako 的 minigrep 示例 cli
Documentation
use std::error::Error;
use std::{env, fs};

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}
impl Config {
    //! # markdown 注释
    //! > quote
    /// 从命令号参数中提取配置
    /// ```
    /// use std::{env, process};
    /// use makogrep::Config;
    /// let args = env::args();
    /// let config = Config::build(args);
    /// ```
    pub fn build(mut args: impl Iterator<Item=String>) -> Result<Config, &'static str> {
        args.next();

        let query = match args.next() {
            Some(item) => item,
            None => return Err("Didn't get a query string")
        };

        let file_path = args.next().ok_or_else(|| "Didn't get a file_path string")?;


        let ignore_case = env::var("IGNORE_CASE").is_ok();
        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}
// 执行命令行工具
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    println!("params: {}--{}", config.query, config.file_path);

    println!("🚗In file {}", config.file_path);

    let contents = fs::read_to_string(config.file_path)?;
    // .expect("❌Should have been able to read the file.");

    let result = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };
    for line in result {
        println!("{line}")
    };
    Ok(())
}

fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    content.lines().filter(|line| line.contains(query)).collect()
}

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

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

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

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