rustcommand-line-interfaceclap

How to make clap derive not convert underscores to hyphens in option names


With Clap's derive macro:

/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// Name of the person to greet
    #[arg(short, long)]
    full_name: String,
}

This will create a command line argument --full-name. Is there any way to make it use --full_name instead? Ideally with a global option rather than having to set it for each option individually?


Solution

  • You can either override arg name by providing #[arg(long("custom_name")]

    /// Simple program to greet a person
    #[derive(Parser, Debug)]
    #[command(author, version, about, long_about = None)]
    struct Args {
        /// Name of the person to greet
        #[arg(short, long("full_name"))]
        full_name: String,
    }
    

    or if you want to use snake_case naming for all args you can change default renaming convention by setting #[command(rename_all = "snake_case")]

    /// Simple program to greet a person
    #[derive(Parser, Debug)]
    #[command(author, version, about, long_about = None, rename_all = "snake_case")]
    struct Args {
        /// Name of the person to greet
        #[arg(short, long)]
        full_name: String,
    }