Skip to content

Commit 713f7a5

Browse files
committed
refactor code for proper error handling and testing
1 parent 112003c commit 713f7a5

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

src/main.rs

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,40 @@
1-
use std::{env, fs};
1+
use std::{env, error::Error, fs, process};
22

33
fn main() {
44
let args: Vec<String> = env::args().collect();
55

6-
let query = &args[1];
7-
let file_path = &args[2];
6+
let config = Config::build(&args).unwrap_or_else(|err| {
7+
println!("Problem parsing arguments: {}", err);
8+
process::exit(1);
9+
});
810

9-
println!("Searching for {}", query);
10-
println!("In file {}\n", file_path);
11+
println!("Searching for {}", config.query);
12+
println!("In file {}\n", config.file_path);
1113

12-
let contents = fs::read_to_string(file_path)
13-
.expect("Should be able to read the file!");
14+
if let Err(e) = run(config) {
15+
println!("Application error: {}", e);
16+
process::exit(1);
17+
}
18+
}
1419

20+
fn run(config: Config) -> Result<(), Box<dyn Error>> {
21+
let contents = fs::read_to_string(config.file_path)?;
1522
println!("With text contents:\n{}", contents);
23+
Ok(())
24+
}
25+
26+
struct Config {
27+
query: String,
28+
file_path: String,
29+
}
30+
31+
impl Config {
32+
fn build(args: &[String]) -> Result<Config, &'static str> {
33+
if args.len() < 3 {
34+
return Err("No enough arguments");
35+
}
36+
let query = args[1].clone();
37+
let file_path = args[2].clone();
38+
Ok(Config { query, file_path })
39+
}
1640
}

0 commit comments

Comments
 (0)