Skip to content

Commit

Permalink
fixes case where embeded structs would cause no field to be found
Browse files Browse the repository at this point in the history
  • Loading branch information
codyleyhan committed Aug 24, 2018
1 parent 40f904a commit 32de231
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
7 changes: 5 additions & 2 deletions codegen/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package codegen
import (
"fmt"
"go/types"
"log"
"reflect"
"regexp"
"strings"
Expand Down Expand Up @@ -117,6 +118,8 @@ func findField(typ *types.Struct, name, structTag string) (*types.Var, error) {
for i := 0; i < typ.NumFields(); i++ {
field := typ.Field(i)

log.Println("@@@@", field.Name(), name, structTag)

if structTag != "" {
tags := reflect.StructTag(typ.Tag(i))
if val, ok := tags.Lookup(structTag); ok {
Expand All @@ -134,7 +137,7 @@ func findField(typ *types.Struct, name, structTag string) (*types.Var, error) {
if field.Anonymous() {
if named, ok := field.Type().(*types.Struct); ok {
f, err := findField(named, name, structTag)
if err != nil {
if err != nil && !strings.HasPrefix(err.Error(), "no field named") {
return nil, err
}
if f != nil && foundField == nil {
Expand All @@ -144,7 +147,7 @@ func findField(typ *types.Struct, name, structTag string) (*types.Var, error) {

if named, ok := field.Type().Underlying().(*types.Struct); ok {
f, err := findField(named, name, structTag)
if err != nil {
if err != nil && !strings.HasPrefix(err.Error(), "no field named") {
return nil, err
}
if f != nil && foundField == nil {
Expand Down
6 changes: 6 additions & 0 deletions codegen/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ type Amb struct {
Bar string ` + "`" + `gqlgen:"foo"` + "`" + `
Foo int ` + "`" + `gqlgen:"foo"` + "`" + `
}
type Embed struct {
Std
Test string
}
`
scope, err := parseScope(input, "test")
require.NoError(t, err)
Expand All @@ -46,6 +50,7 @@ type Amb struct {
anon := scope.Lookup("Anon").Type().Underlying().(*types.Struct)
tags := scope.Lookup("Tags").Type().Underlying().(*types.Struct)
amb := scope.Lookup("Amb").Type().Underlying().(*types.Struct)
embed := scope.Lookup("Embed").Type().Underlying().(*types.Struct)

tests := []struct {
Name string
Expand All @@ -61,6 +66,7 @@ type Amb struct {
{"Picks field with tag over field name when passed a tag", tags, "foo", "gqlgen", "Bar", false},
{"Errors when ambigious", amb, "foo", "gqlgen", "", true},
{"Finds a field that is in embedded struct", anon, "bar", "", "Bar", false},
{"Finds field that is not in embedded struct", embed, "test", "", "Test", false},
}

for _, tt := range tests {
Expand Down

0 comments on commit 32de231

Please sign in to comment.