cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Powershell completion alias handling

Open bartoncasey opened this issue 1 year ago • 5 comments

Currently the Powershell completion generator registers the completion for the default command name. Any aliases of the command will not have completion enabled. (e.g. k -> kubectl)

This change will include code to register the completer for all current aliases of the command in addition to the command itself.

bartoncasey avatar Oct 18 '23 17:10 bartoncasey

CLA assistant check
All committers have signed the CLA.

CLAassistant avatar Oct 18 '23 17:10 CLAassistant

Thanks @bartoncasey. There is #1977 which is trying to do this. I don't have much expertise with PowerShell, so maybe you can help figure out if #1977 solves things for you?

marckhouzam avatar Oct 18 '23 20:10 marckhouzam

Oh, no. I should have done a better job of looking for existing PRs.

It looks like #1977 is assuming that you will always alias things using the absolute path of the executable:

Set-Alias -Name k -Value "C:\Program Files\Docker\Docker\resources\bin\kubectl.exe"

vs what I think is the more convential form of

Set-Alias -Name k -Value kubectl

Mine looks for aliases of the latter form.

bartoncasey avatar Oct 19 '23 15:10 bartoncasey

Set-Alias -Name k -Value "C:\Program Files\Docker\Docker\resources\bin\kubectl.exe"

I've tested this PR and although it is working very nicely for normal aliases, I don't believe it works for the above form.

So now I'm going back and forth between this PR and #1977 hoping to find the sweet spot.

marckhouzam avatar Oct 30 '23 15:10 marckhouzam

After spending quite a bit of time trying things out, I think this solution is the simplest and I believe can be made to cover every case. I was thinking of these cases:

  1. any alias pointing to kubectl or kubectl.exe
  2. any alias pointing to /<path>/kubectl or /<path>/kubectl.exe

I think we can achieve this with a slight modification do have instead:

# Register the completer for the command and for all aliases of the command
'%[1]s', (Get-Alias -Definition %[1]s,*/%[1]s,%[1]s.exe,*/%[1]s.exe -ErrorAction Ignore).Name | ForEach-Object {
    if ($_) {
        Register-ArgumentCompleter -CommandName $_ -ScriptBlock ${__%[2]sCompleterBlock}
    }
}

This translates to something like Get-Alias -Definition kubectl,*/kubectl,kubectl.exe,*/kubectl.exe which covers the cases listed above.

@bartoncasey What do you think?

marckhouzam avatar Oct 31 '23 15:10 marckhouzam