Skip to content

Mandatory Flags not verified before Prerun. #655

@amanhigh

Description

@amanhigh

Presence of Mandatory Flags is not verified before Prerun unlike Args Check which happens before Prerun.

Hence can't safely use Mandatory Flags in Prerun without additional manual checks.

Sample Code Demonstrating.

package main

import (
	"fmt"
	"github.com/spf13/cobra"
)

var testFlag = ""

var rootCmd = &cobra.Command{
	Use:   "test",
	Short: "Test Command",
	PreRun: func(cmd *cobra.Command, args []string) {
		fmt.Println("Value for Mandator TestFlag is " + testFlag)
	},
	Run: func(cmd *cobra.Command, args []string) {

	},
}

func init() {
	rootCmd.Flags().StringVarP(&testFlag, "test", "t", "Nothing", "Test Flag")
	rootCmd.MarkFlagRequired("test")
}

func main() {
	rootCmd.Execute()
}

Output
Value for Mandator TestFlag is Nothing
Error: required flag(s) "test" not set
Usage:
test [flags]

Flags:
-h, --help help for test
-t, --test string Test Flag (default "Nothing")

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