Skip to content

Commit

Permalink
fix(builder): UnknownValueParser shouldn't error on flag absense
Browse files Browse the repository at this point in the history
Fixes #5079
  • Loading branch information
epage committed Aug 18, 2023
1 parent 6720240 commit 56135f3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 25 deletions.
65 changes: 41 additions & 24 deletions clap_builder/src/builder/value_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2225,35 +2225,52 @@ impl TypedValueParser for UnknownArgumentValueParser {
type Value = String;

fn parse_ref(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, crate::Error> {
TypedValueParser::parse_ref_(self, cmd, arg, value, ValueSource::CommandLine)
}

fn parse_ref_(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
_value: &std::ffi::OsStr,
source: ValueSource,
) -> Result<Self::Value, crate::Error> {
let arg = match arg {
Some(arg) => arg.to_string(),
None => "..".to_owned(),
};
let err = crate::Error::unknown_argument(
cmd,
arg,
self.arg.as_ref().map(|s| (s.as_str().to_owned(), None)),
false,
crate::output::Usage::new(cmd).create_usage_with_title(&[]),
);
#[cfg(feature = "error-context")]
let err = {
debug_assert_eq!(
err.get(crate::error::ContextKind::Suggested),
None,
"Assuming `Error::unknown_argument` doesn't apply any `Suggested` so we can without caution"
);
err.insert_context_unchecked(
crate::error::ContextKind::Suggested,
crate::error::ContextValue::StyledStrs(self.suggestions.clone()),
)
};
Err(err)
match source {
ValueSource::DefaultValue => {
TypedValueParser::parse_ref_(&StringValueParser::new(), cmd, arg, _value, source)
}
ValueSource::EnvVariable | ValueSource::CommandLine => {
let arg = match arg {
Some(arg) => arg.to_string(),
None => "..".to_owned(),
};
let err = crate::Error::unknown_argument(
cmd,
arg,
self.arg.as_ref().map(|s| (s.as_str().to_owned(), None)),
false,
crate::output::Usage::new(cmd).create_usage_with_title(&[]),
);
#[cfg(feature = "error-context")]
let err = {
debug_assert_eq!(
err.get(crate::error::ContextKind::Suggested),
None,
"Assuming `Error::unknown_argument` doesn't apply any `Suggested` so we can without caution"
);
err.insert_context_unchecked(
crate::error::ContextKind::Suggested,
crate::error::ContextValue::StyledStrs(self.suggestions.clone()),
)
};
Err(err)
}
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/builder/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ fn unknown_argument_flag() {
]);

let res = cmd.clone().try_get_matches_from(["test"]);
assert!(res.is_err());
assert!(res.is_ok());

let res = cmd.try_get_matches_from(["test", "--ignored"]);
assert!(res.is_err());
Expand Down

0 comments on commit 56135f3

Please sign in to comment.