|
| 1 | +// Package flags provides utility functions for working with cobra command flags. |
| 2 | +// It simplifies the process of marking flags as required and handling related errors. |
| 3 | +package flags |
| 4 | + |
| 5 | +import ( |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +const flagRequiredErrorMsg = "error setting %s flag as required - %s: %v" |
| 13 | + |
| 14 | +// SetFlagRequired marks a single flag as required for a cobra command. |
| 15 | +// If isPersistent is true, it marks the persistent flag as required. |
| 16 | +// Returns an error if the flag cannot be marked as required. |
| 17 | +func SetFlagRequired(cmd *cobra.Command, flag string, location string, isPersistent bool) error { |
| 18 | + if isPersistent { |
| 19 | + if err := cmd.MarkPersistentFlagRequired(flag); err != nil { |
| 20 | + return fmt.Errorf(flagRequiredErrorMsg, flag, location, err) |
| 21 | + } |
| 22 | + } else { |
| 23 | + if err := cmd.MarkFlagRequired(flag); err != nil { |
| 24 | + return fmt.Errorf(flagRequiredErrorMsg, flag, location, err) |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + return nil |
| 29 | +} |
| 30 | + |
| 31 | +// SetFlagsRequired marks multiple flags as required for a cobra command. |
| 32 | +// If isPersistent is true, it marks the persistent flags as required. |
| 33 | +// Returns a joined error if any flag cannot be marked as required. |
| 34 | +func SetFlagsRequired(cmd *cobra.Command, flags []string, location string, isPersistent bool) error { |
| 35 | + flagErrors := make([]error, len(flags)) |
| 36 | + |
| 37 | + for i, flag := range flags { |
| 38 | + if err := SetFlagRequired(cmd, flag, location, isPersistent); err != nil { |
| 39 | + flagErrors[i] = err |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return errors.Join(flagErrors...) |
| 44 | +} |
0 commit comments