Skip to content
Myr

simplegrep.rs

This file

Path

crates/grep/examples/simplegrep.rs

69 lines · 1.9 KiB · Rust

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 5f5da48 point at it.

globset: support nested alternatesLuke Sandbergbefore adoption5f5da48

lines 1–69why, one step back
1use std::{env, error::Error, ffi::OsString, io::IsTerminal, process};
23use {4 grep::{5 cli,6 printer::{ColorSpecs, StandardBuilder},7 regex::RegexMatcher,8 searcher::{BinaryDetection, SearcherBuilder},9 },10 termcolor::ColorChoice,11 walkdir::WalkDir,12};1314fn main() {15 if let Err(err) = try_main() {16 eprintln!("{}", err);17 process::exit(1);18 }19}2021fn try_main() -> Result<(), Box<dyn Error>> {22 let mut args: Vec<OsString> = env::args_os().collect();23 if args.len() < 2 {24 return Err("Usage: simplegrep <pattern> [<path> ...]".into());25 }26 if args.len() == 2 {27 args.push(OsString::from("./"));28 }29 search(cli::pattern_from_os(&args[1])?, &args[2..])30}3132fn search(pattern: &str, paths: &[OsString]) -> Result<(), Box<dyn Error>> {33 let matcher = RegexMatcher::new_line_matcher(&pattern)?;34 let mut searcher = SearcherBuilder::new()35 .binary_detection(BinaryDetection::quit(b'\x00'))36 .line_number(false)37 .build();38 let mut printer = StandardBuilder::new()39 .color_specs(ColorSpecs::default_with_color())40 .build(cli::stdout(if std::io::stdout().is_terminal() {41 ColorChoice::Auto42 } else {43 ColorChoice::Never44 }));4546 for path in paths {47 for result in WalkDir::new(path) {48 let dent = match result {49 Ok(dent) => dent,50 Err(err) => {51 eprintln!("{}", err);52 continue;53 }54 };55 if !dent.file_type().is_file() {56 continue;57 }58 let result = searcher.search_path(59 &matcher,60 dent.path(),61 printer.sink_with_path(&matcher, dent.path()),62 );63 if let Err(err) = result {64 eprintln!("{}: {}", dent.path().display(), err);65 }66 }67 }68 Ok(())69}