From 9b56cecda8fb33cb006d40d2e367bca2796c7d23 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Thu, 21 Apr 2016 02:47:29 -0400 Subject: find_alias_in_file: Return a vector of matches Instead of returning a boolean value, get all lines that include the alias being searched for. This will give us a list of values like: Ok([ "alias farnsworth-hubert Hubert Farnsworth ", "alias farnsworth-hubert-2 Hubert Farnsworth ", "alias farnsworth-hubert-3 Hubert Farnsworth " ]) Our list will contain all Mutt alias calls that start with the given alias string. Use my new learnings from the Error Handling section of the Rust book (http://doc.rust-lang.org/book/error-handling.html). We return a Result type so that we can communicate both File IO errors and our own custom matching errors. We define a new error type that allows us to provide information about the reason for our own errors. Note that I haven't yet implemented the required `fmt::Display` and `error::Error` methods on my custom error type yet as those didn't appear to be crucial to just getting this working. Change the `line.unwrap()` line to `try!(line)` so that we don't panic in the event of an error, but instead bubble the error upstream. If we come across a Mutt alias that has the same email as the inputted search alias, we want to abort because we shouldn't add a new Mutt alias line for an existing email address that's already been aliased. --- src/main.rs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index a4a36e5..aebabef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -81,22 +81,44 @@ fn build_alias(s: &str) -> String { alias_line } -fn find_alias_in_file(alias: &Alias, file: &str) -> Result<(), io::Error> { +#[derive(Debug)] +enum AliasSearchError { + NotFound, + EmailExists, + Io(io::Error), +} + +// impl fmt::Display for AliasSearchError {} +// impl error::Error for AliasSearchError {} + +impl From for AliasSearchError { + fn from(err: io::Error) -> AliasSearchError { + AliasSearchError::Io(err) + } +} + +fn find_alias_in_file(alias: &Alias, file: &str) -> Result, AliasSearchError> { + let mut matches = Vec::new(); let f = try!(File::open(file)); let file = BufReader::new(&f); for line in file.lines() { - let line = line.unwrap(); + let line = try!(line); let split: Vec<&str> = line.split_whitespace().collect(); - // if email is in alias file - // return true + if line.contains(&alias.email) { + return Err(AliasSearchError::EmailExists) + } if split[1].starts_with(&alias.alias) { - println!("booya"); + matches.push(line.to_owned()); } } - Ok(()) + if matches.is_empty() { + Err(AliasSearchError::NotFound) + } else { + Ok(matches) + } } fn main() { -- cgit v1.2.3