docs: Provide custom version flag example

This commit is contained in:
Ed Page 2023-10-04 16:22:46 -05:00
parent 39f5e807af
commit e74864f88a

View file

@ -1244,12 +1244,41 @@ impl Command {
/// # use clap_builder as clap; /// # use clap_builder as clap;
/// # use clap::{Command, error::ErrorKind}; /// # use clap::{Command, error::ErrorKind};
/// let res = Command::new("myprog") /// let res = Command::new("myprog")
/// .version("1.0.0")
/// .disable_version_flag(true) /// .disable_version_flag(true)
/// .try_get_matches_from(vec![ /// .try_get_matches_from(vec![
/// "myprog", "--version"
/// ]);
/// assert!(res.is_err());
/// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
/// ```
///
/// You can create a custom version flag with [`ArgAction::Version`]
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, Arg, ArgAction, error::ErrorKind};
/// let mut cmd = Command::new("myprog")
/// .version("1.0.0")
/// // Remove the `-V` short flag
/// .disable_version_flag(true)
/// .arg(
/// Arg::new("version")
/// .long("version")
/// .action(ArgAction::Version)
/// .help("Print version")
/// );
///
/// let res = cmd.try_get_matches_from_mut(vec![
/// "myprog", "-V" /// "myprog", "-V"
/// ]); /// ]);
/// assert!(res.is_err()); /// assert!(res.is_err());
/// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
///
/// let res = cmd.try_get_matches_from_mut(vec![
/// "myprog", "--version"
/// ]);
/// assert!(res.is_err());
/// assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayVersion);
/// ``` /// ```
#[inline] #[inline]
pub fn disable_version_flag(self, yes: bool) -> Self { pub fn disable_version_flag(self, yes: bool) -> Self {