command-line-rust icon indicating copy to clipboard operation
command-line-rust copied to clipboard

Chapter 2 "echor": breaking changes in clap 3 & 4 need adjustment

Open UweSauter opened this issue 1 year ago • 0 comments

For everyone trying to follow along using a current (4.2.7) version of clap here's a working solution:

use clap::{Arg, ArgAction, Command};

fn main() {
    let matches = Command::new("echor")
        .version("0.1.0")
        .author("author")
        .about("echo in Rust")
        .arg(
            Arg::new("text")
                .value_name("TEXT")
                .help("input text")
                .required(true)
                .action(ArgAction::Append),
        )
        .arg(
            Arg::new("omit newline")
                .short('n')
                .help("Don't print newline character")
                .action(ArgAction::SetTrue),
        )
        .get_matches();
    let text: Vec<&str> = matches
        .get_many("text")
        .unwrap()
        .map(String::as_str)
        .collect();
    let omit_newline = matches.get_flag("omit newline");
    let ending = if omit_newline { "" } else { "\n" };
    print!("{}{}", text.join(" "), ending);
}

There have been some breaking changes in clap since 2.33 that required some work to get right. Most challenging was to collect the arguments into text.

UweSauter avatar May 13 '23 22:05 UweSauter