From e72fab8dd1ef096e5a9279b3a591298687e9414f Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Tue, 18 Sep 2018 00:24:00 -0600 Subject: [PATCH] v0.1.1: refactor of main --- src/main.rs | 43 ++++++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2bc4859..b56adf4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,8 @@ extern crate grep; use std::env; use std::fs::File; use std::io::prelude::*; +use std::process; +use std::error::Error; struct Config { query: String, @@ -12,27 +14,46 @@ struct Config { fn main() { let args: Vec = env::args().collect(); - let conf = parse_config(&args); + let conf = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + //let filename = &conf.filename.clone(); + if let Err(e) = run(conf) { + println!("Big bad bada boom!\n{:?}", e); + //println!("Big bad bada boom!\n{:?}", e.kind()); + //println!("Big bad bada boom!\n{}", e.description()); + + process::exit(1); + } +} + +//fn run(conf: Config) -> Result<(), Box> +fn run(conf: Config) -> Result<(), Box> { println!("{:?} {:?}", conf.query, conf.filename); - let mut f = File::open(&conf.filename).expect(&("file not found: ".to_owned() + &conf.filename)); - //let mut f = File::open(filename).expect(&format!("file not found: {}", &filename)); + let mut f = File::open(&conf.filename)?; let mut contents = String::new(); - f.read_to_string(&mut contents) - .expect("something went wrong reading the file"); + f.read_to_string(&mut contents)?; println!("Searching for '{}'", conf.query); println!("In file '{}'", conf.filename); println!("With text:\n{}", contents); + + Ok(()) } -//fn parse_config(args: &[String]) -> (&String, &String) -//fn parse_config(args: &[String]) -> (&str, &str) -fn parse_config(args: &[String]) -> Config { - Config { - query: args[1].clone(), - filename: args[2].clone(), +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("too few arguments") + } + + Ok(Config { + query: args[1].clone(), + filename: args[2].clone(), + }) } }