api_minigrep 0.1.1

Api for MiniGrep.
Documentation
//! # MiniGrep api module

use itertools::Itertools;
use std::{
    fs::File,
    io::{BufRead, BufReader},
};

#[derive(Debug)]
/// # Struct for use api
pub struct MiniGrep {
    path: String,
    data: String,
}

impl MiniGrep {
    /// Create new object with a patch on a file for processing.
    ///
    /// # Example
    ///
    /// ```
    /// use api_minigrep::MiniGrep;
    ///
    /// let obj = MiniGrep::new("/path/to/file.txt");
    /// ```
    pub fn new(path: &str) -> Self {
        Self {
            path: path.to_string(),
            data: String::new(),
        }
    }
}

impl MiniGrep {
    /// Output of processed information from a file.
    pub fn print(&self) {
        println!("{}", self.data);
    }

    /// The function that processes the file, then saves the result and returns the processing result.
    ///
    /// ## Args
    /// * search - Argument to search in a file.
    ///
    /// # Example
    /// ``` ignore
    /// use api_minigrep::MiniGrep;
    /// use std::process;
    ///
    /// let mut obj = MiniGrep::new("/path/to/file.txt");
    ///
    /// if let Err(e) = obj.parse(None) { // and obj.parse(Some("data"))
    ///     eprintln!("Parse error: {e}");
    ///     process::exit(1);
    /// }
    /// obj.print();
    /// ```
    pub fn parse(&mut self, search: Option<&str>) -> anyhow::Result<()> {
        let buff = BufReader::new(File::open(&self.path)?);

        if let Some(arg) = search {
            self.data = buff.lines().filter_ok(|str| str.contains(arg)).try_fold(
                String::new(),
                |mut acc, line| -> anyhow::Result<String> {
                    acc.push_str(&line?);
                    acc.push('\n');

                    Ok(acc)
                },
            )?;
            self.data.pop();
        } else {
            self.data = buff.lines().try_fold(
                String::new(),
                |mut acc, line| -> anyhow::Result<String> {
                    acc.push_str(&line?);
                    acc.push('\n');

                    Ok(acc)
                },
            )?;
        }
        Ok(())
    }
}

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

    #[test]
    fn test() -> anyhow::Result<()> {
        let mut obj = MiniGrep::new(".test.txt");
        assert_eq!(".test.txt", obj.path);

        obj.parse(None)?;
        assert_eq!("Yes\nNo\n", obj.data);

        obj.parse(Some("Yes"))?;
        assert_eq!("Yes", obj.data);

        Ok(())
    }
}