Skip to content

Commit

Permalink
Merge pull request #5873 from epage/ignore
Browse files Browse the repository at this point in the history
fix(parser): Set correct source on ignore-errors with did-you-mean
  • Loading branch information
epage authored Jan 7, 2025
2 parents 1d5c679 + c721b6c commit 9accea8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
8 changes: 5 additions & 3 deletions clap_builder/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1571,9 +1571,11 @@ impl Parser<'_> {
);

// Add the arg to the matches to build a proper usage string
if let Some((name, _)) = did_you_mean.as_ref() {
if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) {
self.start_custom_arg(matcher, arg, ValueSource::CommandLine);
if !self.cmd.is_ignore_errors_set() {
if let Some((name, _)) = did_you_mean.as_ref() {
if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) {
self.start_custom_arg(matcher, arg, ValueSource::CommandLine);
}
}
}
let did_you_mean = did_you_mean.map(|(arg, cmd)| (format!("--{arg}"), cmd));
Expand Down
40 changes: 39 additions & 1 deletion tests/builder/ignore_errors.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use clap::{arg, Arg, ArgAction, Command};
use clap::{arg, error::ErrorKind, parser::ValueSource, Arg, ArgAction, Command};
use snapbox::str;

use super::utils;

Expand Down Expand Up @@ -116,6 +117,43 @@ fn unexpected_argument() {
assert_eq!(m.get_one::<bool>("unset-flag").copied(), Some(false));
}

#[test]
#[cfg(feature = "error-context")]
fn did_you_mean() {
let mut cmd = Command::new("cmd").arg(arg!(--"ignore-immutable"));

// Verify we are in a "did you mean" error
let r = cmd.try_get_matches_from_mut(vec!["cmd", "--ig"]);
assert!(r.is_err());
let err = r.unwrap_err();
utils::assert_error(
err,
ErrorKind::UnknownArgument,
str![[r#"
error: unexpected argument '--ig' found
tip: a similar argument exists: '--ignore-immutable'
Usage: cmd --ignore-immutable
For more information, try '--help'.
"#]],
true,
);

let r = cmd
.ignore_errors(true)
.try_get_matches_from(vec!["cmd", "--ig"]);
assert!(r.is_ok(), "unexpected error: {r:?}");
let m = r.unwrap();
assert!(m.contains_id("ignore-immutable"), "{m:#?}");
assert_eq!(
m.value_source("ignore-immutable"),
Some(ValueSource::DefaultValue)
);
}

#[test]
fn subcommand() {
let cmd = Command::new("test")
Expand Down

0 comments on commit 9accea8

Please sign in to comment.