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
60
61
62
63
64
65
mod front_of_house;

use crate::front_of_house::hosting::add_to_waitlist;
use std::{error::Error, fs};

pub fn eat_at_restaurant() {
    // front_of_house::hosting::add_to_waitlist();
    add_to_waitlist();
}

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

impl Config {
    pub fn build(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
        args.next();
        let default_config = Config {
            query: String::from("de"),
            file_path: String::from("Cargo.toml"),
        };
        let query = match args.next() {
            Some(arg) => arg,
            None => return Ok(default_config),
        };
        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Ok(default_config),
        };
        Ok(Config { query, file_path })
    }
}

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

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let content = fs::read_to_string(config.file_path)?;
    dbg!(&content);
    for line in search(config.query, &content) {
        println!("{line}");
    }
    Ok(())
}

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

    #[test]
    fn one_result() {
        let query = "foo".to_string();
        let content = "\
limp fimp
fimp foop
gloop sloop"
            .to_string();
        assert_eq!(vec!["fimp foop"], search(query, &content));
    }
}