From 95a14877231aa8413a101d306f7f52607bade8fe Mon Sep 17 00:00:00 2001 From: Arik Kfir Date: Wed, 31 Jul 2024 13:44:42 +0300 Subject: [PATCH] fix(flags): apply CLI and environment vars values for post-run hooks This change fixes an omission bug that causes flags of post-run hooks not to be parsed and applied. --- command.go | 7 +++++++ command_test.go | 25 ++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index b18894d..8b252ee 100644 --- a/command.go +++ b/command.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "reflect" + "slices" "strings" ) @@ -162,6 +163,12 @@ func (c *Command) setParent(parent *Command) error { for _, hook := range c.preRunHooks { configObjects = append(configObjects, reflect.ValueOf(hook)) } + for _, hook := range c.postRunHooks { + hv := reflect.ValueOf(hook) + if !slices.ContainsFunc(configObjects, func(v reflect.Value) bool { return v.Interface() == hv.Interface() }) { + configObjects = append(configObjects, hv) + } + } if fs, err := newFlagSet(parentFlags, configObjects...); err != nil { return fmt.Errorf("failed creating flag-set for command '%s': %w", c.name, err) } else { diff --git a/command_test.go b/command_test.go index b358f6d..a3486ea 100644 --- a/command_test.go +++ b/command_test.go @@ -53,7 +53,16 @@ func TestNew(t *testing.T) { Action MyFlag string `flag:"true"` }{}, - nil, + []any{ + &struct { + TrackingPreRunHook + PreRunFlag string `flag:"true"` + }{}, + &struct { + TrackingPostRunHook + PostRunFlag string `flag:"true"` + }{}, + }, ) }, expectedFlagSet: &flagSet{ @@ -65,6 +74,20 @@ func TestNew(t *testing.T) { }, Targets: []reflect.Value{}, }, + { + flagInfo: flagInfo{ + Name: "pre-run-flag", + HasValue: true, + }, + Targets: []reflect.Value{}, + }, + { + flagInfo: flagInfo{ + Name: "post-run-flag", + HasValue: true, + }, + Targets: []reflect.Value{}, + }, }, }, },