Skip to content
Myr

powershell completion with custom comp (#1208)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The current powershell completion is not very capable. Let's port it to the go custom completion logic to have a unified experience accross all shells. Powershell supports three different completion modes - TabCompleteNext (default windows style - on each key press the next option is displayed) - Complete (works like bash) - MenuComplete (works like zsh) You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>` To keep it backwards compatible `GenPowerShellCompletion` will not display descriptions. Use `GenPowerShellCompletionWithDesc` instead. Descriptions will only be displayed with `MenuComplete` or `Complete`.

authored by Paul Holzinger · committed by GitHub · parent 471c9ac · Browse files · 4 files+306 added−206 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Paul Holzinger <paul.holzinger@web.de>

Diff stats

4 files+306 added−206 removed

  • other:+306 added−206 removed

4 files+306 added−206 removed

deleted:powershell_completions_test.go-122 removed
1package cobra23import (4 "bytes"5 "strings"6 "testing"7)89func TestPowerShellCompletion(t *testing.T) {10 tcs := []struct {11 name string12 root *Command13 expectedExpressions []string14 }{15 {16 name: "trivial",17 root: &Command{Use: "trivialapp"},18 expectedExpressions: []string{19 "Register-ArgumentCompleter -Native -CommandName 'trivialapp' -ScriptBlock",20 "$command = @(\n 'trivialapp'\n",21 },22 },23 {24 name: "tree",25 root: func() *Command {26 r := &Command{Use: "tree"}2728 sub1 := &Command{Use: "sub1"}29 r.AddCommand(sub1)3031 sub11 := &Command{Use: "sub11"}32 sub12 := &Command{Use: "sub12"}3334 sub1.AddCommand(sub11)35 sub1.AddCommand(sub12)3637 sub2 := &Command{Use: "sub2"}38 r.AddCommand(sub2)3940 sub21 := &Command{Use: "sub21"}41 sub22 := &Command{Use: "sub22"}4243 sub2.AddCommand(sub21)44 sub2.AddCommand(sub22)4546 return r47 }(),48 expectedExpressions: []string{49 "'tree'",50 "[CompletionResult]::new('sub1', 'sub1', [CompletionResultType]::ParameterValue, '')",51 "[CompletionResult]::new('sub2', 'sub2', [CompletionResultType]::ParameterValue, '')",52 "'tree;sub1'",53 "[CompletionResult]::new('sub11', 'sub11', [CompletionResultType]::ParameterValue, '')",54 "[CompletionResult]::new('sub12', 'sub12', [CompletionResultType]::ParameterValue, '')",55 "'tree;sub1;sub11'",56 "'tree;sub1;sub12'",57 "'tree;sub2'",58 "[CompletionResult]::new('sub21', 'sub21', [CompletionResultType]::ParameterValue, '')",59 "[CompletionResult]::new('sub22', 'sub22', [CompletionResultType]::ParameterValue, '')",60 "'tree;sub2;sub21'",61 "'tree;sub2;sub22'",62 },63 },64 {65 name: "flags",66 root: func() *Command {67 r := &Command{Use: "flags"}68 r.Flags().StringP("flag1", "a", "", "")69 r.Flags().String("flag2", "", "")7071 sub1 := &Command{Use: "sub1"}72 sub1.Flags().StringP("flag3", "c", "", "")73 r.AddCommand(sub1)7475 return r76 }(),77 expectedExpressions: []string{78 "'flags'",79 "[CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, '')",80 "[CompletionResult]::new('--flag1', 'flag1', [CompletionResultType]::ParameterName, '')",81 "[CompletionResult]::new('--flag2', 'flag2', [CompletionResultType]::ParameterName, '')",82 "[CompletionResult]::new('sub1', 'sub1', [CompletionResultType]::ParameterValue, '')",83 "'flags;sub1'",84 "[CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, '')",85 "[CompletionResult]::new('--flag3', 'flag3', [CompletionResultType]::ParameterName, '')",86 },87 },88 {89 name: "usage",90 root: func() *Command {91 r := &Command{Use: "usage"}92 r.Flags().String("flag", "", "this describes the usage of the 'flag' flag")9394 sub1 := &Command{95 Use: "sub1",96 Short: "short describes 'sub1'",97 }98 r.AddCommand(sub1)99100 return r101 }(),102 expectedExpressions: []string{103 "[CompletionResult]::new('--flag', 'flag', [CompletionResultType]::ParameterName, 'this describes the usage of the ''flag'' flag')",104 "[CompletionResult]::new('sub1', 'sub1', [CompletionResultType]::ParameterValue, 'short describes ''sub1''')",105 },106 },107 }108109 for _, tc := range tcs {110 t.Run(tc.name, func(t *testing.T) {111 buf := new(bytes.Buffer)112 tc.root.GenPowerShellCompletion(buf)113 output := buf.String()114115 for _, expectedExpression := range tc.expectedExpressions {116 if !strings.Contains(output, expectedExpression) {117 t.Errorf("Expected completion to contain %q somewhere; got %q", expectedExpression, output)118 }119 }120 })121 }122}
modified:powershell_completions.go+251 added-66 removed
1// PowerShell completions are based on the amazing work from clap:2// https://github.com/clap-rs/clap/blob/3294d18efe5f264d12c9035f404c7d189d4824e1/src/completions/powershell.rs3//1// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but2// can be downloaded separately for windows 7 or 8.1).34package cobra
2 unmodified lines
7 "bytes"8 "fmt"9 "io"10 "os"14 "strings"1516 "github.com/spf13/pflag"11)1219var powerShellCompletionTemplate = `using namespace System.Management.Automation20using namespace System.Management.Automation.Language21Register-ArgumentCompleter -Native -CommandName '%s' -ScriptBlock {22 param($wordToComplete, $commandAst, $cursorPosition)23 $commandElements = $commandAst.CommandElements24 $command = @(25 '%s'26 for ($i = 1; $i -lt $commandElements.Count; $i++) {27 $element = $commandElements[$i]28 if ($element -isnot [StringConstantExpressionAst] -or29 $element.StringConstantType -ne [StringConstantType]::BareWord -or30 $element.Value.StartsWith('-')) {31 break32 }33 $element.Value13func genPowerShellComp(buf *bytes.Buffer, name string, includeDesc bool) {14 compCmd := ShellCompRequestCmd15 if !includeDesc {16 compCmd = ShellCompNoDescRequestCmd17 }18 buf.WriteString(fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-1920function __%[1]s_debug {21 if ($env:BASH_COMP_DEBUG_FILE) {22 "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"23 }24}2526filter __%[1]s_escapeStringWithSpecialChars {27`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`28}2930Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {31 param(32 $WordToComplete,33 $CommandAst,34 $CursorPosition35 )3637 # Get the current command line and convert into a string38 $Command = $CommandAst.CommandElements39 $Command = "$Command"4041 __%[1]s_debug ""42 __%[1]s_debug "========= starting completion logic =========="43 __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"4445 # The user could have moved the cursor backwards on the command-line.46 # We need to trigger completion from the $CursorPosition location, so we need47 # to truncate the command-line ($Command) up to the $CursorPosition location.48 # Make sure the $Command is longer then the $CursorPosition before we truncate.49 # This happens because the $Command does not include the last space. 50 if ($Command.Length -gt $CursorPosition) {51 $Command=$Command.Substring(0,$CursorPosition)52 }53 __%[1]s_debug "Truncated command: $Command"54 55 $ShellCompDirectiveError=%[3]d56 $ShellCompDirectiveNoSpace=%[4]d57 $ShellCompDirectiveNoFileComp=%[5]d58 $ShellCompDirectiveFilterFileExt=%[6]d59 $ShellCompDirectiveFilterDirs=%[7]d6061 # Prepare the command to request completions for the program.62 # Split the command at the first space to separate the program and arguments.63 $Program,$Arguments = $Command.Split(" ",2)64 $RequestComp="$Program %[2]s $Arguments"65 __%[1]s_debug "RequestComp: $RequestComp"6667 # we cannot use $WordToComplete because it 68 # has the wrong values if the cursor was moved69 # so use the last argument70 if ($WordToComplete -ne "" ) {71 $WordToComplete = $Arguments.Split(" ")[-1]72 }73 __%[1]s_debug "New WordToComplete: $WordToComplete"747576 # Check for flag with equal sign77 $IsEqualFlag = ($WordToComplete -Like "--*=*" )78 if ( $IsEqualFlag ) {79 __%[1]s_debug "Completing equal sign flag"80 # Remove the flag part81 $Flag,$WordToComplete = $WordToComplete.Split("=",2)82 }8384 if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {85 # If the last parameter is complete (there is a space following it)86 # We add an extra empty parameter so we can indicate this to the go method.87 __%[1]s_debug "Adding extra empty parameter"88`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+`89`+" $RequestComp=\"$RequestComp\" + ' `\"`\"' "+`90 }9192 __%[1]s_debug "Calling $RequestComp"93 #call the command store the output in $out and redirect stderr and stdout to null94 # $Out is an array contains each line per element95 Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null969798 # get directive from last line99 [int]$Directive = $Out[-1].TrimStart(':')100 if ($Directive -eq "") {101 # There is no directive specified102 $Directive = 0103 }104 __%[1]s_debug "The completion directive is: $Directive"105 106 # remove directive (last element) from out107 $Out = $Out | Where-Object { $_ -ne $Out[-1] }108 __%[1]s_debug "The completions are: $Out"109110 if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {111 # Error code. No completion.112 __%[1]s_debug "Received error from custom completion go code"113 return114 }115116 $Longest = 0117 $Values = $Out | ForEach-Object {118 #Split the output in name and description119`+" $Name, $Description = $_.Split(\"`t\",2)"+`120 __%[1]s_debug "Name: $Name Description: $Description"121122 # Look for the longest completion so that we can format things nicely123 if ($Longest -lt $Name.Length) {124 $Longest = $Name.Length125 }35 ) -join ';'36 $completions = @(switch ($command) {%s37 })38 $completions.Where{ $_.CompletionText -like "$wordToComplete*" } |39 Sort-Object -Property ListItemText40}`12642func generatePowerShellSubcommandCases(out io.Writer, cmd *Command, previousCommandName string) {43 var cmdName string44 if previousCommandName == "" {45 cmdName = cmd.Name()46 } else {47 cmdName = fmt.Sprintf("%s;%s", previousCommandName, cmd.Name())48 }127 # Set the description to a one space string if there is none set.128 # This is needed because the CompletionResult does not accept an empty string as argument129 if (-Not $Description) {130 $Description = " "131 }132 @{Name="$Name";Description="$Description"}133 }13450 fmt.Fprintf(out, "\n '%s' {", cmdName)13552 cmd.Flags().VisitAll(func(flag *pflag.Flag) {53 if nonCompletableFlag(flag) {54 return55 }56 usage := escapeStringForPowerShell(flag.Usage)57 if len(flag.Shorthand) > 0 {58 fmt.Fprintf(out, "\n [CompletionResult]::new('-%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Shorthand, flag.Shorthand, usage)59 }60 fmt.Fprintf(out, "\n [CompletionResult]::new('--%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Name, flag.Name, usage)61 })136 $Space = " "137 if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {138 # remove the space here139 __%[1]s_debug "ShellCompDirectiveNoSpace is called"140 $Space = ""141 }14263 for _, subCmd := range cmd.Commands() {64 usage := escapeStringForPowerShell(subCmd.Short)65 fmt.Fprintf(out, "\n [CompletionResult]::new('%s', '%s', [CompletionResultType]::ParameterValue, '%s')", subCmd.Name(), subCmd.Name(), usage)66 }143 if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {144 __%[1]s_debug "ShellCompDirectiveNoFileComp is called"145 146 if ($Values.Length -eq 0) {147 # Just print an empty string here so the 148 # shell does not start to complete paths.149 # We cannot use CompletionResult here because 150 # it does not accept an empty string as argument.151 ""152 return153 }154 }15568 fmt.Fprint(out, "\n break\n }")156 if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or 157 (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {158 __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"15970 for _, subCmd := range cmd.Commands() {71 generatePowerShellSubcommandCases(out, subCmd, cmdName)72 }73}160 # return here to prevent the completion of the extensions161 return162 }16375func escapeStringForPowerShell(s string) string {76 return strings.Replace(s, "'", "''", -1)77}164 $Values = $Values | Where-Object {165 # filter the result166 $_.Name -like "$WordToComplete*"16779// GenPowerShellCompletion generates PowerShell completion file and writes to the passed writer.80func (c *Command) GenPowerShellCompletion(w io.Writer) error {81 buf := new(bytes.Buffer)168 # Join the flag back if we have a equal sign flag169 if ( $IsEqualFlag ) {170 __%[1]s_debug "Join the equal sign flag back to the completion value"171 $_.Name = $Flag + "=" + $_.Name172 }173 } 17483 var subCommandCases bytes.Buffer84 generatePowerShellSubcommandCases(&subCommandCases, c, "")85 fmt.Fprintf(buf, powerShellCompletionTemplate, c.Name(), c.Name(), subCommandCases.String())175 # Get the current mode176 $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function177 __%[1]s_debug "Mode: $Mode"178179 $Values | ForEach-Object {180181 # store temporay because switch will overwrite $_182 $comp = $_183184 # Powershell supports three different completion modes185 # - TabCompleteNext (default windows style - on each key press the next option is displayed)186 # - Complete (works like bash)187 # - MenuComplete (works like zsh)188 # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>189190 # CompletionResult Arguments:191 # 1) CompletionText text to be used as the auto completion result192 # 2) ListItemText text to be displayed in the suggestion list193 # 3) ResultType type of completion result194 # 4) ToolTip text for the tooltip with details about the object195196 switch ($Mode) {197198 # bash like199 "Complete" {200201 if ($Values.Length -eq 1) {202 __%[1]s_debug "Only one completion left"203204 # insert space after value205 [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")206207 } else {208 # Add the proper number of spaces to align the descriptions209 while($comp.Name.Length -lt $Longest) {210 $comp.Name = $comp.Name + " "211 }212213 # Check for empty description and only add parentheses if needed214 if ($($comp.Description) -eq " " ) {215 $Description = ""216 } else {217 $Description = " ($($comp.Description))"218 }219220 [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")221 }222 }223224 # zsh like225 "MenuComplete" {226 # insert space after value227 # MenuComplete will automatically show the ToolTip of 228 # the highlighted value at the bottom of the suggestions.229 [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")230 }231232 # TabCompleteNext and in case we get something unknown233 Default {234 # Like MenuComplete but we don't want to add a space here because 235 # the user need to press space anyway to get the completion.236 # Description will not be shown because thats not possible with TabCompleteNext237 [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")238 }239 }240241 }242}243`, name, compCmd,244 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,245 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))246}247248func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {249 buf := new(bytes.Buffer)250 genPowerShellComp(buf, c.Name(), includeDesc)251 _, err := buf.WriteTo(w)252 return err253}25491// GenPowerShellCompletionFile generates PowerShell completion file.92func (c *Command) GenPowerShellCompletionFile(filename string) error {255func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error {256 outFile, err := os.Create(filename)257 if err != nil {258 return err259 }260 defer outFile.Close()26199 return c.GenPowerShellCompletion(outFile)262 return c.genPowerShellCompletion(outFile, includeDesc)263}264265// GenPowerShellCompletionFile generates powershell completion file without descriptions.266func (c *Command) GenPowerShellCompletionFile(filename string) error {267 return c.genPowerShellCompletionFile(filename, false)268}269270// GenPowerShellCompletion generates powershell completion file without descriptions271// and writes it to the passed writer.272func (c *Command) GenPowerShellCompletion(w io.Writer) error {273 return c.genPowerShellCompletion(w, false)274}275276// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.277func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error {278 return c.genPowerShellCompletionFile(filename, true)279}280281// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions282// and writes it to the passed writer.283func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error {284 return c.genPowerShellCompletion(w, true)285}
modified:powershell_completions.md+1 added-14 removed
modified:shell_completions.md+54 added-4 removed
47 unmodified lines
48$ yourprogram completion fish | source4950# To load completions for each session, execute once:51$ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish5253Powershell:5455PS> yourprogram completion powershell | Out-String | Invoke-Expression5657# To load completions for every new session, run:58PS> yourprogram completion powershell > yourprogram.ps159# and source this file from your powershell profile.60`,61 DisableFlagsInUseLine: true,62 ValidArgs: []string{"bash", "zsh", "fish", "powershell"},63 Args: cobra.ExactValidArgs(1),
259 unmodified lines
323})324```325### Descriptions for completions326319Both `zsh` and `fish` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh:327`zsh`, `fish` and `powershell` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh:328```329$ helm s[tab]330search -- search for a keyword in charts331show -- show information of a chart
65 unmodified lines
397398### Limitations399400* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).393 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`).401 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).402* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.403 * You should instead use `RegisterFlagCompletionFunc()`.404405### Zsh completions standardization
17 unmodified lines
423424### Limitations425426* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).419 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`).427 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).428* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.429 * You should instead use `RegisterFlagCompletionFunc()`.430* The following flag completion annotations are not supported and will be ignored for `fish`:431 * `BashCompFilenameExt` (filtering by file extension)
6 unmodified lines
438 * `ShellCompDirectiveFilterDirs` (filtering by directory)439440## PowerShell completions441434Please refer to [PowerShell Completions](powershell_completions.md) for details.442Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.443444The script is designed to support all three Powershell completion modes:445446* TabCompleteNext (default windows style - on each key press the next option is displayed)447* Complete (works like bash)448* MenuComplete (works like zsh)449450You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.451452Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.453454```455# With descriptions and Mode 'Complete'456$ helm s[tab]457search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)458459# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.460$ helm s[tab]461search show status 462463search for a keyword in charts464465# Without descriptions466$ helm s[tab]467search show status468```469470### Limitations471472* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).473 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).474* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.475 * You should instead use `RegisterFlagCompletionFunc()`.476* The following flag completion annotations are not supported and will be ignored for `powershell`:477 * `BashCompFilenameExt` (filtering by file extension)478 * `BashCompSubdirsInDir` (filtering by directory)479* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:480 * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)481 * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)482* Similarly, the following completion directives are not supported and will be ignored for `powershell`:483 * `ShellCompDirectiveFilterFileExt` (filtering by file extension)484 * `ShellCompDirectiveFilterDirs` (filtering by directory)