package.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package protobuf
  14. import (
  15. "fmt"
  16. "go/ast"
  17. "log"
  18. "os"
  19. "path/filepath"
  20. "reflect"
  21. "strings"
  22. "k8s.io/kubernetes/cmd/libs/go2idl/generator"
  23. "k8s.io/kubernetes/cmd/libs/go2idl/types"
  24. )
  25. func newProtobufPackage(packagePath, packageName string, generateAll bool, omitFieldTypes map[types.Name]struct{}) *protobufPackage {
  26. pkg := &protobufPackage{
  27. DefaultPackage: generator.DefaultPackage{
  28. // The protobuf package name (foo.bar.baz)
  29. PackageName: packageName,
  30. // A path segment relative to the GOPATH root (foo/bar/baz)
  31. PackagePath: packagePath,
  32. HeaderText: []byte(
  33. `
  34. // This file was autogenerated by go-to-protobuf. Do not edit it manually!
  35. `),
  36. PackageDocumentation: []byte(fmt.Sprintf(
  37. `// Package %s is an autogenerated protobuf IDL.
  38. `, packageName)),
  39. },
  40. GenerateAll: generateAll,
  41. OmitFieldTypes: omitFieldTypes,
  42. }
  43. pkg.FilterFunc = pkg.filterFunc
  44. pkg.GeneratorFunc = pkg.generatorFunc
  45. return pkg
  46. }
  47. // protobufPackage contains the protobuf implementation of Package.
  48. type protobufPackage struct {
  49. generator.DefaultPackage
  50. // If true, generate protobuf serializations for all public types.
  51. // If false, only generate protobuf serializations for structs that
  52. // request serialization.
  53. GenerateAll bool
  54. // A list of types to filter to; if not specified all types will be included.
  55. FilterTypes map[types.Name]struct{}
  56. // If true, omit any gogoprotobuf extensions not defined as types.
  57. OmitGogo bool
  58. // A list of field types that will be excluded from the output struct
  59. OmitFieldTypes map[types.Name]struct{}
  60. // A list of names that this package exports
  61. LocalNames map[string]struct{}
  62. // A list of type names in this package that will need marshaller rewriting
  63. // to remove synthetic protobuf fields.
  64. OptionalTypeNames map[string]struct{}
  65. // A list of struct tags to generate onto named struct fields
  66. StructTags map[string]map[string]string
  67. // An import tracker for this package
  68. Imports *ImportTracker
  69. }
  70. func (p *protobufPackage) Clean(outputBase string) error {
  71. for _, s := range []string{p.ImportPath(), p.OutputPath()} {
  72. if err := os.Remove(filepath.Join(outputBase, s)); err != nil && !os.IsNotExist(err) {
  73. return err
  74. }
  75. }
  76. return nil
  77. }
  78. func (p *protobufPackage) ProtoTypeName() types.Name {
  79. return types.Name{
  80. Name: p.Path(), // the go path "foo/bar/baz"
  81. Package: p.Name(), // the protobuf package "foo.bar.baz"
  82. Path: p.ImportPath(), // the path of the import to get the proto
  83. }
  84. }
  85. func (p *protobufPackage) filterFunc(c *generator.Context, t *types.Type) bool {
  86. switch t.Kind {
  87. case types.Func, types.Chan:
  88. return false
  89. case types.Struct:
  90. if t.Name.Name == "struct{}" {
  91. return false
  92. }
  93. case types.Builtin:
  94. return false
  95. case types.Alias:
  96. if !isOptionalAlias(t) {
  97. return false
  98. }
  99. case types.Slice, types.Array, types.Map:
  100. return false
  101. case types.Pointer:
  102. return false
  103. }
  104. if _, ok := isFundamentalProtoType(t); ok {
  105. return false
  106. }
  107. _, ok := p.FilterTypes[t.Name]
  108. return ok
  109. }
  110. func (p *protobufPackage) HasGoType(name string) bool {
  111. _, ok := p.LocalNames[name]
  112. return ok
  113. }
  114. func (p *protobufPackage) OptionalTypeName(name string) bool {
  115. _, ok := p.OptionalTypeNames[name]
  116. return ok
  117. }
  118. func (p *protobufPackage) ExtractGeneratedType(t *ast.TypeSpec) bool {
  119. if !p.HasGoType(t.Name.Name) {
  120. return false
  121. }
  122. switch s := t.Type.(type) {
  123. case *ast.StructType:
  124. for i, f := range s.Fields.List {
  125. if len(f.Tag.Value) == 0 {
  126. continue
  127. }
  128. tag := strings.Trim(f.Tag.Value, "`")
  129. protobufTag := reflect.StructTag(tag).Get("protobuf")
  130. if len(protobufTag) == 0 {
  131. continue
  132. }
  133. if len(f.Names) > 1 {
  134. log.Printf("WARNING: struct %s field %d %s: defined multiple names but single protobuf tag", t.Name.Name, i, f.Names[0].Name)
  135. // TODO hard error?
  136. }
  137. if p.StructTags == nil {
  138. p.StructTags = make(map[string]map[string]string)
  139. }
  140. m := p.StructTags[t.Name.Name]
  141. if m == nil {
  142. m = make(map[string]string)
  143. p.StructTags[t.Name.Name] = m
  144. }
  145. m[f.Names[0].Name] = tag
  146. }
  147. default:
  148. log.Printf("WARNING: unexpected Go AST type definition: %#v", t)
  149. }
  150. return true
  151. }
  152. func (p *protobufPackage) generatorFunc(c *generator.Context) []generator.Generator {
  153. generators := []generator.Generator{}
  154. p.Imports.AddNullable()
  155. generators = append(generators, &genProtoIDL{
  156. DefaultGen: generator.DefaultGen{
  157. OptionalName: "generated",
  158. },
  159. localPackage: types.Name{Package: p.PackageName, Path: p.PackagePath},
  160. localGoPackage: types.Name{Package: p.PackagePath, Name: p.GoPackageName()},
  161. imports: p.Imports,
  162. generateAll: p.GenerateAll,
  163. omitGogo: p.OmitGogo,
  164. omitFieldTypes: p.OmitFieldTypes,
  165. })
  166. return generators
  167. }
  168. func (p *protobufPackage) GoPackageName() string {
  169. return filepath.Base(p.PackagePath)
  170. }
  171. func (p *protobufPackage) ImportPath() string {
  172. return filepath.Join(p.PackagePath, "generated.proto")
  173. }
  174. func (p *protobufPackage) OutputPath() string {
  175. return filepath.Join(p.PackagePath, "generated.pb.go")
  176. }
  177. var (
  178. _ = generator.Package(&protobufPackage{})
  179. )