Level 2 · Practitioner· Lesson 8 of 8 · 45 min
Project: a command-line search tool
Put Level 2 together — build a small grep with a library core, clean error handling, tests, and idiomatic API design.
You now know enough to build a real tool. This project is a small grep: search files for a pattern and print matching lines. Build it locally — create the project with cargo new minigrep and follow along.
Design
minigrep/
├── Cargo.toml
├── src/
│ ├── main.rs // argument parsing, I/O, exit codes
│ └── lib.rs // Config, search, Match — pure and testable
└── tests/
└── cli.rs
Goals: minigrep [-i] [-n] PATTERN FILE..., exit status 0 if anything matched, 1 if nothing matched, 2 on error — the same convention as grep.
The library core
The whole core runs on the Playground, so you can experiment before creating files:
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub pattern: String,
pub paths: Vec<String>,
pub ignore_case: bool,
pub line_numbers: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum ConfigError {
MissingPattern,
MissingPath,
UnknownFlag(String),
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConfigError::MissingPattern => write!(f, "missing PATTERN"),
ConfigError::MissingPath => write!(f, "missing FILE"),
ConfigError::UnknownFlag(flag) => write!(f, "unknown flag `{flag}`"),
}
}
}
impl std::error::Error for ConfigError {}
impl Config {
/// Builds a configuration from arguments (without the program name).
pub fn parse<I>(args: I) -> Result<Config, ConfigError>
where
I: IntoIterator<Item = String>,
{
let mut ignore_case = false;
let mut line_numbers = false;
let mut positional = Vec::new();
for arg in args {
match arg.as_str() {
"-i" | "--ignore-case" => ignore_case = true,
"-n" | "--line-number" => line_numbers = true,
flag if flag.starts_with('-') && flag.len() > 1 => {
return Err(ConfigError::UnknownFlag(arg));
}
_ => positional.push(arg),
}
}
let mut positional = positional.into_iter();
let pattern = positional.next().ok_or(ConfigError::MissingPattern)?;
let paths: Vec<String> = positional.collect();
if paths.is_empty() {
return Err(ConfigError::MissingPath);
}
Ok(Config { pattern, paths, ignore_case, line_numbers })
}
}
/// One matching line. Borrows from the searched text.
#[derive(Debug, PartialEq, Eq)]
pub struct Match<'a> {
pub line_number: usize,
pub line: &'a str,
}
/// Returns every line of `contents` that contains `pattern`.
pub fn search<'a>(pattern: &str, contents: &'a str, ignore_case: bool) -> Vec<Match<'a>> {
let needle = if ignore_case { pattern.to_lowercase() } else { pattern.to_string() };
contents
.lines()
.enumerate()
.filter(|(_, line)| {
if ignore_case {
line.to_lowercase().contains(&needle)
} else {
line.contains(&needle)
}
})
.map(|(i, line)| Match { line_number: i + 1, line })
.collect()
}
fn main() {
let poem = "I'm nobody! Who are you?\nAre you nobody, too?\nThen there's a pair of us - don't tell!";
let config = Config::parse(["-i", "-n", "ARE", "poem.txt"].map(String::from)).unwrap();
for m in search(&config.pattern, poem, config.ignore_case) {
println!("{}:{}", m.line_number, m.line);
}
println!("{:?}", Config::parse(["--wat".to_string()]));
}
Design points worth noticing:
Config::parseaccepts anyIntoIterator<Item = String>. In production you passstd::env::args().skip(1); in tests you pass an array. No global state, so it is trivially testable.- Errors are a small enum, not strings.
maindecides how to present them. searchis a pure function from text to matches. It does no I/O and returns borrowed slices, so nothing is copied.
The binary
// src/main.rs
use std::process::ExitCode;
use std::{env, fs};
use minigrep::{search, Config};
fn main() -> ExitCode {
let config = match Config::parse(env::args().skip(1)) {
Ok(c) => c,
Err(e) => {
eprintln!("minigrep: {e}");
eprintln!("usage: minigrep [-i] [-n] PATTERN FILE...");
return ExitCode::from(2);
}
};
let mut found = false;
let mut failed = false;
let many = config.paths.len() > 1;
for path in &config.paths {
let contents = match fs::read_to_string(path) {
Ok(c) => c,
Err(e) => {
eprintln!("minigrep: {path}: {e}");
failed = true;
continue;
}
};
for m in search(&config.pattern, &contents, config.ignore_case) {
found = true;
if many {
print!("{path}:");
}
if config.line_numbers {
print!("{}:", m.line_number);
}
println!("{}", m.line);
}
}
if failed {
ExitCode::from(2)
} else if found {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
One unreadable file does not stop the others from being searched — the error is reported on stderr and the loop continues.
Tests
Unit tests go at the bottom of lib.rs:
#[cfg(test)]
mod tests {
use super::*;
fn args(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}
#[test]
fn parses_flags_in_any_position() {
let c = Config::parse(args(&["needle", "-i", "a.txt", "-n", "b.txt"])).unwrap();
assert!(c.ignore_case && c.line_numbers);
assert_eq!(c.paths, ["a.txt", "b.txt"]);
}
#[test]
fn rejects_unknown_flags() {
assert_eq!(
Config::parse(args(&["-x", "p", "f"])),
Err(ConfigError::UnknownFlag("-x".into()))
);
}
#[test]
fn case_sensitive_by_default() {
let text = "Rust\nrust\nTrust";
let lines: Vec<_> = search("rust", text, false).iter().map(|m| m.line_number).collect();
assert_eq!(lines, [2, 3]);
}
#[test]
fn case_insensitive_matches_all() {
assert_eq!(search("RUST", "Rust\nrust\nTrust", true).len(), 3);
}
}
For end-to-end tests of the compiled binary, the assert_cmd crate runs it and asserts on output and exit status.
Take it further
Each of these is a worthwhile exercise:
- Use
clap. Replace the hand-written parser with#[derive(Parser)]and get--help,--version, and validation for free. - Regular expressions. Add the
regexcrate and a-Eflag. Compile theRegexonce, outside the loop. - Streaming.
read_to_stringloads the whole file. Switch toBufReader::lines()so a 10 GB log does not need 10 GB of memory. How does that changeMatch<'a>? - Standard input. When no file is given, or the file is
-, read from stdin. Abstract over the source withBox<dyn BufRead>or a genericR: BufRead. - Recursive search. Add
-rwith thewalkdircrate (orignore, which respects.gitignore). - Colour. Highlight the match when stdout is a terminal (
std::io::IsTerminal). - Benchmark against
grepandripgrepon a large file. Then read how ripgrep achieves its speed.
Level 2 checkpoint
You are ready for Level 3 if you can:
- Write a generic function with trait bounds and explain what monomorphization does to it.
- Explain what
'ameans in a signature and when elision supplies it. - Choose between
Box,Rc,RefCelland plain ownership for a given data structure. - Express a data transformation as an iterator chain.
- Design an error enum, implement
Fromfor its sources, and test both the success and failure paths.
Check your understanding
Pick an answer to see the explanation.
1.Why put the search logic in
lib.rsand keepmain.rssmall?2.Where should a well-behaved CLI print error messages?
3.Why does
searchreturnVec<Match<'a>>borrowing from the contents instead of owningStrings?