Skip to content

Commit

Permalink
rename PostSet to SetV and split the dynamic log level example/code
Browse files Browse the repository at this point in the history
  • Loading branch information
ldemailly committed Feb 12, 2023
1 parent ac3ba1f commit dec9c81
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
8 changes: 6 additions & 2 deletions dyngeneric.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,14 @@ func (d *DynValue[T]) Set(rawInput string) error {
if err != nil {
return err
}
return d.PostSet(val)
return d.SetV(val)
}

func (d *DynValue[T]) PostSet(val T) error {
// SetV is for when the value is already parsed/of the correct type.
// Validators and notifiers are triggered (only input mutator and parsing from string is skipped).
// Ideally this would be called Set() and the other SetAsString() but
// the flag api needs Set() to be the one taking a string.
func (d *DynValue[T]) SetV(val T) error {
if d.mutator != nil {
val = d.mutator(val)
}
Expand Down
2 changes: 1 addition & 1 deletion dynjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (d *DynJSONValue) Set(rawInput string) error {
if err := json.Unmarshal([]byte(input), val); err != nil {
return err
}
return d.PostSet(val)
return d.SetV(val)
}

// String returns the canonical string representation of the type.
Expand Down
6 changes: 4 additions & 2 deletions dynloglevel/dynloglevel.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ func LoggerFlagSetup() {
return // avoid redefining flag/make it ok for multiple function to init this.
}
// virtual dynLevel flag that maps back to actual level
_ = dflag.DynString(flag.CommandLine, "loglevel", log.GetLogLevel().String(),
fmt.Sprintf("loglevel, one of %v", log.LevelToStrA)).WithInputMutator(
defVal := log.GetLogLevel().String()
usage := fmt.Sprintf("`loglevel`, one of %v", log.LevelToStrA)
flag := dflag.New(defVal, usage).WithInputMutator(
func(inp string) string {
// The validation map has full lowercase and capitalized first letter version
return strings.ToLower(strings.TrimSpace(inp))
Expand All @@ -48,6 +49,7 @@ func LoggerFlagSetup() {
func(old, newStr string) {
_ = log.SetLogLevelStr(newStr) // will succeed as we just validated it first
})
dflag.Flag("loglevel", flag)
done = true
}

Expand Down

0 comments on commit dec9c81

Please sign in to comment.