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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
use std::error::Error;
use std::fs;
use std::env;

use colored::*;

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

#[derive(Debug)]
pub struct ResultType<'a> {
    pub pos: usize,
    pub text: &'a str,
}

impl Config {
    pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("Count of args is less than expected");
        }

        args.next();

        let query = args.next().unwrap_or_else(|| {
            panic!("First arg did't passed");
        });

        let filename = args.next().unwrap_or_else(|| {
            panic!("Second arg did't passed")
        });

        println!("{}", query);

        Ok(Config { query, filename })
    }
}

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

  for line in search(&config.query, &contents) {
    let result_line = format!("Line {}: {}", line.pos, line.text);
    // highlights with colored lib
    println!("{}", result_line.cyan());
  }

  Ok(())
}

/// Find text line by query
///
/// # Examples
///
/// ```
/// let text = "lalal
/// hello world
/// hi
/// hello!
/// "
///
/// let answer = my_crate::search("hello", "text");
///
/// println!("{}", answer);
/// // hello world
/// // hello!
/// ```
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<ResultType<'a>> {
    contents
        .lines()
        .filter(|line| line.contains(query))
        .enumerate()
        .map(|(idx, text)| ResultType { pos: idx, text })
        .collect()
}

#[derive(Debug)]
pub enum Foo {
    A(i32),
    B(i32),
}

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

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

let mut v: Vec<ResultType> = Vec::new();
v.push(ResultType { pos: 1, text: "safe, fast, productive" });


        assert_matches!(
            search(query, contents),
            v,
        );

    }
}