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

feat(clap_complete): Add powershell support for native completion #5564

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
1,438 changes: 657 additions & 781 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions clap_complete/Cargo.toml
Original file line number Diff line number Diff line change
@@ -45,8 +45,8 @@ unicode-xid = { version = "0.2.2", optional = true }
snapbox = { version = "0.5.9", features = ["diff", "path", "examples"] }
# Cutting out `filesystem` feature
trycmd = { version = "0.15.1", default-features = false, features = ["color-auto", "diff", "examples"] }
completest = "0.4.0"
completest-pty = "0.5.0"
completest = {path = "/home/shanmu/completest"}
completest-pty = {path = "/home/shanmu/completest/crates/completest-pty"}
clap = { path = "../", version = "4.0.0", default-features = false, features = ["std", "derive", "help"] }
automod = "1.0.14"

2 changes: 2 additions & 0 deletions clap_complete/src/dynamic/shells/mod.rs
Original file line number Diff line number Diff line change
@@ -2,10 +2,12 @@
mod bash;
mod fish;
mod powershell;
mod shell;

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

use std::ffi::OsString;
68 changes: 68 additions & 0 deletions clap_complete/src/dynamic/shells/powershell.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/// Completion support for Powershell
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Powershell;

impl crate::dynamic::Completer for Powershell {
fn file_name(&self, name: &str) -> String {
format!("{name}.ps1")
}

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#"
Register-ArgumentCompleter -Native -CommandName {bin} -ScriptBlock {{
param($wordToComplete, $commandAst, $cursorPosition)
$results = Invoke-Expression "&{completer} complete --shell powershell -- $($commandAst.ToString())";
$results | ForEach-Object {{
$split = $_.Split("`t");
$cmd = $split[0];
if ($split.Length -eq 2) {{
$help = $split[1];
}}
else {{
$help = $split[0];
}}
[System.Management.Automation.CompletionResult]::new($cmd, $cmd, 'ParameterValue', $help)
}}
}};
"#
)
}

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)?;

for (completion, help) in completions {
write!(buf, "{}", completion.to_string_lossy())?;
if let Some(help) = help {
write!(
buf,
"\t{}",
help.to_string().lines().next().unwrap_or_default()
)?;
}
writeln!(buf)?;
}
Ok(())
}
}
6 changes: 5 additions & 1 deletion clap_complete/src/dynamic/shells/shell.rs
Original file line number Diff line number Diff line change
@@ -12,6 +12,8 @@ pub enum Shell {
Bash,
/// Friendly Interactive `SHell` (fish)
Fish,
/// Powerful `SHell` (powershel)
Powershell,
}

impl Display for Shell {
@@ -39,13 +41,14 @@ 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::Fish]
&[Shell::Bash, Shell::Fish, Shell::Powershell]
}

fn to_possible_value(&self) -> Option<PossibleValue> {
Some(match self {
Shell::Bash => PossibleValue::new("bash"),
Shell::Fish => PossibleValue::new("fish"),
Shell::Powershell => PossibleValue::new("powershell"),
})
}
}
@@ -55,6 +58,7 @@ impl Shell {
match self {
Self::Bash => &super::Bash,
Self::Fish => &super::Fish,
Self::Powershell => &super::Powershell,
}
}
}

Large diffs are not rendered by default.

28 changes: 28 additions & 0 deletions clap_complete/tests/testsuite/powershell.rs
Original file line number Diff line number Diff line change
@@ -132,3 +132,31 @@ fn subcommand_last() {
name,
);
}

#[test]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the tests can't be added in a prior commit, then they should be added in the commit with the feature.

#[cfg(unix)]
fn register_completion() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that I said working tests is not a blocker for this.

common::register_example::<completest_pty::PowershellRuntimeBuilder>("static", "exhaustive");
}

#[test]
#[cfg(unix)]
fn complete() {
if !common::has_command("pwsh") {
return;
}

let term = completest::Term::new();
let mut runtime =
common::load_runtime::<completest_pty::PowershellRuntimeBuilder>("static", "exhaustive");

let input = "exhaustive \t";
let expected = snapbox::str![
r#"% exhaustive
action complete global help last quote value
alias generate h hint pacman V version "#
];
let actual = runtime.complete(input, &term).unwrap();
println!("shanmu actual: {:?}", actual);
snapbox::assert_eq(expected, actual);
}