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

Generate suggestions from cobra.Command recursively. #18

Open
c-bata opened this issue Feb 22, 2018 · 1 comment
Open

Generate suggestions from cobra.Command recursively. #18

c-bata opened this issue Feb 22, 2018 · 1 comment

Comments

@c-bata
Copy link
Owner

c-bata commented Feb 22, 2018

Generate suggestions from cobra.Command defined at kubectl:

https://github.com/kubernetes/kubernetes/blob/d7cadf5d180277cfed7fd57d1e1a125c538bd751/pkg/kubectl/cmd/cmd.go#L221

@c-bata
Copy link
Owner Author

c-bata commented Feb 22, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant