cli_util 0.2.35

Command-line utilitiy for unix based systems
Documentation
//! # Search file(s) for specific text.
//!
//! `Syntax`
//!
//!      grep options "Search String" [filename]
//!
//! `Options`
//!
//! `-c`    Suppress normal output; instead print a count of matching lines for each input file.
//!       With the -v, --invert-match option (see below), count non-matching lines.
//!
//! `-n`    Prefix each line of output with the line number within its input file.
//!
//! `-v`    Selected lines are those not matching any of the specified patterns. Invert matching.

use crate::parse_command_line_args;
use glob::glob;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};

#[cfg(not(docsrs))]
pub fn grep(_args: &str, handle: &mut Box<dyn Write>) -> Result<(), Box<dyn std::error::Error>> {
    let mut keyword = String::new();
    let mut pattern = String::new();
    let mut print_line_number = false;
    let mut count_matches = false;
    let mut invert = false;

    let args = parse_command_line_args(_args);
    for arg in args {
        let mut arg_chars = arg.chars();
        if arg_chars.next() == Some('-') {
            loop {
                match arg_chars.next() {
                    None | Some(' ') => break,
                    Some('n') => print_line_number = true,
                    Some('c') => count_matches = true,
                    Some('v') => invert = true,
                    Some(_) => {
                        eprintln!("Invalid argument {}", arg);
                        return Ok(());
                    }
                }
            }
        } else if keyword.is_empty() {
            keyword = arg.to_string();
        } else {
            pattern = arg;
        }
    }
    for entry in glob(&pattern)? {
        match entry {
            Ok(path) => {
                // Open file and read
                let file = File::open(&path)?;
                let reader = BufReader::new(file);

                //let mut count_lines =0;
                let mut count_match = 0;
                if count_matches {
                    write!(handle, "{}:", path.display())?;
                }
                // Reading the file line by line and searching for the keyword
                for (count_lines, line_result) in reader.lines().enumerate() {

                    match line_result {
                        Ok(line) => {
                            let found = line.contains(&keyword);
                            if (invert && !found) || (!invert && found) {
                                if count_matches {
                                    count_match += 1;
                                } else if print_line_number {
                                    writeln!(handle, "{}:{}: {}", path.display(), count_lines + 1, line)?;
                                } else {
                                    writeln!(handle, "{}:{}", path.display(), line)?;
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!("grep: {}: {}", path.display(), e.to_string());
                            break;
                        }
                    }
                }
                if count_matches {
                    writeln!(handle, "{}", count_match)?;
                }
            }
            Err(e) => eprintln!("Dosya okuma hatası: {:?}", e),
        }
    }
    Ok(())
}
#[cfg(docsrs)]
pub fn grep(_args: &str, handle: &mut Box<dyn Write>) -> Result<(), Box<dyn std::error::Error>> {
    let mut keyword = String::new();
    let mut pattern = String::new();
    let mut print_line_number = false;
    let mut count_matches = false;
    let mut invert = false;

    let args = parse_command_line_args(_args);
    for arg in args {
        let mut arg_chars = arg.chars();
        if arg_chars.next() == Some('-') {
            loop {
                match arg_chars.next() {
                    None | Some(' ') => break,
                    Some('n') => print_line_number = true,
                    Some('c') => count_matches = true,
                    Some('v') => invert = true,
                    Some(_) => {
                        eprintln!("Invalid argument {}", arg);
                        return Ok(());
                    }
                }
            }
        } else if keyword.is_empty() {
            keyword = arg.to_string();
        } else {
            pattern = arg;
        }
    }
    for entry in glob(&pattern)? {
        match entry {
            Ok(path) => {
                // Open file and read
                //line intentionally marked comment
                //let file = File::open(&path)?;
                let reader = BufReader::new(file);

                //let mut count_lines =0;
                let mut count_match = 0;
                if count_matches {
                    write!(handle, "{}:", path.display())?;
                }
                // Reading the file line by line and searching for the keyword
                for (count_lines, line_result) in reader.lines().enumerate() {

                    match line_result {
                        Ok(line) => {
                            let found = line.contains(&keyword);
                            if (invert && !found) || (!invert && found) {
                                if count_matches {
                                    count_match += 1;
                                } else if print_line_number {
                                    writeln!(handle, "{}:{}: {}", path.display(), count_lines + 1, line)?;
                                } else {
                                    writeln!(handle, "{}:{}", path.display(), line)?;
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!("grep: {}: {}", path.display(), e.to_string());
                            break;
                        }
                    }
                }
                if count_matches {
                    writeln!(handle, "{}", count_match)?;
                }
            }
            Err(e) => eprintln!("Dosya okuma hatası: {:?}", e),
        }
    }
    Ok(())
}