Code cleanup, error handling, closes #1

This commit is contained in:
sharkdp 2017-05-12 12:39:13 +02:00
parent 23e51da3c9
commit b1baa5cb76
1 changed files with 24 additions and 22 deletions

View File

@ -30,23 +30,25 @@ fn scan(root: &Path, pattern: &Regex) {
continue; continue;
} }
let path_relative = entry.path().strip_prefix(root).unwrap(); let path_str_r = entry
let path_str = match path_relative.to_str() { .path()
Some(s) => s, .strip_prefix(root) // create relative path
.ok()
.and_then(Path::to_str);
let path_str = match path_str_r {
Some(p) => p,
None => continue None => continue
}; };
match pattern.find(path_str) {
Some(_) => pattern.find(path_str)
println!("{}", path_str), .map(|_| println!("{}", path_str));
None =>
continue
}
} }
} }
/// Print error message to stderr and exit with status `1`. /// Print error message to stderr and exit with status `1`.
fn error<T: Error>(err: &T) -> ! { fn error(message: &str) -> ! {
writeln!(&mut std::io::stderr(), "{}", err.description()) writeln!(&mut std::io::stderr(), "{}", message)
.expect("Failed writing to stderr"); .expect("Failed writing to stderr");
process::exit(1); process::exit(1);
} }
@ -58,8 +60,8 @@ fn main() {
opts.optflag("h", "help", "print this help message"); opts.optflag("h", "help", "print this help message");
opts.optflag("s", "sensitive", "case-sensitive search"); opts.optflag("s", "sensitive", "case-sensitive search");
let matches = match opts.parse(&args[1..]) { let matches = match opts.parse(&args[1..]) {
Ok(m) => { m } Ok(m) => m,
Err(f) => { error(&f) } Err(e) => error(e.description())
}; };
if matches.opt_present("h") { if matches.opt_present("h") {
@ -73,16 +75,16 @@ fn main() {
let empty = String::new(); let empty = String::new();
let pattern = matches.free.get(0).unwrap_or(&empty); let pattern = matches.free.get(0).unwrap_or(&empty);
let current_dir_buf = env::current_dir() let current_dir_buf = match env::current_dir() {
.expect("Could not get current directory!"); Ok(cd) => cd,
Err(_) => error("Could not get current directory!")
};
let current_dir = current_dir_buf.as_path(); let current_dir = current_dir_buf.as_path();
match match RegexBuilder::new(pattern)
RegexBuilder::new(pattern) .case_insensitive(case_insensitive)
.case_insensitive(case_insensitive) .build() {
.build() { Ok(re) => scan(current_dir, &re),
Ok(re) => Err(err) => error(err.description())
scan(current_dir, &re),
Err(err) => error(&err)
} }
} }