Skip to content

having required persistent flag in root command fails builtin command like "completion" and "help" when the flag is not specified #2212

@hujun-open

Description

@hujun-open

if there is required persistent flag in root command, then the cobra builtin command "completion" and "help" will not work if the flag is not specified, I guess this is somewhat expected behavior, but I find it is a bit annoying to have this limitation, is there any workaround to address this?

example code:

package main

import (
	"fmt"

	"github.com/spf13/cobra"
)

func main() {
	var rootCmd = &cobra.Command{
		Use: "mytest",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("root gets called")
		},
	}
	var source string
	rootCmd.PersistentFlags().StringVarP(&source, "source", "s", "", "source input")
	rootCmd.MarkPersistentFlagRequired("source")
	rootCmd.AddCommand(&cobra.Command{
		Use: "sub",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("sub gets called")
		},
	})

	err := rootCmd.Execute()
	if err != nil {
		panic(err)
	}
}

completion doesn't work if the "source" flag is not specified

.\mytest.exe completion powershell
Error: required flag(s) "source" not set
Usage:
  mytest completion powershell [flags]

Flags:
  -h, --help              help for powershell
      --no-descriptions   disable completion descriptions

Global Flags:
  -s, --source string   source input

panic: required flag(s) "source" not set

goroutine 1 [running]:
main.main()
        C:/hujun/gomodules/src/test/main.go:28 +0x133

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions