Skip to main content

minigrep/
minigrep.rs

1//! The Rust Book's `minigrep` (chapter 12), with its arguments and its environment declared
2//! once instead of read by hand.
3//!
4//! Chapter 12 of *The Rust Programming Language* builds a tiny `grep`: two positional arguments
5//! (a query and a file) and a case-insensitive mode switched on by the `IGNORE_CASE` variable.
6//! The book reads each one by hand (`args[1]`, `env::var("IGNORE_CASE").is_ok()`), which is the
7//! right way to *learn* the standard library. This example is the same program with the
8//! invocation written as data. What that buys, for the price of one declaration:
9//!
10//! - `IGNORE_CASE=1`, `--ignore-case` and `-i` are one setting with two doors, and the flag wins;
11//! - a misspelled flag stops the program with a suggestion instead of being ignored;
12//! - the usage text is generated from the declaration, so it cannot disagree with what is parsed;
13//! - the same declaration can be published (`Contract::records()`) for tools to read.
14//!
15//! One behaviour differs from the book, on purpose: the book treats *any* value of `IGNORE_CASE`
16//! as "on" (it only asks whether the variable is set), so `IGNORE_CASE=0` still ignores case.
17//! Here the variable is a boolean, so `0`, `false`, `off` and `no` mean off.
18//!
19//! The `search` functions and their tests are the book's, under the same MIT OR Apache-2.0 terms
20//! as this crate.
21//!
22//! ```text
23//! cargo run -p argenv-resolve --example minigrep -- duct poem.txt
24//! cargo run -p argenv-resolve --example minigrep -- --ignore-case rUsT poem.txt
25//! IGNORE_CASE=1 cargo run -p argenv-resolve --example minigrep -- rUsT poem.txt
26//! cargo run -p argenv-resolve --example minigrep -- --ignore-cas rust poem.txt   # a suggestion
27//! cargo run -p argenv-resolve --example minigrep -- --help
28//! ```
29use 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    // Positional arguments are numbered from zero, in the order they appear.
44    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    // The book's `IGNORE_CASE`: one setting, two doors, declared next to each other.
61    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
72/// The book's `search` (listing 12-19).
73pub 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
80/// The book's `search_case_insensitive` (listing 12-21).
81pub 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
89/// The lines that match, case-sensitively or not.
90pub 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
98/// Usage text, generated from the declaration.
99pub 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    // A misspelled flag or variable is an error by default, so `--ignore-cas` stops the program
120    // here instead of running the search case-sensitively. A program that would rather carry on
121    // says so with its own policy: `Contract::parse_and_lint_with(OnProblems::FailOnError,
122    // &LintPolicy::lenient())`.
123    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    // ---- the declaration -------------------------------------------------------------
179
180    #[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    // ---- ignore case: one setting, two doors -----------------------------------------
200
201    #[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        // The book only asks whether IGNORE_CASE is set, so IGNORE_CASE=0 still ignores case.
220        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    // ---- what declaring it catches ---------------------------------------------------
232
233    #[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    // ---- the book's own search tests (listings 12-20 and 12-21) ----------------------
273
274    #[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        // "Trust me." contains a lowercase "rust"; "Rust:" does not.
304        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}