|
1 |
| -use std::{env, fs}; |
| 1 | +use std::{env, error::Error, fs, process}; |
2 | 2 |
|
3 | 3 | fn main() {
|
4 | 4 | let args: Vec<String> = env::args().collect();
|
5 | 5 |
|
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 | + }); |
8 | 10 |
|
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); |
11 | 13 |
|
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 | +} |
14 | 19 |
|
| 20 | +fn run(config: Config) -> Result<(), Box<dyn Error>> { |
| 21 | + let contents = fs::read_to_string(config.file_path)?; |
15 | 22 | 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 | + } |
16 | 40 | }
|
0 commit comments