Sub topic 13
Keeping parsing separate from logic
This chapter assumes you know how to derive a Parser struct, use Subcommand enums, and return an ExitCode from main. It shows how to split a clap program so the parsing layer is thin and the logic can be tested without a terminal.
Why separate them
Cli::parse() reads the process arguments and can exit the program. Code that calls it directly is hard to test. Logic that takes &Cli as input also depends on clap types it doesn't need.
A common layout has three layers:
mainparses arguments and chooses the exit code.- A
runfunction takes the parsed values and returnsResult. - Plain functions do the real work and know nothing about clap.
A worked example
The program below keeps the clap types in main, dispatches in run, and puts the counting logic in a function that takes plain strings.
use clap::{Parser, Subcommand};
use std::process::ExitCode;
#[derive(Parser)]
#[command(version, about = "Text statistics")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Count words in the given text
Words { text: String },
/// Repeat the text a number of times
Repeat {
text: String,
#[arg(short, long, default_value_t = 2)]
times: usize,
},
}
fn count_words(text: &str) -> usize {
text.split_whitespace().count()
}
fn repeat(text: &str, times: usize) -> Result<String, String> {
if times == 0 {
return Err("times must be at least 1".into());
}
Ok(vec![text; times].join(" "))
}
fn run(cli: Cli) -> Result<String, String> {
match cli.command {
Commands::Words { text } => Ok(count_words(&text).to_string()),
Commands::Repeat { text, times } => repeat(&text, times),
}
}
fn main() -> ExitCode {
let cli = Cli::parse();
match run(cli) {
Ok(output) => {
println!("{output}");
ExitCode::SUCCESS
}
Err(msg) => {
eprintln!("error: {msg}");
ExitCode::FAILURE
}
}
}count_words and repeat take &str and usize. You can call them from a unit test with no Cli value at all. run is the only function that matches on clap's enum, and only main touches the process.
Rules that keep the split clean
- Return output as a value from
runinstead of printing deep inside logic. Printing is then a single decision inmain. - Send errors to stderr with
eprintln!and normal output to stdout, so pipes still work. - Convert clap's types to your own at the boundary when the logic would otherwise need
Cli. APathBufand au32need no conversion. A wholeClistruct usually does. - Let
runtakeCliby value if it moves fields out, or&Cliif it only reads them.
Common mistakes
- Calling
std::process::exitinside logic functions. The test process exits too, and destructors do not run. - Calling
Cli::parse()outsidemain. Tests then parse the test runner's own arguments. - Using
unwrapon logic errors that a user can trigger. ReturnErrand letmainreport it.
Exercise
In the example, why does repeat return Result<String, String> instead of printing and calling std::process::exit(1) when times is 0?
Show answer
Returning a Result lets the caller decide what to do. main prints the message to stderr and returns ExitCode::FAILURE, and a unit test can assert on the Err value. Calling exit inside repeat would end the test process and mix error handling into the logic.