145 lines
3.1 KiB
Rust

use std::fs;
use std::error::Error;
use std::env;
// refactor 9
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
// refactor 14
// pub fn build(args: &[String]) -> Result<Config, &'static str> {
// 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 })
// }
pub fn build(mut args: impl Iterator<Item = String>,) -> Result<Config, &'static str> {
// --snip-- for now
// skip first value in iterator, value inside is name of program
args.next();
let query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string"),
};
let file_path = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file path")
};
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
// refactor 10
// println!("With text:\n{contents}")
// refactor 12
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
// refactor 12
// for line in search(&config.query, &contents) {
// println!("{line}");
// }
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
// refacotr 15
// // original that only can fail
// // vec![]
// let mut results = Vec::new();
// for line in contents.lines() {
// if line.contains(query) {
// // do something with line
// results.push(line);
// }
// }
// results
contents
.lines()
.filter(|line| line.contains(query))
.collect()
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str
) -> Vec<&'a str> {
// orignal that only fails
// vec![]
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."], search_case_insensitive(query, contents)
);
}
}