Cobra: completions doesn't work with changed executable name

Created on 1 Nov 2020  路  5Comments  路  Source: spf13/cobra

To reproduce

  • go build -o custom_executable_name
  • On bash source <(custom_executable_name completion bash)
  • ./coustom_executable_name [TAB][TAB] results in nothing

The completions doesn't work because they still read from the cobra's app name

Expected:

The bash or any other completions should work

Suggestion

I've been trying to tweak it by getting the executable's name using exepath, err := os.Executable() then path.Base(exepath) and use that to generate bash completions. I think that would work.

Most helpful comment

@hitzhangjie For aliases things are easier. For zsh and fish aliases are handled automatically. For bash you have to include an extra line in your .bashrc file. Please see: https://github.com/spf13/cobra/blob/master/shell_completions.md#aliases

All 5 comments

I recommend using Use: filepath.Base(os.Args[0]) for the root command, path.Base() would not work correctly on windows.

I'd love to see this supported.
For Helm, there is a common case while users migrate from helm v2 to helm v3 where they will install both versions. Some of these users will rename the binaries to helm2 and/or helm3.

To support completion in these cases we've had to append code to each completion script to consider the new binary name. That approach is very hacky and brittle. And we didn't even do it for Fish completion as it was too complex.

For example: https://github.com/helm/helm/blob/84b02bbee3ec2415cdddc0b52f85d120f2d4a592/cmd/helm/completion.go#L128

I come across same problem.

I deveoped a utility named gitcode, while I think typing gitcode is a little time consuming, so I added an alias in .bashrc:

alias gg=gitcode

Then I run gg [tab][tab], no completions at all. I see it is because the generated completion shell script is based on the rootCmd's name, not the executable's name.

@hitzhangjie For aliases things are easier. For zsh and fish aliases are handled automatically. For bash you have to include an extra line in your .bashrc file. Please see: https://github.com/spf13/cobra/blob/master/shell_completions.md#aliases

Yeah, it works. Thanks @marckhouzam

Was this page helpful?
0 / 5 - 0 ratings

Related issues

icholy picture icholy  路  6Comments

diwakergupta picture diwakergupta  路  5Comments

garthk picture garthk  路  3Comments

rogercoll picture rogercoll  路  5Comments

anentropic picture anentropic  路  4Comments