use argenv_resolve::*;
use std::path::PathBuf;
use std::process::ExitCode;
contract! {
HELP: bool = Input {
key: "help",
ty: Type::Bool,
default: Some(false),
arg: Some(Arg::pair("help", 'h')),
summary: "Show this help and exit.",
..Input::EMPTY
};
QUERY: String = Input {
key: "query",
ty: Type::String,
arg: Some(Arg { value_name: "QUERY", ..Arg::positional(0) }),
summary: "The text to search for.",
..Input::EMPTY
};
FILE_PATH: PathBuf = Input {
key: "file_path",
ty: Type::Path,
arg: Some(Arg { value_name: "FILE", ..Arg::positional(1) }),
summary: "The file to search in.",
..Input::EMPTY
};
IGNORE_CASE: bool = Input {
key: "ignore_case",
ty: Type::Bool,
default: Some(false),
env: Some(Env::new("IGNORE_CASE")),
arg: Some(Arg::pair("ignore-case", 'i')),
summary: "Ignore the case of the query and of the text.",
..Input::EMPTY
};
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.contains(query))
.collect()
}
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
contents
.lines()
.filter(|line| line.to_lowercase().contains(&query))
.collect()
}
pub fn grep<'a>(query: &str, contents: &'a str, ignore_case: bool) -> Vec<&'a str> {
if ignore_case {
search_case_insensitive(query, contents)
} else {
search(query, contents)
}
}
pub fn usage() -> String {
let mut text = String::from("usage: minigrep [OPTIONS] <QUERY> <FILE>\n\n");
for record in Contract::records() {
text.push_str(&format!(
" {:<20} {}\n",
record.usage(),
record.summary.as_deref().unwrap_or("")
));
if !record.env_names().is_empty() {
text.push_str(&format!(
" {:<20} (or set {})\n",
"",
record.env_names().join(", ")
));
}
}
text
}
fn main() -> ExitCode {
let resolution = Contract::parse_and_lint(OnProblems::FailOnError);
if Contract::HELP.get_from_or_default(&resolution) == Some(true) {
print!("{}", usage());
return ExitCode::SUCCESS;
}
let (Some(query), Some(path)) = (
Contract::QUERY.get_from(&resolution),
Contract::FILE_PATH.get_from(&resolution),
) else {
eprint!("{}", usage());
return ExitCode::from(2);
};
let ignore_case = Contract::IGNORE_CASE
.get_from_or_default(&resolution)
.unwrap_or(false);
let contents = match std::fs::read_to_string(&path) {
Ok(contents) => contents,
Err(error) => {
eprintln!("minigrep: cannot read {}: {error}", path.display());
return ExitCode::FAILURE;
}
};
for line in grep(&query, &contents, ignore_case) {
println!("{line}");
}
ExitCode::SUCCESS
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn resolve(args: &[&str], env: &[(&str, &str)]) -> Resolution {
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
let env: BTreeMap<String, String> = env
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Invocation {
args: &args,
env: &env,
}
.resolve(&Contract::records())
}
fn ignore_case(args: &[&str], env: &[(&str, &str)]) -> bool {
let r = resolve(args, env);
Contract::IGNORE_CASE
.get_from_or_default(&r)
.unwrap_or(false)
}
#[test]
fn the_declaration_is_valid() {
assert!(
Contract::problems().is_empty(),
"{:#?}",
Contract::problems()
);
}
#[test]
fn the_two_positionals_are_the_query_and_the_file() {
let r = resolve(&["duct", "poem.txt"], &[]);
assert_eq!(Contract::QUERY.get_from(&r).as_deref(), Some("duct"));
assert_eq!(
Contract::FILE_PATH.get_from(&r),
Some(PathBuf::from("poem.txt"))
);
}
#[test]
fn case_is_respected_unless_asked_otherwise() {
assert!(!ignore_case(&["q", "f"], &[]));
}
#[test]
fn the_flag_turns_it_on_in_both_spellings() {
assert!(ignore_case(&["--ignore-case", "q", "f"], &[]));
assert!(ignore_case(&["-i", "q", "f"], &[]));
}
#[test]
fn the_environment_variable_turns_it_on_like_in_the_book() {
assert!(ignore_case(&["q", "f"], &[("IGNORE_CASE", "1")]));
}
#[test]
fn a_false_value_means_off_which_is_where_this_differs_from_the_book() {
assert!(!ignore_case(&["q", "f"], &[("IGNORE_CASE", "0")]));
}
#[test]
fn the_flag_wins_over_the_environment() {
assert!(ignore_case(
&["--ignore-case", "q", "f"],
&[("IGNORE_CASE", "0")]
));
}
#[test]
fn a_misspelled_flag_is_reported_with_the_right_suggestion() {
let r = resolve(&["--ignore-cas", "q", "f"], &[]);
let findings = lint(&Contract::records(), &r);
assert!(
findings.iter().any(|f| matches!(
f,
Finding::UnknownArg { did_you_mean: Some(s), .. } if s == "--ignore-case"
)),
"{findings:#?}"
);
}
#[test]
fn an_invalid_value_for_the_variable_is_an_error_naming_where_it_came_from() {
let r = resolve(&["q", "f"], &[("IGNORE_CASE", "maybe")]);
let findings = lint(&Contract::records(), &r);
let error = findings
.iter()
.find(|f| f.severity() == Severity::Error)
.expect("an error finding");
assert!(error.to_string().contains("environment"), "{error}");
}
#[test]
fn the_usage_text_mentions_every_input_and_the_variable() {
let text = usage();
for needle in [
"<QUERY>",
"<FILE>",
"--ignore-case",
"-i",
"IGNORE_CASE",
"--help",
] {
assert!(text.contains(needle), "usage lacks {needle}:\n{text}");
}
}
#[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)
);
}
#[test]
fn grep_picks_the_search_by_the_setting() {
let contents = "Rust:\nTrust me.";
assert_eq!(grep("rust", contents, false), vec!["Trust me."]);
assert_eq!(grep("rust", contents, true), vec!["Rust:", "Trust me."]);
}
}