Search code examples
rustcommand-line-interfacerust-cratesclap

Is there a way to make clap treat -? the same way as -h?


The clap crate implements built-in behaviour for the -h option, but it doesn't seem to do the same for -?. Is there a way to tell it to do so?


Solution

  • I had opened an issue at the clap repository. The author / main contributor has answered there. Here is a copy of the code, which answers the question:

    extern crate clap;
    
    use std::env;
    use std::process;
    
    use clap::{App, Arg};
    
    fn main() {
        // We build the App instance and save it, so we can
        // use it later if needed
        let mut app = App::new("prog").arg(
            Arg::with_name("help")
                .short("?")
                .help("Also prints the help message"),
        );
    
        // We call this method which will do all the
        //parsing, but not consume our App instance
        let res = app.get_matches_from_safe_borrow(env::args_os());
    
        // This calls all the normal clap error messages
        // if one should exist
        let matches = res.unwrap_or_else(|e| e.exit());
    
        // Now we check for ?
        if matches.is_present("help") {
            let _ = app.print_help();
            println!(""); // adds a newline
            process::exit(0);
        }
    
        // Now we can use matches like normal...
    }