A real command-line interface
Parse arguments with clap, read files or standard input line by line through BufRead, and report failures on stderr with meaningful exit codes.
- lesson
- 07 of 08
- read
- 15 min
tally computes the right numbers behind a makeshift interface: its only flag is checked by hand, and its input has to be a file. This lesson replaces the argument handling with clap and reads input line by line, from files or from standard input. It then settles how the program reports failure, so that a script calling tally can rely on its exit status and its output streams.
Arguments with clap
Argument parsing comes from a crate:
cargo add clap --features deriveThis adds clap = { version = "4.6.10", features = ["derive"] } to Cargo.toml. With its derive API, clap generates an argument parser from a struct. Below the four mod lines, the top of main.rs becomes:
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::PathBuf;
use std::process::ExitCode;
use clap::{Parser, ValueEnum};
use entry::parse_line;
use error::TallyError;
use output::{Json, Render, Text};
use summary::Summary;
/// Summarize web server access logs
#[derive(Parser)]
#[command(version, about)]
struct Cli {
/// Log files to read; standard input when none are given
files: Vec<PathBuf>,
/// Output format
#[arg(short, long, value_enum, default_value_t = Format::Text)]
format: Format,
/// How many paths and clients to list
#[arg(short = 'n', long, default_value_t = 5)]
top: usize,
/// Fail on the first malformed line instead of skipping it
#[arg(long)]
strict: bool,
}
#[derive(Clone, Copy, ValueEnum)]
enum Format {
Text,
Json,
}Each field is one argument, and its type decides how the argument is parsed:
| Field type | Accepts |
|---|---|
Vec<PathBuf> |
any number of values |
Format, which derives ValueEnum |
one of the variant names, in lowercase |
usize |
a non-negative integer |
bool |
nothing: the flag is either present or absent |
A field with no #[arg] attribute is positional. #[arg(short, long)] turns a field into an option, here -f and --format, named after the field. The /// doc comments become the help text, and #[command(version, about)] takes the version number from Cargo.toml.
PathBuf is the owned type for file system paths. Paths are not Strings, because the operating system does not promise that they are valid UTF-8, and path.display() gives a printable form.
cargo run -q -- --helpSummarize web server access logs
Usage: tally [OPTIONS] [FILES]...
Arguments:
[FILES]... Log files to read; standard input when none are given
Options:
-f, --format <FORMAT> Output format [default: text] [possible values: text, json]
-n, --top <TOP> How many paths and clients to list [default: 5]
--strict Fail on the first malformed line instead of skipping it
-h, --help Print help
-V, --version Print versionValidation and its error messages come with the parser:
cargo run -q -- --format yaml access.log; echo "exit $?"error: invalid value 'yaml' for '--format <FORMAT>'
[possible values: text, json]
For more information, try '--help'.
exit 2Reading line by line
fs::read_to_string needs a path and loads the whole input into memory, and neither suits standard input. What a file and standard input have in common is the BufRead trait, implemented by a BufReader wrapped around a file and by a locked standard input. The reading code is written against the trait:
fn read_log(
mut reader: impl BufRead,
name: &str,
strict: bool,
summary: &mut Summary,
) -> Result<(), TallyError> {
let mut line = String::new();
let mut number = 0;
loop {
line.clear();
let read = reader
.read_line(&mut line)
.map_err(|source| TallyError::Read {
name: name.to_string(),
source,
})?;
if read == 0 {
return Ok(());
}
number += 1;
match parse_line(line.trim_end()) {
Ok(entry) => summary.record(&entry),
Err(source) if strict => {
return Err(TallyError::Parse {
name: name.to_string(),
line: number,
source,
});
}
Err(err) => {
eprintln!("{name}:{number}: {err}");
summary.malformed += 1;
}
}
}
}read_line appends the next line, newline included, to the string it is given. It returns the number of bytes read, which is zero at the end of the input. One String serves for the whole input: clear empties it and keeps its capacity. reader.lines() would be shorter, and it allocates a new String for every line. Lesson 8 measures what that costs.
Reusing the buffer works because of a decision in lesson 5. entry borrows from line, and line.clear() needs exclusive access. The borrow checker allows it because the entry is gone by the end of each iteration, and the summary kept owned copies of the few strings it needed. Memory use no longer grows with the size of the log, only with the number of distinct paths and clients.
The second match arm has a guard, if strict: the arm applies only when the pattern matches and the condition holds. This is the --strict flag promised in lesson 4.
read_log is generic over the reader, the other column of the table in the last lesson. run calls it with two reader types, so the compiler produces two specialized copies of the loop:
fn run(cli: &Cli) -> Result<(), TallyError> {
let mut summary = Summary::new();
if cli.files.is_empty() {
read_log(io::stdin().lock(), "<stdin>", cli.strict, &mut summary)?;
}
for path in &cli.files {
let name = path.display().to_string();
let file = File::open(path).map_err(|source| TallyError::Read {
name: name.clone(),
source,
})?;
read_log(BufReader::new(file), &name, cli.strict, &mut summary)?;
}
let renderer: Box<dyn Render> = match cli.format {
Format::Text => Box::new(Text),
Format::Json => Box::new(Json),
};
let report = summary.report(cli.top);
let mut out = io::stdout().lock();
renderer.render(&report, &mut out)?;
Ok(())
}The renderer function in output.rs can be deleted. The format is now an enum that clap validates, and the match in run maps it to a trait object.
Errors that name their source
Opening a file and reading a line both fail with a bare io::Error. In read_log and in run, map_err wraps it in a variant that carries the name of the input, which the From impl of lesson 4 had no way to do:
use std::error::Error;
use std::fmt;
use std::io;
use crate::entry::ParseError;
#[derive(Debug)]
pub enum TallyError {
Read {
name: String,
source: io::Error,
},
Parse {
name: String,
line: usize,
source: ParseError,
},
Io(io::Error),
}
impl fmt::Display for TallyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TallyError::Read { name, source } => write!(f, "{name}: {source}"),
TallyError::Parse { name, line, source } => write!(f, "{name}:{line}: {source}"),
TallyError::Io(err) => write!(f, "{err}"),
}
}
}
impl Error for TallyError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
TallyError::Read { source, .. } => Some(source),
TallyError::Parse { source, .. } => Some(source),
TallyError::Io(err) => Some(err),
}
}
}
impl From<io::Error> for TallyError {
fn from(err: io::Error) -> Self {
TallyError::Io(err)
}
}Parse is what strict mode returns; it keeps the ParseError as its source. Io and its From impl stay for the one place that has no context to add, writing the report. NoInput is gone, because no arguments now means standard input.
Exit codes and standard error
main is left with two jobs, parsing the arguments and turning the result of run into an exit status:
fn main() -> ExitCode {
let cli = Cli::parse();
match run(&cli) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("tally: {err}");
ExitCode::FAILURE
}
}
}Cli::parse() handles its own failures: it prints a usage error and exits with status 2 when the arguments are invalid, and exits with 0 after --help. main returns an ExitCode where lesson 4 called process::exit. exit ends the process on the spot without running destructors; returning from main lets every value be dropped in order first.
The contract with the caller is now this:
| Status | Meaning |
|---|---|
| 0 | A report was printed. Malformed lines, if any, were skipped and listed on standard error. |
| 1 | An input could not be read, or --strict met a malformed line. |
| 2 | The command line was invalid. |
cargo run -q -- --strict access.log; echo "exit $?"tally: access.log:8: missing request
exit 1cargo run -q -- nope.log; echo "exit $?"tally: nope.log: No such file or directory (os error 2)
exit 1Standard output carries the report and nothing else. Warnings go to standard error, so the report can be piped or redirected while they stay on the terminal:
cat access.log | cargo run -q -- -n 2<stdin>:8: missing request
<stdin>:15: missing path
requests 16
malformed 2
bytes 152631
status
2xx 9
3xx 2
4xx 3
5xx 2
top paths
4 /
3 /api/orders
top clients
7 203.0.113.7
4 198.51.100.23A closed pipe is not a failure
One error deserves separate treatment. Generate a log with many distinct paths, then ask for a long report and cut it off with head:
seq 100000 | awk '{ print "203.0.113.7 - - [28/Nov/2026:09:12:01 +0000] \"GET /item/" $1 " HTTP/1.1\" 200 512" }' > many.log
cargo run -q -- -n 100000 many.log | head -n 1requests 100000
tally: Broken pipe (os error 32)head exits after one line, so the next write to the pipe fails. tally reports that as an error, with status 1, although its reader only asked it to stop. Because the error is a value, main can look at it before deciding. Add one arm:
Ok(()) => ExitCode::SUCCESS,
// A reader such as `head` closed the pipe early. That is not a failure.
Err(TallyError::Io(err)) if err.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
Err(err) => {This is the match on a variant that lesson 4 kept the enum for. The same command now prints the first line and exits with status 0.
The program is feature-complete. The last lesson protects its behavior with tests and builds it for release.
Exercises
- Accept
-as a file name that means standard input, so thatcat access.log | cargo run -q -- access.log -reports 32 requests. The two branches produce readers of different types, which is a job forBox<dyn BufRead>. - A line that is not valid UTF-8 currently ends the run with
stream did not contain valid UTF-8. Read bytes instead, withread_until(b'\n', &mut buffer)on aVec<u8>, and convert each line withString::from_utf8_lossy. Make a test file withprintf '203.0.113.7 - - [28/Nov/2026:09:20:00 +0000] "GET /caf\xe9 HTTP/1.1" 404 153\n' > latin1.log. The report for it should show one request, with a path of/caffollowed by the replacement character. - Add a
--quietflag, with-qas its short form, that suppresses the per-line warnings. Themalformedcount in the report should stay the same.