From cc6483b5b30a5a002fd7757e858f4c7509e6c98a Mon Sep 17 00:00:00 2001 From: sgoudham Date: Tue, 18 Jan 2022 02:00:29 +0000 Subject: [PATCH] Add minigrep --- minigrep/Cargo.toml | 8 ++++++++ minigrep/src/lib.rs | 28 ++++++++++++++++++++++++++++ minigrep/src/main.rs | 22 ++++++++++++++++++++++ minigrep/src/resources/poem.txt | 9 +++++++++ 4 files changed, 67 insertions(+) create mode 100644 minigrep/Cargo.toml create mode 100644 minigrep/src/lib.rs create mode 100644 minigrep/src/main.rs create mode 100644 minigrep/src/resources/poem.txt diff --git a/minigrep/Cargo.toml b/minigrep/Cargo.toml new file mode 100644 index 0000000..a256566 --- /dev/null +++ b/minigrep/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "minigrep" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/minigrep/src/lib.rs b/minigrep/src/lib.rs new file mode 100644 index 0000000..993973e --- /dev/null +++ b/minigrep/src/lib.rs @@ -0,0 +1,28 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) +} \ No newline at end of file diff --git a/minigrep/src/main.rs b/minigrep/src/main.rs new file mode 100644 index 0000000..22a9291 --- /dev/null +++ b/minigrep/src/main.rs @@ -0,0 +1,22 @@ +use std::{env, process}; + +use minigrep::{ + Config, + run, +}; + +fn main() { + let args: Vec = env::args().collect(); + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + if let Err(e) = run(config) { + println!("Application error: {}", e); + process::exit(1); + } +} \ No newline at end of file diff --git a/minigrep/src/resources/poem.txt b/minigrep/src/resources/poem.txt new file mode 100644 index 0000000..3a260bf --- /dev/null +++ b/minigrep/src/resources/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