Skip to content
Myr

simplegrep: touch up

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Andrew Gallant · committed by Andrew Gallant · parent 0e2f8f7 · Browse files · 1 file+12 added−27 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+12 added−27 removed

  • other:+12 added−27 removed

1 file+12 added−27 removed

modified:grep/examples/simplegrep.rs+12 added-27 removed
1 unmodified line
2extern crate termcolor;3extern crate walkdir;45use std::env;6use std::error::Error;7use std::ffi::OsString;7use std::path::Path;8use std::process;9use std::result;910use grep::cli;11use grep::printer::{ColorSpecs, StandardBuilder};12use grep::regex::RegexMatcher;13use grep::searcher::{BinaryDetection, SearcherBuilder};14use termcolor::ColorChoice;15use walkdir::WalkDir;1618macro_rules! fail {19 ($($tt:tt)*) => {20 return Err(From::from(format!($($tt)*)));21 }22}2324type Result<T> = result::Result<T, Box<::std::error::Error>>;2517fn main() {18 if let Err(err) = try_main() {19 eprintln!("{}", err);20 process::exit(1);21 }22}2333fn try_main() -> Result<()> {24fn try_main() -> Result<(), Box<Error>> {25 let mut args: Vec<OsString> = env::args_os().collect();26 if args.len() < 2 {36 fail!("Usage: simplegrep <pattern> [<path> ...]");27 return Err("Usage: simplegrep <pattern> [<path> ...]".into());28 }29 if args.len() == 2 {30 args.push(OsString::from("./"));31 }32 search(cli::pattern_from_os(&args[1])?, &args[2..])33}3444fn search(pattern: &str, paths: &[OsString]) -> Result<()> {35fn search(pattern: &str, paths: &[OsString]) -> Result<(), Box<Error>> {36 let matcher = RegexMatcher::new_line_matcher(&pattern)?;37 let mut searcher = SearcherBuilder::new()38 .binary_detection(BinaryDetection::quit(b'\x00'))39 .line_number(false)40 .build();41 let mut printer = StandardBuilder::new()42 .color_specs(ColorSpecs::default_with_color())52 .build(cli::stdout(color_choice()));43 .build(cli::stdout(44 if cli::is_tty_stdout() {45 ColorChoice::Auto46 } else {47 ColorChoice::Never48 }49 ));5051 for path in paths {52 for result in WalkDir::new(path) {53 let dent = match result {54 Ok(dent) => dent,55 Err(err) => {59 eprintln!(60 "{}: {}",61 err.path().unwrap_or(Path::new("error")).display(),62 err,63 );56 eprintln!("{}", err);57 continue;58 }59 };60 if !dent.file_type().is_file() {
10 unmodified lines
71 }72 }73 Ok(())74}8283fn color_choice() -> ColorChoice {84 if cli::is_tty_stdout() {85 ColorChoice::Auto86 } else {87 ColorChoice::Never88 }89}