Skip to content

Commit

Permalink
feat(complete): Support allow_hyphen_values in native completions
Browse files Browse the repository at this point in the history
  • Loading branch information
mart-mihkel committed Aug 25, 2024
1 parent 6c4b930 commit b111717
Showing 1 changed file with 43 additions and 11 deletions.
54 changes: 43 additions & 11 deletions clap_complete/src/engine/complete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ pub fn complete(
} else if arg.is_escape() {
is_escaped = true;
} else if let Some((flag, value)) = arg.to_long() {
if let ParseState::Opt((opt, count)) = current_state {
if opt.is_allow_hyphen_values_set() {
next_state = parse_opt(opt, count);
continue;
}
}

if let Ok(flag) = flag {
let opt = current_cmd.get_arguments().find(|a| {
let longs = a.get_long_and_visible_aliases();
Expand All @@ -69,33 +76,40 @@ pub fn complete(
});
is_find.unwrap_or(false)
});
if opt.map(|o| o.get_action().takes_values()).unwrap_or(false) {
if value.is_none() {
next_state = ParseState::Opt((opt.unwrap(), 1));

if let Some(opt) = opt {
if opt.get_action().takes_values() && value.is_none() {
next_state = ParseState::Opt((opt, 1));
};
} else if pos_allows_hyphen(current_cmd, pos_index) {
(next_state, pos_index) =
parse_positional(current_cmd, pos_index, is_escaped, current_state);
}
}
} else if let Some(short) = arg.to_short() {
if let ParseState::Opt((opt, count)) = current_state {
if opt.is_allow_hyphen_values_set() {
next_state = parse_opt(opt, count);
continue;
}
}

let (_, takes_value_opt, mut short) = parse_shortflags(current_cmd, short);
if let Some(opt) = takes_value_opt {
if short.next_value_os().is_none() {
next_state = ParseState::Opt((opt, 1));
}
} else if pos_allows_hyphen(current_cmd, pos_index) {
(next_state, pos_index) =
parse_positional(current_cmd, pos_index, is_escaped, current_state);
}
} else {
match current_state {
ParseState::ValueDone | ParseState::Pos(..) => {
(next_state, pos_index) =
parse_positional(current_cmd, pos_index, is_escaped, current_state);
}

ParseState::Opt((opt, count)) => {
let range = opt.get_num_args().expect("built");
let max = range.max_values();
if count < max {
next_state = ParseState::Opt((opt, count + 1));
}
}
ParseState::Opt((opt, count)) => next_state = parse_opt(opt, count),
}
}
}
Expand Down Expand Up @@ -546,3 +560,21 @@ fn parse_positional<'a>(
),
}
}

/// Parse optional flag argument. Return new state
fn parse_opt(opt: &clap::Arg, count: usize) -> ParseState<'_> {
let range = opt.get_num_args().expect("built");
let max = range.max_values();
if count < max {
ParseState::Opt((opt, count + 1))
} else {
ParseState::ValueDone
}
}

fn pos_allows_hyphen(cmd: &clap::Command, pos_index: usize) -> bool {
cmd.get_positionals()
.find(|a| a.get_index() == Some(pos_index))
.map(|p| p.is_allow_hyphen_values_set())
.unwrap_or(false)
}

0 comments on commit b111717

Please sign in to comment.