From b81f43e24e0e56d865516c46f5cb2ac77a07da66 Mon Sep 17 00:00:00 2001 From: Chmouel Boudjnah Date: Tue, 7 Jan 2020 09:35:27 +0100 Subject: [PATCH] Add Aliases completions on ZSH Signed-off-by: Chmouel Boudjnah --- zsh_completions.go | 12 +++++++++++- zsh_completions_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/zsh_completions.go b/zsh_completions.go index 12755482f..7632714f1 100644 --- a/zsh_completions.go +++ b/zsh_completions.go @@ -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) { diff --git a/zsh_completions_test.go b/zsh_completions_test.go index e53fa886e..a5839d44a 100644 --- a/zsh_completions_test.go +++ b/zsh_completions_test.go @@ -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