Cobra MarkPersistentFlagRequired not working on Root

1.9k Views Asked by At

Using spf13/Cobra for cli flag parsing.

root command has a field marked required:

rootCmd.PersistentFlags().StringVarP(&configFilePath, "config", "c","", "REQUIRED: config file")
    rootCmd.MarkPersistentFlagRequired("config")    
    rootCmd.MarkFlagRequired("config")

However, cobra does not raise an error if it's the root command.

If I add a subcommand and add a required field, .MarkFlagRequired raises an error as expected if the argument is not provided on the command line.

1

There are 1 best solutions below

0
On BEST ANSWER

This works for me.

package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    var strTmp string
    rootCmd := &cobra.Command{
        Use: "root",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println(strTmp)
        },
    }
    subCmd := &cobra.Command{
        Use: "sub",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println(strTmp)
        },
    }
    rootCmd.PersistentFlags().StringVarP((&strTmp), "test", "t", "", "test required")
    rootCmd.MarkPersistentFlagRequired("test")
    rootCmd.AddCommand(subCmd)
    rootCmd.Execute()
}

Output

sub command

 ⇒  go run test.go sub     
Error: required flag(s) "test" not set
Usage:
  root sub [flags]

Flags:
  -h, --help   help for sub

Global Flags:
  -t, --test string   test required

root command

⇒  go run test.go     
Error: required flag(s) "test" not set
Usage:
  root [flags]
  root [command]

Available Commands:
  completion  generate the autocompletion script for the specified shell
  help        Help about any command
  sub         

Flags:
  -h, --help          help for root
  -t, --test string   test required

Use "root [command] --help" for more information about a command.