Install shell completion as an optional command

This commit is contained in:
2026-11-03 03:50:12 +00:00
parent 0bed76a6f7
commit fc2f6d5346
9 changed files with 219 additions and 3 deletions

View File

@@ -9,6 +9,9 @@ import (
spfcobra "github.com/spf13/cobra"
)
// CompletionQueryToken is the hidden request understood by generated scripts.
const CompletionQueryToken = spfcobra.ShellCompRequestCmd
// CompletionScript generates a shell script for the installed executable.
func CompletionScript(w io.Writer, executable, shell string) error {
root := &spfcobra.Command{Use: executable}
@@ -56,6 +59,11 @@ func replaceCompletionText(script, old, replacement string) (string, error) {
func adjustFishCompletion(script, name string) (string, error) {
var err error
cobraName := strings.NewReplacer("-", "_", ":", "_").Replace(name)
variableName := strings.ReplaceAll(cobraName, ".", "_")
if cobraName != variableName {
script = strings.ReplaceAll(script, "__"+cobraName+"_", "__"+variableName+"_")
}
script, err = replaceCompletionText(script,
`set -l lastArg (string escape -- (commandline -ct))`,
"set -l lastArg (string unescape -- (commandline -ct))\n set -q lastArg[1]; or set lastArg \"\"")
@@ -72,7 +80,7 @@ func adjustFishCompletion(script, name string) (string, error) {
if err != nil {
return "", err
}
variable := "__" + strings.NewReplacer("-", "_", ":", "_").Replace(name) + "_comp_results"
variable := "__" + variableName + "_comp_results"
directories := fmt.Sprintf(`if test $dirfilter -eq 1
set -l flagPrefix (string match -r -- '^-[^=]*=' (commandline -ct))
set --global %[1]s