powershell_completions.go
This file
Path
powershell_completions.go
350 lines · 13.3 KiB · Go
Last changed by
Make Powershell completion script work in constrained mode (#2196)Leonhard Stemplingerbefore adoption5a138f1
History of this fileTake it
The walk stopped after 200 commits: lines older than 89d7b83 point at it.
update copyright year (#1927)Unai Martinez-Corralbefore adoption9e6b58a
line 1why, one step back1// Copyright 2013-2023 The Cobra Authorsadd missing license headers (#1809)Unai Martinez-Corralbefore adoption6d978a9
lines 2–14why, one step back2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 15–24why, one step back15// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but16// can be downloaded separately for windows 7 or 8.1).1718package cobra1920import (21 "bytes"22 "fmt"23 "io"24 "os"Allow user to add completion for powershell alias (#1621)Marc Khouzambefore adoptiond4040ad
line 25why, one step back25 "strings"Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 26–28why, one step back26)2728func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {Allow user to add completion for powershell alias (#1621)Marc Khouzambefore adoptiond4040ad
lines 29–30why, one step back29 // Variables should not contain a '-' or ':' character30 nameForVar := nameMore linting (#2099)Ville Skyttäbefore adoption6b5f577
lines 31–32why, one step back31 nameForVar = strings.ReplaceAll(nameForVar, "-", "_")32 nameForVar = strings.ReplaceAll(nameForVar, ":", "_")Allow user to add completion for powershell alias (#1621)Marc Khouzambefore adoptiond4040ad
line 33why, one step back33Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 34–49why, one step back34 compCmd := ShellCompRequestCmd35 if !includeDesc {36 compCmd = ShellCompNoDescRequestCmd37 }38 WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-3940function __%[1]s_debug {41 if ($env:BASH_COMP_DEBUG_FILE) {42 "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"43 }44}4546filter __%[1]s_escapeStringWithSpecialChars {47`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`48}49powershell: escape variable with curly brackets (#1960)Paul Holzingerbefore adoptionfdee73b
line 50why, one step back50[scriptblock]${__%[2]sCompleterBlock} = {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 51–74why, one step back51 param(52 $WordToComplete,53 $CommandAst,54 $CursorPosition55 )5657 # Get the current command line and convert into a string58 $Command = $CommandAst.CommandElements59 $Command = "$Command"6061 __%[1]s_debug ""62 __%[1]s_debug "========= starting completion logic =========="63 __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"6465 # The user could have moved the cursor backwards on the command-line.66 # We need to trigger completion from the $CursorPosition location, so we need67 # to truncate the command-line ($Command) up to the $CursorPosition location.68 # Make sure the $Command is longer then the $CursorPosition before we truncate.69 # This happens because the $Command does not include the last space.70 if ($Command.Length -gt $CursorPosition) {71 $Command=$Command.Substring(0,$CursorPosition)72 }73 __%[1]s_debug "Truncated command: $Command"74Allow user to add completion for powershell alias (#1621)Marc Khouzambefore adoptiond4040ad
lines 75–79why, one step back75 $ShellCompDirectiveError=%[4]d76 $ShellCompDirectiveNoSpace=%[5]d77 $ShellCompDirectiveNoFileComp=%[6]d78 $ShellCompDirectiveFilterFileExt=%[7]d79 $ShellCompDirectiveFilterDirs=%[8]dAdd keeporder to shell completion (#1903)Gyanendra Mishrabefore adoption3daa4b9
line 80why, one step back80 $ShellCompDirectiveKeepOrder=%[9]dAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 81–84why, one step back8182 # Prepare the command to request completions for the program.83 # Split the command at the first space to separate the program and arguments.84 $Program,$Arguments = $Command.Split(" ",2)Add Active Help support (#1482)Marc Khouzambefore adoptionf464d6c
line 85why, one step back85Allow user to add completion for powershell alias (#1621)Marc Khouzambefore adoptiond4040ad
line 86why, one step back86 $RequestComp="$Program %[3]s $Arguments"Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 87–109why, one step back87 __%[1]s_debug "RequestComp: $RequestComp"8889 # we cannot use $WordToComplete because it90 # has the wrong values if the cursor was moved91 # so use the last argument92 if ($WordToComplete -ne "" ) {93 $WordToComplete = $Arguments.Split(" ")[-1]94 }95 __%[1]s_debug "New WordToComplete: $WordToComplete"969798 # Check for flag with equal sign99 $IsEqualFlag = ($WordToComplete -Like "--*=*" )100 if ( $IsEqualFlag ) {101 __%[1]s_debug "Completing equal sign flag"102 # Remove the flag part103 $Flag,$WordToComplete = $WordToComplete.Split("=",2)104 }105106 if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {107 # If the last parameter is complete (there is a space following it)108 # We add an extra empty parameter so we can indicate this to the go method.109 __%[1]s_debug "Adding extra empty parameter"Add support for PowerShell 7.2+ (#1916)Oldřich Jedličkabefore adoption567ea8e
lines 110–120why, one step back110 # PowerShell 7.2+ changed the way how the arguments are passed to executables,111 # so for pre-7.2 or when Legacy argument passing is enabled we need to use112`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+`113 if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or114 ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or115 (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and116 $PSNativeCommandArgumentPassing -eq 'Legacy')) {117`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`118 } else {119 $RequestComp="$RequestComp" + ' ""'120 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 121–123why, one step back121 }122123 __%[1]s_debug "Calling $RequestComp"Add Active Help support (#1482)Marc Khouzambefore adoptionf464d6c
line 124why, one step back124 # First disable ActiveHelp which is not supported for Powershellpowershell: escape variable with curly brackets (#1960)Paul Holzingerbefore adoptionfdee73b
line 125why, one step back125 ${env:%[10]s}=0Add Active Help support (#1482)Marc Khouzambefore adoptionf464d6c
line 126why, one step back126Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 127–149why, one step back127 #call the command store the output in $out and redirect stderr and stdout to null128 # $Out is an array contains each line per element129 Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null130131 # get directive from last line132 [int]$Directive = $Out[-1].TrimStart(':')133 if ($Directive -eq "") {134 # There is no directive specified135 $Directive = 0136 }137 __%[1]s_debug "The completion directive is: $Directive"138139 # remove directive (last element) from out140 $Out = $Out | Where-Object { $_ -ne $Out[-1] }141 __%[1]s_debug "The completions are: $Out"142143 if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {144 # Error code. No completion.145 __%[1]s_debug "Received error from custom completion go code"146 return147 }148149 $Longest = 0fix: force ForEach-Object to return array in pwsh completion (#1850)Norman Dankertbefore adoptionc6b9971
line 150why, one step back150 [Array]$Values = $Out | ForEach-Object {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 151–164why, one step back151 #Split the output in name and description152`+" $Name, $Description = $_.Split(\"`t\",2)"+`153 __%[1]s_debug "Name: $Name Description: $Description"154155 # Look for the longest completion so that we can format things nicely156 if ($Longest -lt $Name.Length) {157 $Longest = $Name.Length158 }159160 # Set the description to a one space string if there is none set.161 # This is needed because the CompletionResult does not accept an empty string as argument162 if (-Not $Description) {163 $Description = " "164 }Make Powershell completion script work in constrained mode (#2196)Leonhard Stemplingerbefore adoption5a138f1
lines 165–168why, one step back165 New-Object -TypeName PSCustomObject -Property @{166 Name = "$Name"167 Description = "$Description"168 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 169–197why, one step back169 }170171172 $Space = " "173 if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {174 # remove the space here175 __%[1]s_debug "ShellCompDirectiveNoSpace is called"176 $Space = ""177 }178179 if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or180 (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {181 __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"182183 # return here to prevent the completion of the extensions184 return185 }186187 $Values = $Values | Where-Object {188 # filter the result189 $_.Name -like "$WordToComplete*"190191 # Join the flag back if we have an equal sign flag192 if ( $IsEqualFlag ) {193 __%[1]s_debug "Join the equal sign flag back to the completion value"194 $_.Name = $Flag + "=" + $_.Name195 }196 }197Add keeporder to shell completion (#1903)Gyanendra Mishrabefore adoption3daa4b9
lines 198–202why, one step back198 # we sort the values in ascending order by name if keep order isn't passed199 if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {200 $Values = $Values | Sort-Object -Property Name201 }202Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 203–245why, one step back203 if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {204 __%[1]s_debug "ShellCompDirectiveNoFileComp is called"205206 if ($Values.Length -eq 0) {207 # Just print an empty string here so the208 # shell does not start to complete paths.209 # We cannot use CompletionResult here because210 # it does not accept an empty string as argument.211 ""212 return213 }214 }215216 # Get the current mode217 $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function218 __%[1]s_debug "Mode: $Mode"219220 $Values | ForEach-Object {221222 # store temporary because switch will overwrite $_223 $comp = $_224225 # PowerShell supports three different completion modes226 # - TabCompleteNext (default windows style - on each key press the next option is displayed)227 # - Complete (works like bash)228 # - MenuComplete (works like zsh)229 # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>230231 # CompletionResult Arguments:232 # 1) CompletionText text to be used as the auto completion result233 # 2) ListItemText text to be displayed in the suggestion list234 # 3) ResultType type of completion result235 # 4) ToolTip text for the tooltip with details about the object236237 switch ($Mode) {238239 # bash like240 "Complete" {241242 if ($Values.Length -eq 1) {243 __%[1]s_debug "Only one completion left"244245 # insert space after valueMake Powershell completion script work in constrained mode (#2196)Leonhard Stemplingerbefore adoption5a138f1
lines 246–251why, one step back246 $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space247 if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){248 [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")249 } else {250 $CompletionText251 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 252–265why, one step back252253 } else {254 # Add the proper number of spaces to align the descriptions255 while($comp.Name.Length -lt $Longest) {256 $comp.Name = $comp.Name + " "257 }258259 # Check for empty description and only add parentheses if needed260 if ($($comp.Description) -eq " " ) {261 $Description = ""262 } else {263 $Description = " ($($comp.Description))"264 }265Make Powershell completion script work in constrained mode (#2196)Leonhard Stemplingerbefore adoption5a138f1
lines 266–271why, one step back266 $CompletionText = "$($comp.Name)$Description"267 if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){268 [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")269 } else {270 $CompletionText271 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 272–279why, one step back272 }273 }274275 # zsh like276 "MenuComplete" {277 # insert space after value278 # MenuComplete will automatically show the ToolTip of279 # the highlighted value at the bottom of the suggestions.Make Powershell completion script work in constrained mode (#2196)Leonhard Stemplingerbefore adoption5a138f1
lines 280–286why, one step back280281 $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space282 if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){283 [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")284 } else {285 $CompletionText286 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 287–293why, one step back287 }288289 # TabCompleteNext and in case we get something unknown290 Default {291 # Like MenuComplete but we don't want to add a space here because292 # the user need to press space anyway to get the completion.293 # Description will not be shown because that's not possible with TabCompleteNextMake Powershell completion script work in constrained mode (#2196)Leonhard Stemplingerbefore adoption5a138f1
lines 294–300why, one step back294295 $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars)296 if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){297 [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")298 } else {299 $CompletionText300 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 301–305why, one step back301 }302 }303304 }305}Allow user to add completion for powershell alias (#1621)Marc Khouzambefore adoptiond4040ad
line 306why, one step back306powershell: escape variable with curly brackets (#1960)Paul Holzingerbefore adoptionfdee73b
line 307why, one step back307Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock}Allow user to add completion for powershell alias (#1621)Marc Khouzambefore adoptiond4040ad
line 308why, one step back308`, name, nameForVar, compCmd,Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 309why, one step back309 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,Add keeporder to shell completion (#1903)Gyanendra Mishrabefore adoption3daa4b9
line 310why, one step back310 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 311–350why, one step back311}312313func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {314 buf := new(bytes.Buffer)315 genPowerShellComp(buf, c.Name(), includeDesc)316 _, err := buf.WriteTo(w)317 return err318}319320func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error {321 outFile, err := os.Create(filename)322 if err != nil {323 return err324 }325 defer outFile.Close()326327 return c.genPowerShellCompletion(outFile, includeDesc)328}329330// GenPowerShellCompletionFile generates powershell completion file without descriptions.331func (c *Command) GenPowerShellCompletionFile(filename string) error {332 return c.genPowerShellCompletionFile(filename, false)333}334335// GenPowerShellCompletion generates powershell completion file without descriptions336// and writes it to the passed writer.337func (c *Command) GenPowerShellCompletion(w io.Writer) error {338 return c.genPowerShellCompletion(w, false)339}340341// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.342func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error {343 return c.genPowerShellCompletionFile(filename, true)344}345346// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions347// and writes it to the passed writer.348func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error {349 return c.genPowerShellCompletion(w, true)350}