← العودة إلى الدورة: Rust from scratch

Final project: minigrep, a text search tool

الفيديو قريبًا

You have reached the end of the course. In this project you will build minigrep, a reduced version of the grep tool: a command-line program that searches for a text inside a file and shows the lines containing it, with their number. It is a small project, but it uses almost everything you learned: cargo and project structure, structs, methods, Result and the ? operator, iterators and closures, lifetimes, modules, tests, arguments, files and environment variables. Work at your own pace and compile often.

Brief and requirements

  • Create the project with cargo new minigrep and split it into src/main.rs (only coordinates) and src/lib.rs (all the logic).
  • Usage: minigrep <text> <file>. Each line containing the text is printed as "number: line" (the number starts at 1).
  • If the environment variable IGNORE_CASE is set, the search ignores upper and lower case.
  • Missing arguments: usage message on stderr and exit code 2. Unreadable file: error on stderr and code 1. No matches: it prints nothing and exits with 0.
  • Write at least three unit tests and make cargo test pass.
  • Do not use external crates: only the standard library.

Step 1: design

Before writing code, decide the pieces. A Config struct holds the configuration (text, path, ignore case) and is built with Config::build, which validates the arguments and returns a Result. The run function receives the configuration, reads the file and prints results, returning Result<(), Box<dyn Error>> so you can use ? with any error. The search and search_case_insensitive functions do the pure search, without reading files or printing: that makes them easy to test. main only joins everything and decides the exit code. This separation between logic and input/output is the key to a maintainable program.

Step 2: the library (src/lib.rs)

This is the complete code of the library, with its tests. Before copying it, try to write search and the tests yourself, and compare. Notice the lifetime of search: the returned lines are slices of the original text, so they are tied to contents and not to query. Also notice that the case-insensitive search converts both the query and each line to lowercase, but returns the original line.

rust
use std::env;
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }
        // ignore case if the env var is set (any value)
        let ignore_case = env::var("IGNORE_CASE").is_ok();
        Ok(Config { query: args[1].clone(), path: args[2].clone(), ignore_case })
    }
}

pub fn run(config: &Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(&config.path)?;
    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };
    for (number, line) in results {
        println!("{number}: {line}");
    }
    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<(usize, &'a str)> {
    contents
        .lines()
        .enumerate()
        .filter(|(_, line)| line.contains(query))
        .map(|(i, line)| (i + 1, line))
        .collect()
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<(usize, &'a str)> {
    let query = query.to_lowercase();
    contents
        .lines()
        .enumerate()
        .filter(|(_, line)| line.to_lowercase().contains(&query))
        .map(|(i, line)| (i + 1, line))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEXT: &str = "Rust is fast.\nSafe, productive.\nPick three.\nTrust me.";

    #[test]
    fn case_sensitive() {
        assert_eq!(search("rust", TEXT), vec![(4, "Trust me.")]);
    }

    #[test]
    fn case_insensitive() {
        assert_eq!(
            search_case_insensitive("rUsT", TEXT),
            vec![(1, "Rust is fast."), (4, "Trust me.")]
        );
    }

    #[test]
    fn config_needs_two_arguments() {
        let args = vec![String::from("minigrep")];
        assert!(Config::build(&args).is_err());
    }
}

Step 3: the main program (src/main.rs)

main is deliberately short: it collects the arguments, builds the configuration, calls run and translates errors into messages on stderr and exit codes. unwrap_or_else receives a closure that runs only if Config::build returns Err; there we print the usage and finish with code 2. Since all the logic is in the library, the binary imports it with the package name (use minigrep::Config).

rust
use std::env;
use std::process;

use minigrep::Config;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        eprintln!("usage: minigrep <query> <file>");
        process::exit(2);
    });

    if let Err(e) = minigrep::run(&config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}

Step 4: try it and verify

Create a file poem.txt with four lines (for example "Rust is fast.", "Safe, productive.", "Pick three." and "Trust me.") and run the following commands. With the normal search only "Trust me." matches because the "R" of "Rust" is uppercase; with IGNORE_CASE both lines appear. Also check the exit codes: 0 when all goes well, 1 if the file does not exist and 2 if arguments are missing.

sh
# Run the tests
cargo test

# Normal search: prints "4: Trust me."
cargo run -- rust poem.txt

# Ignoring case (bash): prints "1: Rust is fast." and "4: Trust me."
IGNORE_CASE=1 cargo run -- rust poem.txt
# PowerShell: $env:IGNORE_CASE = "1"; cargo run -- rust poem.txt

# Errors: exit code 1 (missing file) and 2 (missing arguments)
cargo run -- rust nofile.txt
cargo run

Completion criteria and extensions

You can consider the project finished when: cargo build gives no errors or warnings; cargo test passes with at least three tests; the commands above produce exactly the described output, with exit codes 0, 1 and 2; main.rs contains no search logic; and there is no unwrap() on data coming from the user. If you want to go further, add as extensions: a --count option to show only how many lines match, searching several files, searching recursively in a folder, coloring the match, or parallelizing the search of several files with threads and a channel, as in week 8.

اختبر ما تعلمته

السؤال 1 من 7

Why is the logic separated into lib.rs instead of main.rs?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابق