mirror of https://github.com/KaiserY/trpl-zh-cn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.3 KiB
65 lines
1.3 KiB
use std::env;
|
|
use std::error::Error;
|
|
use std::fs;
|
|
use std::process;
|
|
|
|
use minigrep::{search, search_case_insensitive};
|
|
|
|
fn main() {
|
|
let config = Config::build(env::args()).unwrap_or_else(|err| {
|
|
eprintln!("Problem parsing arguments: {err}");
|
|
process::exit(1);
|
|
});
|
|
|
|
if let Err(e) = run(config) {
|
|
eprintln!("Application error: {e}");
|
|
process::exit(1);
|
|
}
|
|
}
|
|
|
|
pub struct Config {
|
|
pub query: String,
|
|
pub file_path: String,
|
|
pub ignore_case: bool,
|
|
}
|
|
|
|
// ANCHOR: here
|
|
impl Config {
|
|
fn build(
|
|
mut args: impl Iterator<Item = String>,
|
|
) -> Result<Config, &'static str> {
|
|
// --snip--
|
|
// ANCHOR_END: here
|
|
if args.len() < 3 {
|
|
return Err("not enough arguments");
|
|
}
|
|
|
|
let query = args[1].clone();
|
|
let file_path = args[2].clone();
|
|
|
|
let ignore_case = env::var("IGNORE_CASE").is_ok();
|
|
|
|
Ok(Config {
|
|
query,
|
|
file_path,
|
|
ignore_case,
|
|
})
|
|
}
|
|
}
|
|
|
|
fn run(config: Config) -> Result<(), Box<dyn Error>> {
|
|
let contents = fs::read_to_string(config.file_path)?;
|
|
|
|
let results = if config.ignore_case {
|
|
search_case_insensitive(&config.query, &contents)
|
|
} else {
|
|
search(&config.query, &contents)
|
|
};
|
|
|
|
for line in results {
|
|
println!("{line}");
|
|
}
|
|
|
|
Ok(())
|
|
}
|