From dec9c817e6636246735c0db967e6299adfdc1124 Mon Sep 17 00:00:00 2001 From: Laurent Demailly Date: Sun, 12 Feb 2023 09:48:19 -0800 Subject: [PATCH] rename PostSet to SetV and split the dynamic log level example/code --- dyngeneric.go | 8 ++++++-- dynjson.go | 2 +- dynloglevel/dynloglevel.go | 6 ++++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/dyngeneric.go b/dyngeneric.go index 4061dc0..9e65c94 100644 --- a/dyngeneric.go +++ b/dyngeneric.go @@ -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) } diff --git a/dynjson.go b/dynjson.go index 393cf6e..444a0d9 100644 --- a/dynjson.go +++ b/dynjson.go @@ -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. diff --git a/dynloglevel/dynloglevel.go b/dynloglevel/dynloglevel.go index 8ed76ee..24ff9ca 100644 --- a/dynloglevel/dynloglevel.go +++ b/dynloglevel/dynloglevel.go @@ -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)) @@ -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 }