github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/cmdconfig/cmd_flags.go (about) 1 package cmdconfig 2 3 import ( 4 "fmt" 5 6 "github.com/fatih/color" 7 "github.com/spf13/cobra" 8 "github.com/spf13/viper" 9 "github.com/turbot/steampipe/pkg/error_helpers" 10 ) 11 12 var requiredColor = color.New(color.Bold).SprintfFunc() 13 14 type FlagOption func(c *cobra.Command, name string, key string) 15 16 // FlagOptions - shortcut for common flag options 17 var FlagOptions = struct { 18 Required func() FlagOption 19 Hidden func() FlagOption 20 Deprecated func(string) FlagOption 21 NoOptDefVal func(string) FlagOption 22 WithShortHand func(string) FlagOption 23 }{ 24 Required: requiredOpt, 25 Hidden: hiddenOpt, 26 Deprecated: deprecatedOpt, 27 NoOptDefVal: noOptDefValOpt, 28 WithShortHand: withShortHand, 29 } 30 31 // Helper function to mark a flag as required 32 func requiredOpt() FlagOption { 33 return func(c *cobra.Command, name, key string) { 34 err := c.MarkFlagRequired(key) 35 error_helpers.FailOnErrorWithMessage(err, "could not mark flag as required") 36 key = fmt.Sprintf("required.%s", key) 37 viper.GetViper().Set(key, true) 38 u := c.Flag(name).Usage 39 c.Flag(name).Usage = fmt.Sprintf("%s %s", u, requiredColor("(required)")) 40 } 41 } 42 43 func hiddenOpt() FlagOption { 44 return func(c *cobra.Command, name, _ string) { 45 c.Flag(name).Hidden = true 46 } 47 } 48 49 func deprecatedOpt(replacement string) FlagOption { 50 return func(c *cobra.Command, name, _ string) { 51 c.Flag(name).Deprecated = fmt.Sprintf("please use %s", replacement) 52 } 53 } 54 55 func noOptDefValOpt(noOptDefVal string) FlagOption { 56 return func(c *cobra.Command, name, _ string) { 57 c.Flag(name).NoOptDefVal = noOptDefVal 58 } 59 } 60 61 func withShortHand(shorthand string) FlagOption { 62 return func(c *cobra.Command, name, _ string) { 63 c.Flag(name).Shorthand = shorthand 64 } 65 }