Open c-bata opened 6 years ago
package kube
import (
"github.com/c-bata/go-prompt"
"github.com/spf13/cobra"
"k8s.io/kubernetes/pkg/kubectl/cmd"
)
var (
cobraCommand *cobra.Command
)
func init() {
cobraCommand = cmd.NewDefaultKubectlCommand()
}
func getSubCommand(command *cobra.Command, name string) *cobra.Command {
sub := command.Commands()
for i := range sub {
if sub[i].Name() == name {
return sub[i]
}
}
return nil
}
func generateSuggestions(command *cobra.Command) []prompt.Suggest {
sub := command.Commands()
suggests := make([]prompt.Suggest, len(sub))
for i := range sub {
suggests[i] = prompt.Suggest{Text: sub[i].Name(), Description: sub[i].Long}
}
}
func argumentsCompleter(args []string) []prompt.Suggest {
current := cobraCommand
l := len(args)
for i := 1; i <= l; i++ {
if i == l {
commands := generateSuggestions(current)
return prompt.FilterHasPrefix(commands, args[0], true)
}
current = getSubCommand(current, args[i])
if current == nil {
break
}
}
return []prompt.Suggest{}
}
todo: automatically generate flag suggesitons
Generate suggestions from cobra.Command defined at kubectl:
https://github.com/kubernetes/kubernetes/blob/d7cadf5d180277cfed7fd57d1e1a125c538bd751/pkg/kubectl/cmd/cmd.go#L221