Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dynamic completions filter options #5057

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
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
33 changes: 30 additions & 3 deletions clap_complete/src/dynamic/completer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ use std::ffi::OsString;

use clap_lex::OsStrExt as _;

/// Specifies the number of dashes an argument must already
/// contain to complete short and long options.
#[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub enum ShowOptions {
/// One `-` for short, two `--` for long options.
ExactDash,
/// At least one `-` to show options.
MinOneDash,
/// Always complete options.
Always,
}

/// Shell-specific completions
pub trait Completer {
/// The recommended file name for the registration code
Expand Down Expand Up @@ -31,6 +43,7 @@ pub fn complete(
args: Vec<std::ffi::OsString>,
arg_index: usize,
current_dir: Option<&std::path::Path>,
show_options: ShowOptions,
) -> Result<Vec<std::ffi::OsString>, std::io::Error> {
cmd.build();

Expand All @@ -54,7 +67,14 @@ pub fn complete(
let mut is_escaped = false;
while let Some(arg) = raw_args.next(&mut cursor) {
if cursor == target_cursor {
return complete_arg(&arg, current_cmd, current_dir, pos_index, is_escaped);
return complete_arg(
&arg,
current_cmd,
current_dir,
pos_index,
is_escaped,
show_options,
);
}

debug!("complete::next: Begin parsing '{:?}'", arg.to_value_os(),);
Expand Down Expand Up @@ -90,6 +110,7 @@ fn complete_arg(
current_dir: Option<&std::path::Path>,
pos_index: usize,
is_escaped: bool,
show_options: ShowOptions,
) -> Result<Vec<std::ffi::OsString>, std::io::Error> {
debug!(
"complete_arg: arg={:?}, cmd={:?}, current_dir={:?}, pos_index={}, is_escaped={}",
Expand Down Expand Up @@ -123,7 +144,10 @@ fn complete_arg(
);
}
}
} else if arg.is_escape() || arg.is_stdio() || arg.is_empty() {
} else if arg.is_escape()
|| (show_options >= ShowOptions::MinOneDash && arg.is_stdio())
|| (show_options == ShowOptions::Always && arg.is_empty())
{
// HACK: Assuming knowledge of is_escape / is_stdio
completions.extend(
crate::generator::utils::longs_and_visible_aliases(cmd)
Expand All @@ -132,7 +156,10 @@ fn complete_arg(
);
}

if arg.is_empty() || arg.is_stdio() || arg.is_short() {
if arg.is_stdio()
|| arg.is_short()
|| (arg.is_empty() && show_options == ShowOptions::Always)
{
let dash_or_arg = if arg.is_empty() {
"-".into()
} else {
Expand Down
5 changes: 4 additions & 1 deletion clap_complete/src/dynamic/shells/bash.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use unicode_xid::UnicodeXID as _;

use crate::dynamic::ShowOptions;

/// Bash completions
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Bash;
Expand Down Expand Up @@ -71,7 +73,8 @@ complete -o nospace -o bashdefault -F _clap_complete_NAME BIN
.ok()
.and_then(|i| i.parse().ok());
let ifs: Option<String> = std::env::var("IFS").ok().and_then(|i| i.parse().ok());
let completions = crate::dynamic::complete(cmd, args, index, current_dir)?;
let completions =
crate::dynamic::complete(cmd, args, index, current_dir, ShowOptions::Always)?;

for (i, completion) in completions.iter().enumerate() {
if i != 0 {
Expand Down
41 changes: 41 additions & 0 deletions clap_complete/src/dynamic/shells/fish.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use crate::dynamic::ShowOptions;

/// Fish completions
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Fish;

impl crate::dynamic::Completer for Fish {
fn file_name(&self, name: &str) -> String {
format!("{name}.fish")
}
fn write_registration(
&self,
_name: &str,
bin: &str,
completer: &str,
buf: &mut dyn std::io::Write,
) -> Result<(), std::io::Error> {
let bin = shlex::quote(bin);
let completer = shlex::quote(completer);
writeln!(
buf,
r#"complete -x -c {bin} -a "("'{completer}'" complete --shell fish -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))""#
)
}
fn write_complete(
&self,
cmd: &mut clap::Command,
args: Vec<std::ffi::OsString>,
current_dir: Option<&std::path::Path>,
buf: &mut dyn std::io::Write,
) -> Result<(), std::io::Error> {
let index = args.len() - 1;
let completions =
crate::dynamic::complete(cmd, args, index, current_dir, ShowOptions::ExactDash)?;

for completion in completions {
writeln!(buf, "{}", completion.to_string_lossy())?;
}
Ok(())
}
}
2 changes: 2 additions & 0 deletions clap_complete/src/dynamic/shells/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
//! Shell support

mod bash;
mod fish;
mod shell;

pub use bash::*;
pub use fish::*;
pub use shell::*;

use std::ffi::OsString;
Expand Down
6 changes: 5 additions & 1 deletion clap_complete/src/dynamic/shells/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use clap::ValueEnum;
pub enum Shell {
/// Bourne Again SHell (bash)
Bash,
/// Friendly Interactive SHell (fish)
Fish,
}

impl Display for Shell {
Expand Down Expand Up @@ -37,12 +39,13 @@ impl FromStr for Shell {
// Hand-rolled so it can work even when `derive` feature is disabled
impl ValueEnum for Shell {
fn value_variants<'a>() -> &'a [Self] {
&[Shell::Bash]
&[Shell::Bash, Shell::Fish]
}

fn to_possible_value<'a>(&self) -> Option<PossibleValue> {
Some(match self {
Shell::Bash => PossibleValue::new("bash"),
Shell::Fish => PossibleValue::new("fish"),
})
}
}
Expand All @@ -51,6 +54,7 @@ impl Shell {
fn completer(&self) -> &dyn crate::dynamic::Completer {
match self {
Self::Bash => &super::Bash,
Self::Fish => &super::Fish,
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
complete -x -c exhaustive -a "("'exhaustive'" complete --shell fish -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
set -U fish_greeting ""
set -U fish_autosuggestion_enabled 0
function fish_title
end
function fish_prompt
printf '%% '
end;
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ _exhaustive() {
fi
case "${prev}" in
--shell)
COMPREPLY=($(compgen -W "bash" -- "${cur}"))
COMPREPLY=($(compgen -W "bash fish" -- "${cur}"))
return 0
;;
--register)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ complete -c exhaustive -n "__fish_seen_subcommand_from hint" -l email -r -f
complete -c exhaustive -n "__fish_seen_subcommand_from hint" -l global -d 'everywhere'
complete -c exhaustive -n "__fish_seen_subcommand_from hint" -s h -l help -d 'Print help'
complete -c exhaustive -n "__fish_seen_subcommand_from hint" -s V -l version -d 'Print version'
complete -c exhaustive -n "__fish_seen_subcommand_from complete" -l shell -d 'Specify shell to complete for' -r -f -a "{bash }"
complete -c exhaustive -n "__fish_seen_subcommand_from complete" -l shell -d 'Specify shell to complete for' -r -f -a "{bash ,fish }"
complete -c exhaustive -n "__fish_seen_subcommand_from complete" -l register -d 'Path to write completion-registration to' -r -F
complete -c exhaustive -n "__fish_seen_subcommand_from complete" -l global -d 'everywhere'
complete -c exhaustive -n "__fish_seen_subcommand_from complete" -s h -l help -d 'Print help (see more with \'--help\')'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ _arguments "${_arguments_options[@]}" \
;;
(complete)
_arguments "${_arguments_options[@]}" \
'--shell=[Specify shell to complete for]:SHELL:(bash)' \
'--shell=[Specify shell to complete for]:SHELL:(bash fish)' \
'--register=[Path to write completion-registration to]:REGISTER:_files' \
'--global[everywhere]' \
'-h[Print help (see more with '\''--help'\'')]' \
Expand Down
1 change: 1 addition & 0 deletions clap_complete/tests/snapshots/register_dynamic.fish
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
complete -x -c my-app -a 'my-app'" complete --shell fish -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token)"
Loading