Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Aliases completions on ZSH #1014

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion zsh_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var (
zshCompFuncMap = template.FuncMap{
"genZshFuncName": zshCompGenFuncName,
"extractFlags": zshCompExtractFlag,
"genAliases": zshGenAliases,
"genFlagEntryForZshArguments": zshCompGenFlagEntryForArguments,
"extractArgsCompletions": zshCompExtractArgumentCompletionHintsForRendering,
}
Expand All @@ -48,7 +49,7 @@ function {{$cmdPath}} {
esac

case "$words[1]" in {{- range .Commands}}{{if not .Hidden}}
{{.Name}})
{{.Name}}{{genAliases .}})
{{$cmdPath}}_{{.Name}}
;;{{end}}{{end}}
esac
Expand Down Expand Up @@ -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) {
Expand Down
32 changes: 32 additions & 0 deletions zsh_completions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,38 @@ import (
"testing"
)

func TestGenZshAliases(t *testing.T) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chmouel excellent job on this PR.

I'd be curious to see some negative test cases (ie. no aliases, empty aliases array, etc)

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
Expand Down