Skip to content

Commit 3c2de63

Browse files
committed
go-to-protobuf: fix rewrite of embedded struct fields
The protobuf generator cannot handle embedded struct fields correctly. When using an embedded field by pointer it produces the error message `unable to get name for tag from struct "...", field ...` The reason is that the name determination evaluating the AST does not handle pointers if the AST does not already contain a field name. This seems to be the case for structs embedded by pointers. Example: ``` type MyStruct struct { *OtherStruct `protobuf:"bytes,1,opt,name=otherStruct"` } ```
1 parent 7f7378e commit 3c2de63

File tree

1 file changed

+19
-7
lines changed
  • staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf

1 file changed

+19
-7
lines changed

staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,21 @@ func RewriteTypesWithProtobufStructTags(name string, structTags map[string]map[s
375375
})
376376
}
377377

378+
func getFieldName(expr ast.Expr, structname string) (name string, err error) {
379+
for {
380+
switch t := expr.(type) {
381+
case *ast.Ident:
382+
return t.Name, nil
383+
case *ast.SelectorExpr:
384+
return t.Sel.Name, nil
385+
case *ast.StarExpr:
386+
expr = t.X
387+
default:
388+
return "", fmt.Errorf("unable to get name for tag from struct %q, field %#v", structname, t)
389+
}
390+
}
391+
}
392+
378393
func updateStructTags(decl ast.Decl, structTags map[string]map[string]string, toCopy []string) []error {
379394
var errs []error
380395
t, ok := decl.(*ast.GenDecl)
@@ -403,14 +418,11 @@ func updateStructTags(decl ast.Decl, structTags map[string]map[string]string, to
403418
for i := range st.Fields.List {
404419
f := st.Fields.List[i]
405420
var name string
421+
var err error
406422
if len(f.Names) == 0 {
407-
switch t := f.Type.(type) {
408-
case *ast.Ident:
409-
name = t.Name
410-
case *ast.SelectorExpr:
411-
name = t.Sel.Name
412-
default:
413-
errs = append(errs, fmt.Errorf("unable to get name for tag from struct %q, field %#v", spec.Name.Name, t))
423+
name, err = getFieldName(f.Type, spec.Name.Name)
424+
if err != nil {
425+
errs = append(errs, err)
414426
continue
415427
}
416428
} else {

0 commit comments

Comments
 (0)