Sub topic 13
Keeping parsing separate from logic
This chapter assumes you can define a CLI with #[derive(Parser)], write a Subcommand enum, and return an ExitCode from main. Those topics come from the earlier chapters on subcommands and error handling.
A first clap program usually puts everything in main: parse, read files, compute, print. That works until you want to test the computation. Cli::parse() reads the real process arguments and exits on bad input, so any code that depends on it is awkward to call from a test. The fix is a layout where clap sits at the edge of the program and the logic never sees it.
The three layers
Split the program into three parts:
- Parsing. The
Clistruct andCli::parse(). This layer turns text into typed values. - Dispatch. A
runfunction that takes the parsedCli, picks what to do, and returns aResult. - Logic. Plain functions that take ordinary Rust values such as
&str,bool, andu16, and return values or errors. They never mention clap.
Only main and run know that clap exists. The logic layer can be tested with ordinary function calls, and you could later reuse it from a different front end.
A single-file example
This program prints the lines of a file that match a filter. It is complete and runs with cargo run -- notes.txt -f todo -i.
use clap::Parser;
use std::fmt;
use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
/// File to search
path: PathBuf,
/// Only print lines containing this text
#[arg(short, long)]
filter: Option<String>,
/// Ignore case when matching
#[arg(short, long)]
ignore_case: bool,
}
#[derive(Debug)]
enum AppError {
Read { path: PathBuf, source: std::io::Error },
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::Read { path, source } => {
write!(f, "cannot read {}: {source}", path.display())
}
}
}
}
impl std::error::Error for AppError {}
/// Pure logic: no clap, no files, no printing.
fn select_lines<'a>(text: &'a str, filter: Option<&str>, ignore_case: bool) -> Vec<&'a str> {
text.lines()
.filter(|line| match filter {
None => true,
Some(needle) if ignore_case => line.to_lowercase().contains(&needle.to_lowercase()),
Some(needle) => line.contains(needle),
})
.collect()
}
fn run(cli: &Cli) -> Result<(), AppError> {
let text = fs::read_to_string(&cli.path).map_err(|source| AppError::Read {
path: cli.path.clone(),
source,
})?;
for line in select_lines(&text, cli.filter.as_deref(), cli.ignore_case) {
println!("{line}");
}
Ok(())
}
fn main() -> ExitCode {
let cli = Cli::parse();
match run(&cli) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_filter_keeps_every_line() {
assert_eq!(select_lines("a\nb", None, false), vec!["a", "b"]);
}
#[test]
fn filter_can_ignore_case() {
let text = "TODO: write\ndone";
assert_eq!(select_lines(text, Some("todo"), true), vec!["TODO: write"]);
assert!(select_lines(text, Some("todo"), false).is_empty());
}
}Some details in this layout matter:
select_linestakesOption<&str>, not&Option<String>. The call site converts withas_deref(), so the logic is not tied to how clap stores the value.- The tests never construct a
Cliand never touch the file system. AppErrorhas aDisplayimplementation, somaincan print any error the same way. A parse failure is a different case: clap prints it and exits with status 2 beforerunis reached.runreturnsResultand never callsstd::process::exit. Onlymaindecides the exit code. Exiting deep inside logic skips destructors and makes the function impossible to test.
Dispatching subcommands
With subcommands, run becomes a match that unpacks each variant and calls one handler per command. The handlers take plain arguments, not the whole Cli or the enum variant.
use clap::{Parser, Subcommand};
use std::process::ExitCode;
#[derive(Parser)]
#[command(version, about = "A tiny task manager")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Add a task
Add { title: String },
/// List tasks
List {
#[arg(short, long)]
all: bool,
},
}
fn add_task(title: &str) -> Result<String, String> {
if title.trim().is_empty() {
return Err("title must not be empty".into());
}
Ok(format!("added {title:?}"))
}
fn list_tasks(all: bool) -> String {
if all { "all tasks".into() } else { "open tasks".into() }
}
fn run(cli: Cli) -> Result<String, String> {
match cli.command {
Commands::Add { title } => add_task(&title),
Commands::List { all } => Ok(list_tasks(all)),
}
}
fn main() -> ExitCode {
match run(Cli::parse()) {
Ok(message) => {
println!("{message}");
ExitCode::SUCCESS
}
Err(message) => {
eprintln!("error: {message}");
ExitCode::FAILURE
}
}
}Here the logic functions return a String instead of printing. The run function returns a value and main prints it. This makes the output testable with assert_eq!. For large outputs, take a &mut impl std::io::Write instead, and pass std::io::stdout() in main and a Vec<u8> in tests.
The empty-title check in add_task is business logic, so it lives in the logic layer. A check that only concerns the shape of the input, such as "port is between 1 and 65535", belongs in clap through value_parser, where it produces a standard usage error.
Splitting into a library and a binary
When the logic grows, move it out of main.rs. Cargo treats src/lib.rs and src/main.rs in the same package as a library crate and a binary crate.
src/
lib.rs logic functions and AppError (no clap)
main.rs Cli, Commands, run, main
tests/
logic.rs integration tests that call the libraryIn main.rs, import the library by the package name, for example use mytool::select_lines;. Integration tests in tests/ can then call the library the way another crate would. If the library has no clap dependency in its public API, a different front end can reuse it.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `Cli::parse()` inside logic functions | Tests exit the process or read the test runner's arguments | Parse once in `main` and pass values down |
| Passing `&Cli` to every function | Logic is coupled to every argument, and tests must build a `Cli` | Pass only the fields each function needs |
| Calling `std::process::exit` from helpers | Skips destructors and cannot be tested | Return `Err` and let `main` choose the exit code |
| Printing from logic functions | Output can only be checked by capturing stdout | Return a value or accept a writer |
| Re-checking argument shape in logic | The same rule is written twice and can drift | Keep shape rules in clap and meaning rules in logic |
Decision criteria
Keep everything in one file when the tool has one command and fewer than about fifty lines of logic. Splitting early adds files without adding clarity. Move to the three-layer layout in a single file once you want unit tests for the logic. Move to a library and binary split when the logic needs integration tests, when another crate or binary will reuse it, or when main.rs grows hard to scan.
Exercise
In the task manager example, you want to add a --limit <N> option to list that caps how many tasks are shown. Which parts of the program change, and which function signature should the logic function have so that it can be tested without clap?
Show answer
Add limit: Option<usize> to the Commands::List variant, with #[arg(short, long)]. Update the Commands::List arm of run to destructure all and limit and pass them on. Change the logic function to fn list_tasks(all: bool, limit: Option<usize>) -> String. It takes plain values, so a test can call list_tasks(true, Some(3)) directly. main and Cli do not change. If a limit of zero should be rejected, enforce the range with value_parser in clap, because that is a rule about the shape of the input.