Skip to content

Commit

Permalink
PersistentFlags
Browse files Browse the repository at this point in the history
  • Loading branch information
mars315 committed Jan 11, 2024
1 parent 495e829 commit 1414afc
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ type (
tagName string
// The tag label separator, default is ","
tagLabelSep string
// persist flags `cmd.PersistentFlags()` default cmd.Flags()
persist bool
}
)

Expand All @@ -136,7 +138,7 @@ func BindFlags(cmd *cobra.Command, v0 builtin.Any, opts ...FlagOption) error {
return err
}

return viper.BindPFlags(cmd.Flags())
return viper.BindPFlags(getFlagSet(cmd, defaultFlagConfig(opts...)))
}

// ReadFlags read flag value from viper
Expand All @@ -157,6 +159,13 @@ func UnmarshalFlags(v0 builtin.Any, opts ...FlagOption) error {

/////////////////////////////////////////////////////// option ///////////////////////////////////////////////////////

// WithPersistFlagSetOption persist flags
func WithPersistFlagSetOption() FlagOption {
return func(cfg *FlagConfig) {
cfg.persist = true
}
}

// WithTagNameOption custom tag name
func WithTagNameOption(tag string) FlagOption {
return func(cfg *FlagConfig) {
Expand Down Expand Up @@ -216,7 +225,7 @@ func bindFlags(cmd *cobra.Command, v0 builtin.Any, cfg *FlagConfig) error {

v := reflect.ValueOf(v0).Elem()
t := v.Type()
flagSet := cmd.Flags()
flagSet := getFlagSet(cmd, cfg)
for i := 0; i < v.NumField(); i++ {
fValue := v.Field(i)
field := t.Field(i)
Expand Down Expand Up @@ -401,6 +410,15 @@ func tryStepOut(field reflect.StructField, cfg *FlagConfig) {
cfg.parent = cfg.parent[:len(cfg.parent)-1]
}

func getFlagSet(cmd *cobra.Command, cfg *FlagConfig) *flag.FlagSet {
switch cfg.persist {
case true:
return cmd.PersistentFlags()
default:
return cmd.Flags()
}
}

// ///////////////////////////////////////////////////// tag ///////////////////////////////////////////////////////

// private
Expand Down

0 comments on commit 1414afc

Please sign in to comment.