Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions lib/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,40 @@ fn parse_partial_with_env(
}
}

if out
.flag_awaiting_value
.last()
.is_some_and(|flag| flag.allow_hyphen_values)
{
while let Some(flag) = out.flag_awaiting_value.pop() {
let arg = flag.arg.as_ref().unwrap();
if validate_choices(
spec,
&out.cmd,
&mut out.errors,
ChoiceTarget::option(&flag),
&w,
arg.choices.as_ref(),
custom_env,
)? {
return Ok(out);
}
if flag.var {
let arr = out
.flags
.entry(flag)
.or_insert_with(|| ParseValue::MultiString(vec![]))
.try_as_multi_string_mut()
.unwrap();
arr.push(w);
} else {
out.flags.insert(flag, ParseValue::String(w));
}
w = "".to_string();
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Outdated
continue;
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Outdated

// long flags
if enable_flags && w.starts_with("--") {
grouped_flag = false;
Expand Down Expand Up @@ -1020,6 +1054,22 @@ mod tests {
panic!("expected first parsed value to be ParseValue::String");
}

fn flag_string_value<'a>(parsed: &'a ParseOutput, name: &str) -> &'a str {
let flag = parsed
.flags
.keys()
.find(|flag| flag.name == name)
.unwrap_or_else(|| panic!("expected flag {name}"));
let value = parsed
.flags
.get(flag)
.unwrap_or_else(|| panic!("expected value for flag {name}"));
match value {
ParseValue::String(value) => value,
_ => panic!("expected flag {name} to be ParseValue::String"),
}
}

fn assert_parse_err(result: Result<ParseOutput, miette::Error>, expected: &str) {
let err = result.expect_err("expected parser error");
assert_eq!(format!("{err}"), expected);
Expand Down Expand Up @@ -2688,4 +2738,48 @@ mod tests {
env3.get("usage_other_args"),
);
}

#[test]
fn test_allow_hyphen_values_consumes_short_flag_collision() {
let spec = r#"
flag "-d --working-dir <DIR>"
flag "-a --args <ARGS>" allow_hyphen_values=#true
"#
.parse::<Spec>()
.unwrap();

let parsed = parse(&spec, &input(&["test", "-a", "-destroy"])).unwrap();

assert_eq!(parsed.flags.len(), 1);
assert_eq!(flag_string_value(&parsed, "args"), "-destroy");
}

#[test]
fn test_allow_hyphen_values_consumes_embedded_long_value() {
let spec = r#"
flag "-d --working-dir <DIR>"
flag "-a --args <ARGS>" allow_hyphen_values=#true
"#
.parse::<Spec>()
.unwrap();

let parsed = parse(&spec, &input(&["test", "--args=-destroy"])).unwrap();

assert_eq!(parsed.flags.len(), 1);
assert_eq!(flag_string_value(&parsed, "args"), "-destroy");
}

#[test]
fn test_hyphen_values_still_default_to_short_flag_parsing() {
let spec = r#"
flag "-d --working-dir <DIR>"
flag "-a --args <ARGS>"
"#
.parse::<Spec>()
.unwrap();

let parsed = parse(&spec, &input(&["test", "-a", "-destroy"])).unwrap();

assert_eq!(flag_string_value(&parsed, "working-dir"), "estroy");
}
}
6 changes: 6 additions & 0 deletions lib/src/spec/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,12 @@ impl SpecFlagBuilder {
self
}

/// Allow this flag's value to start with `-`
pub fn allow_hyphen_values(mut self, allow: bool) -> Self {
self.inner.allow_hyphen_values = allow;
self
}

/// Set the argument spec for flags that take values
pub fn arg(mut self, arg: SpecArg) -> Self {
self.inner.arg = Some(arg);
Expand Down
9 changes: 9 additions & 0 deletions lib/src/spec/flag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ pub struct SpecFlag {
/// Argument specification if this flag takes a value
#[serde(skip_serializing_if = "Option::is_none")]
pub arg: Option<SpecArg>,
/// Whether this flag's value may start with `-`
#[serde(skip_serializing_if = "is_false")]
pub allow_hyphen_values: bool,
/// Default value(s) if the flag is not provided
#[serde(skip_serializing_if = "Vec::is_empty")]
pub default: Vec<String>,
Expand Down Expand Up @@ -115,6 +118,7 @@ impl SpecFlag {
}
"global" => flag.global = v.ensure_bool()?,
"count" => flag.count = v.ensure_bool()?,
"allow_hyphen_values" => flag.allow_hyphen_values = v.ensure_bool()?,
"default" => {
// Support both string and boolean defaults
let default_value = match v.value.as_bool() {
Expand Down Expand Up @@ -152,6 +156,7 @@ impl SpecFlag {
}
"global" => flag.global = child.arg(0)?.ensure_bool()?,
"count" => flag.count = child.arg(0)?.ensure_bool()?,
"allow_hyphen_values" => flag.allow_hyphen_values = child.arg(0)?.ensure_bool()?,
"default" => {
// Support both single value and multiple values
// default "bar" -> vec!["bar"]
Expand Down Expand Up @@ -261,6 +266,9 @@ impl From<&SpecFlag> for KdlNode {
if flag.count {
node.push(KdlEntry::new_prop("count", true));
}
if flag.allow_hyphen_values {
node.push(KdlEntry::new_prop("allow_hyphen_values", true));
}
if let Some(negate) = &flag.negate {
node.push(string_entry(Some("negate"), negate));
}
Expand Down Expand Up @@ -411,6 +419,7 @@ impl From<&clap::Arg> for SpecFlag {
hide,
global: c.is_global_set(),
arg,
allow_hyphen_values: c.is_allow_hyphen_values_set(),
count: matches!(c.get_action(), clap::ArgAction::Count),
default,
deprecated: None,
Expand Down
Loading