1use argenv_resolve::*;
30use std::path::PathBuf;
31use std::process::ExitCode;
32
33contract! {
34 HELP: bool = Input {
35 key: "help",
36 ty: Type::Bool,
37 default: Some(false),
38 arg: Some(Arg::pair("help", 'h')),
39 summary: "Show this help and exit.",
40 ..Input::EMPTY
41 };
42
43 QUERY: String = Input {
45 key: "query",
46 ty: Type::String,
47 arg: Some(Arg { value_name: "QUERY", ..Arg::positional(0) }),
48 summary: "The text to search for.",
49 ..Input::EMPTY
50 };
51
52 FILE_PATH: PathBuf = Input {
53 key: "file_path",
54 ty: Type::Path,
55 arg: Some(Arg { value_name: "FILE", ..Arg::positional(1) }),
56 summary: "The file to search in.",
57 ..Input::EMPTY
58 };
59
60 IGNORE_CASE: bool = Input {
62 key: "ignore_case",
63 ty: Type::Bool,
64 default: Some(false),
65 env: Some(Env::new("IGNORE_CASE")),
66 arg: Some(Arg::pair("ignore-case", 'i')),
67 summary: "Ignore the case of the query and of the text.",
68 ..Input::EMPTY
69 };
70}
71
72pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
74 contents
75 .lines()
76 .filter(|line| line.contains(query))
77 .collect()
78}
79
80pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
82 let query = query.to_lowercase();
83 contents
84 .lines()
85 .filter(|line| line.to_lowercase().contains(&query))
86 .collect()
87}
88
89pub fn grep<'a>(query: &str, contents: &'a str, ignore_case: bool) -> Vec<&'a str> {
91 if ignore_case {
92 search_case_insensitive(query, contents)
93 } else {
94 search(query, contents)
95 }
96}
97
98pub fn usage() -> String {
100 let mut text = String::from("usage: minigrep [OPTIONS] <QUERY> <FILE>\n\n");
101 for record in Contract::records() {
102 text.push_str(&format!(
103 " {:<20} {}\n",
104 record.usage(),
105 record.summary.as_deref().unwrap_or("")
106 ));
107 if !record.env_names().is_empty() {
108 text.push_str(&format!(
109 " {:<20} (or set {})\n",
110 "",
111 record.env_names().join(", ")
112 ));
113 }
114 }
115 text
116}
117
118fn main() -> ExitCode {
119 let resolution = Contract::parse_and_lint(OnProblems::FailOnError);
124
125 if Contract::HELP.get_from_or_default(&resolution) == Some(true) {
126 print!("{}", usage());
127 return ExitCode::SUCCESS;
128 }
129 let (Some(query), Some(path)) = (
130 Contract::QUERY.get_from(&resolution),
131 Contract::FILE_PATH.get_from(&resolution),
132 ) else {
133 eprint!("{}", usage());
134 return ExitCode::from(2);
135 };
136 let ignore_case = Contract::IGNORE_CASE
137 .get_from_or_default(&resolution)
138 .unwrap_or(false);
139
140 let contents = match std::fs::read_to_string(&path) {
141 Ok(contents) => contents,
142 Err(error) => {
143 eprintln!("minigrep: cannot read {}: {error}", path.display());
144 return ExitCode::FAILURE;
145 }
146 };
147 for line in grep(&query, &contents, ignore_case) {
148 println!("{line}");
149 }
150 ExitCode::SUCCESS
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156 use std::collections::BTreeMap;
157
158 fn resolve(args: &[&str], env: &[(&str, &str)]) -> Resolution {
159 let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
160 let env: BTreeMap<String, String> = env
161 .iter()
162 .map(|(k, v)| (k.to_string(), v.to_string()))
163 .collect();
164 Invocation {
165 args: &args,
166 env: &env,
167 }
168 .resolve(&Contract::records())
169 }
170
171 fn ignore_case(args: &[&str], env: &[(&str, &str)]) -> bool {
172 let r = resolve(args, env);
173 Contract::IGNORE_CASE
174 .get_from_or_default(&r)
175 .unwrap_or(false)
176 }
177
178 #[test]
181 fn the_declaration_is_valid() {
182 assert!(
183 Contract::problems().is_empty(),
184 "{:#?}",
185 Contract::problems()
186 );
187 }
188
189 #[test]
190 fn the_two_positionals_are_the_query_and_the_file() {
191 let r = resolve(&["duct", "poem.txt"], &[]);
192 assert_eq!(Contract::QUERY.get_from(&r).as_deref(), Some("duct"));
193 assert_eq!(
194 Contract::FILE_PATH.get_from(&r),
195 Some(PathBuf::from("poem.txt"))
196 );
197 }
198
199 #[test]
202 fn case_is_respected_unless_asked_otherwise() {
203 assert!(!ignore_case(&["q", "f"], &[]));
204 }
205
206 #[test]
207 fn the_flag_turns_it_on_in_both_spellings() {
208 assert!(ignore_case(&["--ignore-case", "q", "f"], &[]));
209 assert!(ignore_case(&["-i", "q", "f"], &[]));
210 }
211
212 #[test]
213 fn the_environment_variable_turns_it_on_like_in_the_book() {
214 assert!(ignore_case(&["q", "f"], &[("IGNORE_CASE", "1")]));
215 }
216
217 #[test]
218 fn a_false_value_means_off_which_is_where_this_differs_from_the_book() {
219 assert!(!ignore_case(&["q", "f"], &[("IGNORE_CASE", "0")]));
221 }
222
223 #[test]
224 fn the_flag_wins_over_the_environment() {
225 assert!(ignore_case(
226 &["--ignore-case", "q", "f"],
227 &[("IGNORE_CASE", "0")]
228 ));
229 }
230
231 #[test]
234 fn a_misspelled_flag_is_reported_with_the_right_suggestion() {
235 let r = resolve(&["--ignore-cas", "q", "f"], &[]);
236 let findings = lint(&Contract::records(), &r);
237 assert!(
238 findings.iter().any(|f| matches!(
239 f,
240 Finding::UnknownArg { did_you_mean: Some(s), .. } if s == "--ignore-case"
241 )),
242 "{findings:#?}"
243 );
244 }
245
246 #[test]
247 fn an_invalid_value_for_the_variable_is_an_error_naming_where_it_came_from() {
248 let r = resolve(&["q", "f"], &[("IGNORE_CASE", "maybe")]);
249 let findings = lint(&Contract::records(), &r);
250 let error = findings
251 .iter()
252 .find(|f| f.severity() == Severity::Error)
253 .expect("an error finding");
254 assert!(error.to_string().contains("environment"), "{error}");
255 }
256
257 #[test]
258 fn the_usage_text_mentions_every_input_and_the_variable() {
259 let text = usage();
260 for needle in [
261 "<QUERY>",
262 "<FILE>",
263 "--ignore-case",
264 "-i",
265 "IGNORE_CASE",
266 "--help",
267 ] {
268 assert!(text.contains(needle), "usage lacks {needle}:\n{text}");
269 }
270 }
271
272 #[test]
275 fn case_sensitive() {
276 let query = "duct";
277 let contents = "\
278Rust:
279safe, fast, productive.
280Pick three.
281Duct tape.";
282
283 assert_eq!(vec!["safe, fast, productive."], search(query, contents));
284 }
285
286 #[test]
287 fn case_insensitive() {
288 let query = "rUsT";
289 let contents = "\
290Rust:
291safe, fast, productive.
292Pick three.
293Trust me.";
294
295 assert_eq!(
296 vec!["Rust:", "Trust me."],
297 search_case_insensitive(query, contents)
298 );
299 }
300
301 #[test]
302 fn grep_picks_the_search_by_the_setting() {
303 let contents = "Rust:\nTrust me.";
305 assert_eq!(grep("rust", contents, false), vec!["Trust me."]);
306 assert_eq!(grep("rust", contents, true), vec!["Rust:", "Trust me."]);
307 }
308}