Остання активність 1 month ago

Subcomando grep con busqueda recursiva y regex (capitulo 07)

grep.rs Неформатований
1use anyhow::Result;
2use colored::*;
3use regex::Regex;
4use walkdir::WalkDir;
5
6pub fn ejecutar(patron: &str, ignorar_mayusculas: bool, archivo: &str) -> Result<()> {
7 let re = if ignorar_mayusculas {
8 Regex::new(&format!("(?i){}", patron))?
9 } else {
10 Regex::new(patron)?
11 };
12
13 let path = std::path::Path::new(archivo);
14
15 if path.is_dir() {
16 for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
17 if entry.file_type().is_file() {
18 buscar_en_archivo(&entry.path().to_string_lossy(), &re)?;
19 }
20 }
21 } else {
22 buscar_en_archivo(archivo, &re)?;
23 }
24
25 Ok(())
26}
27
28fn buscar_en_archivo(ruta: &str, re: &Regex) -> Result<()> {
29 let contenido = match std::fs::read_to_string(ruta) {
30 Ok(c) => c,
31 Err(_) => return Ok(()),
32 };
33
34 for (num, linea) in contenido.lines().enumerate() {
35 if re.is_match(linea) {
36 println!("{}:{}: {}", ruta.cyan().bold(), (num + 1).to_string().yellow(), linea);
37 }
38 }
39
40 Ok(())
41}