|
| 1 | +extern crate walkdir; |
| 2 | +extern crate regex; |
| 3 | + |
| 4 | + |
| 5 | +use std::env; |
| 6 | +use std::fs::File; |
| 7 | +use std::io::{self, BufRead}; |
| 8 | +use std::path::Path; |
| 9 | +use regex::Regex; |
| 10 | +use walkdir::WalkDir; |
| 11 | + |
| 12 | +fn search_by_name(directory: &str, file_name: &str) { |
| 13 | + let file_name_regex = Regex::new(file_name).expect("Invalid regex"); |
| 14 | + |
| 15 | + for entry in WalkDir::new(directory) { |
| 16 | + let entry = entry.expect("Error reading directory entry"); |
| 17 | + let file_path = entry.path(); |
| 18 | + |
| 19 | + if let Some(file_name) = file_path.file_name() { |
| 20 | + if file_name_regex.is_match(file_name.to_str().unwrap_or("")) { |
| 21 | + println!("{}", file_path.display()); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +fn search_by_content(directory: &str, content: &str) { |
| 28 | + for entry in WalkDir::new(directory) { |
| 29 | + let entry = entry.expect("Error reading directory entry"); |
| 30 | + let file_path = entry.path(); |
| 31 | + |
| 32 | + if file_path.is_file() { |
| 33 | + if let Ok(file) = File::open(file_path) { |
| 34 | + let reader = io::BufReader::new(file); |
| 35 | + |
| 36 | + for line in reader.lines() { |
| 37 | + if let Ok(line) = line { |
| 38 | + if line.contains(content) { |
| 39 | + println!("{}", file_path.display()); |
| 40 | + break; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +fn main() { |
| 50 | + let args: Vec<String> = env::args().collect(); |
| 51 | + |
| 52 | + if args.len() < 3 { |
| 53 | + println!("Usage: {} <directory> <search_term> [options: -n for name, -c for content]", args[0]); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + let directory = &args[1]; |
| 58 | + let search_term = &args[2]; |
| 59 | + |
| 60 | + if args.len() == 3 { |
| 61 | + // Default search by name |
| 62 | + search_by_name(directory, search_term); |
| 63 | + } else { |
| 64 | + let option = &args[3]; |
| 65 | + match option.as_str() { |
| 66 | + "-n" => search_by_name(directory, search_term), |
| 67 | + "-c" => search_by_content(directory, search_term), |
| 68 | + _ => println!("Invalid option: {}", option), |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments