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
Provenance
- Commit
3797a2a- Tree
e0508fb- Author
Andrew Gallant <jamslam@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
0e2f8f7
1 file changed+12 added−27 removed
modified:grep/examples/simplegrep.rs+12 added-27 removed
1 unmodified line2 extern crate termcolor;3 extern crate walkdir;4 5 use std::env;6+use std::error::Error;7 use std::ffi::OsString;7-use std::path::Path;8 use std::process;9-use std::result;9 10 use grep::cli;11 use grep::printer::{ColorSpecs, StandardBuilder};12 use grep::regex::RegexMatcher;13 use grep::searcher::{BinaryDetection, SearcherBuilder};14 use termcolor::ColorChoice;15 use walkdir::WalkDir;16 18-macro_rules! fail {19- ($($tt:tt)*) => {20- return Err(From::from(format!($($tt)*)));21- }22-}23-24-type Result<T> = result::Result<T, Box<::std::error::Error>>;25-17 fn main() {18 if let Err(err) = try_main() {19 eprintln!("{}", err);20 process::exit(1);21 }22 }23 33-fn try_main() -> Result<()> {24+fn 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 }34 44-fn search(pattern: &str, paths: &[OsString]) -> Result<()> {35+fn 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+ ));50 51 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 lines71 }72 }73 Ok(())74 }82-83-fn color_choice() -> ColorChoice {84- if cli::is_tty_stdout() {85- ColorChoice::Auto86- } else {87- ColorChoice::Never88- }89-}