Skip to content

Commit bfae3dd

Browse files
committed
minigrep
1 parent 79e541b commit bfae3dd

File tree

5 files changed

+74
-0
lines changed

5 files changed

+74
-0
lines changed

minigrep/Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

minigrep/Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "minigrep"
3+
version = "0.1.0"
4+
edition = "2024"
5+
6+
[dependencies]

minigrep/poem.txt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
I'm nobody! Who are you?
2+
Are you nobody, too?
3+
Then there's a pair of us - don't tell!
4+
They'd banish us, you know.
5+
6+
How dreary to be somebody!
7+
How public, like a frog
8+
To tell your name the livelong day
9+
To an admiring bog!

minigrep/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
pub fn search<'a>(query: &str, contains: &'a str) -> Vec<&'a str> {
2+
unimplemented!()
3+
}

minigrep/src/main.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use std::{
2+
env,
3+
fs,
4+
process,
5+
error::Error,
6+
};
7+
use minigrep::search;
8+
9+
fn main() {
10+
let args: Vec<String> = env::args().collect();
11+
let config = Config::build(&args).unwrap_or_else(|err| {
12+
println!("Problem parsing arguments: {err}");
13+
process::exit(1);
14+
});
15+
println!("Searching for {}", config.query);
16+
println!("In file {}", config.file_path);
17+
// read the file
18+
if let Err(e) = run(config) {
19+
println!("Application error {e}");
20+
process::exit(1);
21+
}
22+
}
23+
24+
struct Config {
25+
query: String,
26+
file_path: String,
27+
}
28+
29+
impl Config {
30+
fn build(args: &[String]) -> Result<Config, &'static str> {
31+
if args.len() < 3 {
32+
return Err("Not enough arguments");
33+
}
34+
let query = args[1].clone();
35+
let file_path = args[2].clone();
36+
37+
Ok(Config {query, file_path})
38+
}
39+
}
40+
41+
fn run(config: Config) -> Result<(), Box<dyn Error>> {
42+
let contents: String = fs::read_to_string(config.file_path)?;
43+
44+
// println!("With text:\n{contents}");
45+
for line in search(&config.query, &contents) {
46+
println!("{line}");
47+
}
48+
Ok(())
49+
}

0 commit comments

Comments
 (0)