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

Completions do not suggest sub-commands if there are ValidArgs #1076

Closed
marckhouzam opened this issue Apr 2, 2020 · 0 comments · Fixed by #1088
Closed

Completions do not suggest sub-commands if there are ValidArgs #1076

marckhouzam opened this issue Apr 2, 2020 · 0 comments · Fixed by #1088

Comments

@marckhouzam
Copy link
Collaborator

When a command has both ValidArgs and sub-commands, the completion script only proposes the ValidArgs. Cobra should do also propose non-hidden sub-commands in the completions list.

I cannot see a reason not to do this...

This was brought up in #1035 (comment)

To illustrate, in the program below, the rootCmd specifies ValidArgs of rs and ds, but also has a sub-command pod. The bash completion script will only propose the values of ValidArgs and not the sub-commands when both are present. In this case testprog [tab][tab] will not suggest pod because there are ValidArgs.

Program to reproduce:

package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	ValidArgs: []string{/*"pod",*/ "rs", "ds"},
	Args:      cobra.ExactArgs(1),
	Use:       "testprog1",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("rootCmd called")
	},
}

var childCmd = &cobra.Command{
	Use: "pod",
	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) {
		return []string{"these", "are", "custom", "completions"}, cobra.BashCompDirectiveDefault
	},
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("child called")
	},
}

var childCmd2 = &cobra.Command{
	Use: "svc",
	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.BashCompDirective) {
		return []string{"second", "level"}, cobra.BashCompDirectiveDefault
	},
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("child called")
	},
}

var completionCmd = &cobra.Command{
	Use: "completion",
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Root().GenBashCompletion(os.Stdout)
	},
}

func main() {
	rootCmd.AddCommand(childCmd)
	rootCmd.AddCommand(completionCmd)
	childCmd.AddCommand(childCmd2)
	rootCmd.Execute()
}
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

Successfully merging a pull request may close this issue.

1 participant