Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
UweSauter opened this issue May 13, 2023 · 0 comments
Open

Comments

@UweSauter
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant