Add Aliases completions on ZSH

Signed-off-by: Chmouel Boudjnah <chmouel@chmouel.com>
This commit is contained in:
Chmouel Boudjnah 2020-01-07 09:35:27 +01:00
parent 89c7ffb512
commit b81f43e24e
No known key found for this signature in database
GPG key ID: 8E00E7B02807E02D
2 changed files with 43 additions and 1 deletions

View file

@ -23,6 +23,7 @@ var (
zshCompFuncMap = template.FuncMap{
"genZshFuncName": zshCompGenFuncName,
"extractFlags": zshCompExtractFlag,
"genAliases": zshGenAliases,
"genFlagEntryForZshArguments": zshCompGenFlagEntryForArguments,
"extractArgsCompletions": zshCompExtractArgumentCompletionHintsForRendering,
}
@ -48,7 +49,7 @@ function {{$cmdPath}} {
esac
case "$words[1]" in {{- range .Commands}}{{if not .Hidden}}
{{.Name}})
{{.Name}}{{genAliases .}})
{{$cmdPath}}_{{.Name}}
;;{{end}}{{end}}
esac
@ -250,6 +251,15 @@ func zshCompGenFuncName(c *Command) string {
return "_" + c.Name()
}
func zshGenAliases(c *Command) string {
sort.Sort(sort.StringSlice(c.Aliases))
ret := ""
for _, value := range c.Aliases {
ret += fmt.Sprintf("|%s", value)
}
return ret
}
func zshCompExtractFlag(c *Command) []*pflag.Flag {
var flags []*pflag.Flag
c.LocalFlags().VisitAll(func(f *pflag.Flag) {

View file

@ -7,6 +7,38 @@ import (
"testing"
)
func TestGenZshAliases(t *testing.T) {
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
echoCmd := &Command{
Use: "echo",
Aliases: []string{"say", "tell"},
Args: NoArgs,
Run: emptyRun,
}
timesCmd := &Command{
Use: "times",
Args: ExactArgs(2),
Run: emptyRun,
}
echoCmd.AddCommand(timesCmd)
rootCmd.AddCommand(echoCmd)
rootCmd.Execute()
buf := new(bytes.Buffer)
if err := rootCmd.GenZshCompletion(buf); err != nil {
t.Error(err)
}
output := buf.Bytes()
expr := `echo|say|tell\)$`
rgx, err := regexp.Compile(expr)
if err != nil {
t.Errorf("error compiling expression (%s): %v", expr, err)
}
if !rgx.Match(output) {
t.Errorf("expected completion (%s) to match '%s'", buf.String(), expr)
}
}
func TestGenZshCompletion(t *testing.T) {
var debug bool
var option string