diff --git a/poem.txt b/poem.txt new file mode 100644 index 0000000..3a260bf --- /dev/null +++ b/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..19e8e50 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,4 @@ +//TODO implement search function +pub fn search() { + unimplemented!(); +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index b0b38db..6fc4d3e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,64 @@ +use std::fs; use std::env; +use std::error::Error; +use std::process; -fn main() { +use minigrep::search; + + +fn main() -> Result<(), Box> { // Args returns an iterator of args from cli // Collect turns an iterator into a collection // In this case transform values of args into a vector let args: Vec = env::args().collect(); - let query = &args[0]; - let file_path = &args[1]; + - println!("Searching for {query}"); - println!("In file {file_path}"); - // TODO handle the case of less or more parameters entered by user + // let config = Config::build(&args)?; + // or + let config = Config::build(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {err}"); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.file_path); + + // run(config)?; + // or + if let Err(e) = run(config) { + println!("Application error: {e}"); + process::exit(1); + } + + Ok(()) +} + +fn run (config: Config) -> Result<(), Box> { + let contents: String = fs::read_to_string(config.file_path)?; + println!("With text:\n{contents}"); + + search(); + + Ok(()) +} + +struct Config { + query: String, + file_path: String, +} + +impl Config { + fn build(args: &[String]) -> Result { + if args.len() > 3 { + return Err("Too many arguments. Usage: minigrep "); + } + if args.len() < 3 { + return Err("Too few arguments. Usage: minigrep "); + } + let query = args[1].clone(); + let file_path = args[2].clone(); + + Ok(Config { query, file_path }) + } }