Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion callbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kong
import (
"fmt"
"reflect"
"runtime"
"strings"
)

Expand Down Expand Up @@ -127,13 +128,38 @@ func getMethod(value reflect.Value, name string) reflect.Value {
return method
}

func getExplicitMethod(value reflect.Value, name string) reflect.Value {
if isExplicitMethod(value.Type(), name) {
return value.MethodByName(name)
}
if value.CanAddr() && isExplicitMethod(value.Addr().Type(), name) {
return value.Addr().MethodByName(name)
}
return reflect.Value{}
}

func isExplicitMethod(t reflect.Type, name string) bool {
method, ok := t.MethodByName(name)
if !ok {
return false
}
// Promoted embedded methods are compiler-generated wrappers. The embedded
// value itself is visited separately, so skip those wrappers here.
fn := runtime.FuncForPC(method.Func.Pointer())
if fn == nil {
return true
}
file, _ := fn.FileLine(method.Func.Pointer())
return file != "<autogenerated>"
}

// getMethods gets all methods with the given name from the given value
// and any embedded fields.
//
// Returns a slice of bound methods that can be called directly.
func getMethods(value reflect.Value, name string) (methods []reflect.Value) {
walkEmbedded(value, func(v reflect.Value) {
if method := getMethod(v, name); method.IsValid() {
if method := getExplicitMethod(v, name); method.IsValid() {
methods = append(methods, method)
}
})
Expand Down
31 changes: 31 additions & 0 deletions kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2697,6 +2697,37 @@ func TestApplyCalledOnce(t *testing.T) {
assert.NoError(t, err)
}

type EmbeddedAfterApplyLeaf struct {
calls *int
}

func (l EmbeddedAfterApplyLeaf) AfterApply() error {
(*l.calls)++
return nil
}

type EmbeddedAfterApplyMiddle struct {
EmbeddedAfterApplyLeaf
}

type EmbeddedAfterApplyRoot struct {
EmbeddedAfterApplyMiddle
}

func TestPromotedEmbeddedAfterApplyCalledOnce(t *testing.T) {
calls := 0
cli := &EmbeddedAfterApplyRoot{
EmbeddedAfterApplyMiddle: EmbeddedAfterApplyMiddle{
EmbeddedAfterApplyLeaf: EmbeddedAfterApplyLeaf{
calls: &calls,
},
},
}
_, err := mustNew(t, cli).Parse(nil)
assert.NoError(t, err)
assert.Equal(t, 1, calls)
}

type envOnlyAfterApply struct {
called bool
}
Expand Down