LINE1 10 20 30 40 50 60 70 80 901use std::fs::{self, File};2use std::io::{self, BufRead, BufReader, IsTerminal, Write};3use std::path::{Path, PathBuf};4use std::process::ExitCode;56use clap::{Parser, ValueEnum};7use regex::{Regex, RegexBuilder};89#[derive(Debug, Clone, Copy, ValueEnum)]10enum ColorChoice {11 Auto,12 Always,13 Never,14}1516#[derive(Debug, Parser)]17#[command(18 name = "grust",19 version,20 about = "Search files with a regular expression"21)]22struct Cli {23 24 #[arg(value_name = "PATTERN")]25 pattern: String,2627 28 #[arg(value_name = "PATH")]29 paths: Vec<PathBuf>,3031 32 #[arg(short = 'i', long)]33 ignore_case: bool,3435 36 #[arg(short = 'n', long)]37 line_number: bool,3839 40 #[arg(short = 'v', long)]41 invert_match: bool,4243 44 #[arg(short = 'r', long = "recursive", alias = "R")]45 recursive: bool,4647 48 #[arg(short = 'c', long)]49 count: bool,5051 52 #[arg(short = 'l', long = "files-with-matches")]53 files_with_matches: bool,5455 56 #[arg(short = 'o', long = "only-matching")]57 only_matching: bool,5859 60 #[arg(short = 'H', long = "with-filename", conflicts_with = "no_filename")]61 with_filename: bool,6263 64 #[arg(short = 'h', long = "no-filename", conflicts_with = "with_filename")]65 no_filename: bool,6667 68 #[arg(long, value_enum, default_value_t = ColorChoice::Auto)]69 color: ColorChoice,70}7172#[derive(Debug)]73struct Source {74 path: PathBuf,75 stdin: bool,76}7778fn main() -> ExitCode {79 let cli = Cli::parse();80 if cli.only_matching && cli.invert_match {81 eprintln!("grust: --only-matching cannot be used with --invert-match");82 return ExitCode::from(2);83 }8485 let regex = match RegexBuilder::new(&cli.pattern)86 .case_insensitive(cli.ignore_case)87 .build()88 {89 Ok(regex) => regex,90 Err(error) => {91 eprintln!("grust: invalid regular expression: {error}");92 return ExitCode::from(2);93 }94 };9596 let mut stdout = io::BufWriter::new(io::stdout().lock());97 let mut stderr = io::BufWriter::new(io::stderr().lock());98 let stdin = io::stdin();99 let status = run(&cli, ®ex, stdin.lock(), &mut stdout, &mut stderr);100 if let Err(error) = stdout.flush() {101 let _ = writeln!(stderr, "grust: failed to write output: {error}");102 return ExitCode::from(2);103 }104 ExitCode::from(status)105}106107fn run<R: BufRead, W: Write, E: Write>(108 cli: &Cli,109 regex: &Regex,110 stdin: R,111 stdout: &mut W,112 stderr: &mut E,113) -> u8 {114 let requested = if cli.paths.is_empty() {115 vec![PathBuf::from("-")]116 } else {117 cli.paths.clone()118 };119 let mut sources = Vec::new();120 let mut had_directory = false;121 let mut had_error = false;122123 for path in requested {124 if path == Path::new("-") {125 sources.push(Source { path, stdin: true });126 continue;127 }128 match fs::metadata(&path) {129 Ok(metadata) if metadata.is_dir() => {130 had_directory = true;131 if cli.recursive {132 if let Err(error) = collect_files(&path, &mut sources) {133 report_error(stderr, &path, &error);134 had_error = true;135 }136 } else {137 report_error(138 stderr,139 &path,140 &io::Error::other("is a directory (use -r to search recursively)"),141 );142 had_error = true;143 }144 }145 Ok(_) => sources.push(Source { path, stdin: false }),146 Err(error) => {147 report_error(stderr, &path, &error);148 had_error = true;149 }150 }151 }152153 let prefix = cli.with_filename || (!cli.no_filename && (sources.len() > 1 || had_directory));154 let color = match cli.color {155 ColorChoice::Always => true,156 ColorChoice::Never => false,157 ColorChoice::Auto => io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(),158 };159 let mut any_match = false;160 let mut stdin = Some(stdin);161162 for source in sources {163 let source_name = if source.stdin {164 "(standard input)".to_owned()165 } else {166 source.path.to_string_lossy().into_owned()167 };168 let result = if source.stdin {169 if let Some(input) = stdin.take() {170 search_reader(input, &source_name, cli, regex, prefix, color, stdout)171 } else {172 report_error(173 stderr,174 &source.path,175 &io::Error::other("standard input was requested more than once"),176 );177 had_error = true;178 continue;179 }180 } else {181 match File::open(&source.path) {182 Ok(file) => search_reader(183 BufReader::new(file),184 &source_name,185 cli,186 regex,187 prefix,188 color,189 stdout,190 ),191 Err(error) => {192 report_error(stderr, &source.path, &error);193 had_error = true;194 continue;195 }196 }197 };198 match result {199 Ok(matched) => any_match |= matched,200 Err(error) => {201 let _ = writeln!(stderr, "grust: {source_name}: {error}");202 had_error = true;203 }204 }205 }206207 if had_error {208 2209 } else if any_match {210 0211 } else {212 1213 }214}215216fn collect_files(directory: &Path, sources: &mut Vec<Source>) -> io::Result<()> {217 let mut entries = fs::read_dir(directory)?.collect::<Result<Vec<_>, _>>()?;218 entries.sort_by_key(std::fs::DirEntry::file_name);219 for entry in entries {220 let path = entry.path();221 let file_type = entry.file_type()?;222 if file_type.is_dir() {223 collect_files(&path, sources)?;224 } else if file_type.is_file() {225 sources.push(Source { path, stdin: false });226 }227 }228 Ok(())229}230231fn search_reader<R: BufRead, W: Write>(232 mut reader: R,233 name: &str,234 cli: &Cli,235 regex: &Regex,236 prefix: bool,237 color: bool,238 output: &mut W,239) -> io::Result<bool> {240 let mut line = String::new();241 let mut line_number = 0_u64;242 let mut match_count = 0_u64;243 let mut found = false;244245 loop {246 line.clear();247 if reader.read_line(&mut line)? == 0 {248 break;249 }250 line_number += 1;251 if line.ends_with('\n') {252 line.pop();253 if line.ends_with('\r') {254 line.pop();255 }256 }257 let regex_matches = regex.is_match(&line);258 let selected = regex_matches != cli.invert_match;259 if !selected {260 continue;261 }262263 found = true;264 match_count += 1;265 if cli.count || cli.files_with_matches {266 continue;267 }268 if cli.only_matching {269 for found_match in regex.find_iter(&line) {270 write_prefix(output, name, prefix, cli.line_number, line_number, true)?;271 write_colored(output, &line[found_match.start()..found_match.end()], color)?;272 writeln!(output)?;273 }274 } else {275 write_prefix(output, name, prefix, cli.line_number, line_number, false)?;276 if selected && regex_matches {277 write_highlighted(output, &line, regex, color)?;278 } else {279 write!(output, "{line}")?;280 }281 writeln!(output)?;282 }283 }284285 if cli.files_with_matches && found {286 writeln!(output, "{name}")?;287 } else if cli.count {288 write_prefix(output, name, prefix, false, 0, false)?;289 writeln!(output, "{match_count}")?;290 }291 Ok(found)292}293294fn write_prefix<W: Write>(295 output: &mut W,296 name: &str,297 prefix: bool,298 line_number_enabled: bool,299 line_number: u64,300 only_match: bool,301) -> io::Result<()> {302 if prefix {303 write!(output, "{name}:")?;304 }305 if line_number_enabled {306 write!(output, "{line_number}:")?;307 } else if prefix && only_match {308 309 }310 Ok(())311}312313fn write_highlighted<W: Write>(314 output: &mut W,315 line: &str,316 regex: &Regex,317 color: bool,318) -> io::Result<()> {319 let mut end = 0;320 for found_match in regex.find_iter(line) {321 write!(output, "{}", &line[end..found_match.start()])?;322 write_colored(output, found_match.as_str(), color)?;323 end = found_match.end();324 }325 write!(output, "{}", &line[end..])326}327328fn write_colored<W: Write>(output: &mut W, text: &str, color: bool) -> io::Result<()> {329 if color {330 write!(output, "\x1b[1;31m{text}\x1b[0m")331 } else {332 write!(output, "{text}")333 }334}335336fn report_error<W: Write>(stderr: &mut W, path: &Path, error: &io::Error) {337 let _ = writeln!(stderr, "grust: {}: {error}", path.display());338}339340#[cfg(test)]341mod tests {342 use super::*;343 use clap::Parser;344345 fn options(args: &[&str]) -> Cli {346 Cli::try_parse_from(std::iter::once("grust").chain(args.iter().copied())).unwrap()347 }348349 fn search(input: &str, args: &[&str]) -> (u8, String, String) {350 let cli = options(args);351 let regex = Regex::new(&cli.pattern).unwrap();352 let mut stdout = Vec::new();353 let mut stderr = Vec::new();354 let status = run(355 &cli,356 ®ex,357 io::Cursor::new(input),358 &mut stdout,359 &mut stderr,360 );361 (362 status,363 String::from_utf8(stdout).unwrap(),364 String::from_utf8(stderr).unwrap(),365 )366 }367368 #[test]369 fn prints_matching_lines_and_line_numbers() {370 let (status, output, error) = search("none\nRust here\n", &["-n", "Rust"]);371 assert_eq!(status, 0);372 assert_eq!(output, "2:Rust here\n");373 assert!(error.is_empty());374 }375376 #[test]377 fn supports_case_insensitive_inverted_and_count_modes() {378 let (status, output, _) = search("Rust\nother\nRUST\n", &["-i", "-v", "-c", "rust"]);379 assert_eq!(status, 0);380 assert_eq!(output, "1\n");381 }382383 #[test]384 fn prints_each_matching_part() {385 let (status, output, _) = search("aba ab\n", &["-o", "ab"]);386 assert_eq!(status, 0);387 assert_eq!(output, "ab\nab\n");388 }389390 #[test]391 fn no_match_has_grep_exit_status() {392 let (status, output, _) = search("nothing\n", &["needle"]);393 assert_eq!(status, 1);394 assert!(output.is_empty());395 }396397 #[test]398 fn color_can_be_forced_or_disabled() {399 let (_, colored, _) = search("needle\n", &["--color=always", "needle"]);400 assert_eq!(colored, "\x1b[1;31mneedle\x1b[0m\n");401 let (_, plain, _) = search("needle\n", &["--color=never", "needle"]);402 assert_eq!(plain, "needle\n");403 }404}