Skip to content

Commit

Permalink
feat: add flags method to Args
Browse files Browse the repository at this point in the history
This can simplify the boilerplate of returning, and advancing, the Args
iterator, returning only when there is matching flags.
  • Loading branch information
RoloEdits committed Dec 18, 2024
1 parent 9b9b50b commit 153b656
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
18 changes: 18 additions & 0 deletions helix-core/src/shellwords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,24 @@ impl<'a> Args<'a> {
count: 0,
}
}

pub fn flags<'f, F: Iterator<Item = &'f str>>(&mut self, mut flags: F) -> Option<&'a str> {
if self.is_empty() {
return None;
}

let mut args = self.peekable();

if let Some(arg) = args.peek() {
if flags.any(|f| f == arg.trim_start_matches('-').trim_start_matches("--")) {
return self
.next()
.map(|flag| flag.trim_start_matches('-').trim_start_matches("--"));
}
}

None
}
}

impl<'a> Iterator for Args<'a> {
Expand Down
17 changes: 8 additions & 9 deletions helix-term/src/commands/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2131,16 +2131,15 @@ fn sort(
return Ok(());
}

if let Some(flag) = args.next() {
let flag = flag.trim_start_matches("--").trim_start_matches('-');
let flags = flags
.iter()
.map(|flag| flag.long)
.chain(flags.iter().filter_map(|flag| flag.short));

if flags
.iter()
.any(|x| x.long == flag || x.short == Some(flag))
{
sort_impl(cx, true);
} else {
bail!("There is no flag `--{flag}` on sort");
if let Some(flag) = args.flags(flags) {
match flag {
"reverse" | "r" => sort_impl(cx, true),
_ => bail!("unhandle command flag `{flag}`, implementation failed to cover all flags."),
}
} else {
sort_impl(cx, false);
Expand Down

0 comments on commit 153b656

Please sign in to comment.