PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/github.com/gogo/protobuf/plugin/stringer/stringer.go

https://gitlab.com/unofficial-mirrors/kubernetes
Go | 296 lines | 189 code | 15 blank | 92 comment | 43 complexity | d2722bd309bc7b4d2eaf44b4afc695c5 MD5 | raw file
  1. // Protocol Buffers for Go with Gadgets
  2. //
  3. // Copyright (c) 2013, The GoGo Authors. All rights reserved.
  4. // http://github.com/gogo/protobuf
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. /*
  29. The stringer plugin generates a String method for each message.
  30. It is enabled by the following extensions:
  31. - stringer
  32. - stringer_all
  33. The stringer plugin also generates a test given it is enabled using one of the following extensions:
  34. - testgen
  35. - testgen_all
  36. Let us look at:
  37. github.com/gogo/protobuf/test/example/example.proto
  38. Btw all the output can be seen at:
  39. github.com/gogo/protobuf/test/example/*
  40. The following message:
  41. option (gogoproto.goproto_stringer_all) = false;
  42. option (gogoproto.stringer_all) = true;
  43. message A {
  44. optional string Description = 1 [(gogoproto.nullable) = false];
  45. optional int64 Number = 2 [(gogoproto.nullable) = false];
  46. optional bytes Id = 3 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uuid", (gogoproto.nullable) = false];
  47. }
  48. given to the stringer stringer, will generate the following code:
  49. func (this *A) String() string {
  50. if this == nil {
  51. return "nil"
  52. }
  53. s := strings.Join([]string{`&A{`,
  54. `Description:` + fmt.Sprintf("%v", this.Description) + `,`,
  55. `Number:` + fmt.Sprintf("%v", this.Number) + `,`,
  56. `Id:` + fmt.Sprintf("%v", this.Id) + `,`,
  57. `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
  58. `}`,
  59. }, "")
  60. return s
  61. }
  62. and the following test code:
  63. func TestAStringer(t *testing4.T) {
  64. popr := math_rand4.New(math_rand4.NewSource(time4.Now().UnixNano()))
  65. p := NewPopulatedA(popr, false)
  66. s1 := p.String()
  67. s2 := fmt1.Sprintf("%v", p)
  68. if s1 != s2 {
  69. t.Fatalf("String want %v got %v", s1, s2)
  70. }
  71. }
  72. Typically fmt.Printf("%v") will stop to print when it reaches a pointer and
  73. not print their values, while the generated String method will always print all values, recursively.
  74. */
  75. package stringer
  76. import (
  77. "github.com/gogo/protobuf/gogoproto"
  78. "github.com/gogo/protobuf/protoc-gen-gogo/generator"
  79. "strings"
  80. )
  81. type stringer struct {
  82. *generator.Generator
  83. generator.PluginImports
  84. atleastOne bool
  85. localName string
  86. }
  87. func NewStringer() *stringer {
  88. return &stringer{}
  89. }
  90. func (p *stringer) Name() string {
  91. return "stringer"
  92. }
  93. func (p *stringer) Init(g *generator.Generator) {
  94. p.Generator = g
  95. }
  96. func (p *stringer) Generate(file *generator.FileDescriptor) {
  97. proto3 := gogoproto.IsProto3(file.FileDescriptorProto)
  98. p.PluginImports = generator.NewPluginImports(p.Generator)
  99. p.atleastOne = false
  100. p.localName = generator.FileName(file)
  101. fmtPkg := p.NewImport("fmt")
  102. stringsPkg := p.NewImport("strings")
  103. reflectPkg := p.NewImport("reflect")
  104. sortKeysPkg := p.NewImport("github.com/gogo/protobuf/sortkeys")
  105. protoPkg := p.NewImport("github.com/gogo/protobuf/proto")
  106. for _, message := range file.Messages() {
  107. if !gogoproto.IsStringer(file.FileDescriptorProto, message.DescriptorProto) {
  108. continue
  109. }
  110. if gogoproto.EnabledGoStringer(file.FileDescriptorProto, message.DescriptorProto) {
  111. panic("old string method needs to be disabled, please use gogoproto.goproto_stringer or gogoproto.goproto_stringer_all and set it to false")
  112. }
  113. if message.DescriptorProto.GetOptions().GetMapEntry() {
  114. continue
  115. }
  116. p.atleastOne = true
  117. ccTypeName := generator.CamelCaseSlice(message.TypeName())
  118. p.P(`func (this *`, ccTypeName, `) String() string {`)
  119. p.In()
  120. p.P(`if this == nil {`)
  121. p.In()
  122. p.P(`return "nil"`)
  123. p.Out()
  124. p.P(`}`)
  125. for _, field := range message.Field {
  126. if !p.IsMap(field) {
  127. continue
  128. }
  129. fieldname := p.GetFieldName(message, field)
  130. m := p.GoMapType(nil, field)
  131. mapgoTyp, keyField, keyAliasField := m.GoType, m.KeyField, m.KeyAliasField
  132. keysName := `keysFor` + fieldname
  133. keygoTyp, _ := p.GoType(nil, keyField)
  134. keygoTyp = strings.Replace(keygoTyp, "*", "", 1)
  135. keygoAliasTyp, _ := p.GoType(nil, keyAliasField)
  136. keygoAliasTyp = strings.Replace(keygoAliasTyp, "*", "", 1)
  137. keyCapTyp := generator.CamelCase(keygoTyp)
  138. p.P(keysName, ` := make([]`, keygoTyp, `, 0, len(this.`, fieldname, `))`)
  139. p.P(`for k, _ := range this.`, fieldname, ` {`)
  140. p.In()
  141. if keygoAliasTyp == keygoTyp {
  142. p.P(keysName, ` = append(`, keysName, `, k)`)
  143. } else {
  144. p.P(keysName, ` = append(`, keysName, `, `, keygoTyp, `(k))`)
  145. }
  146. p.Out()
  147. p.P(`}`)
  148. p.P(sortKeysPkg.Use(), `.`, keyCapTyp, `s(`, keysName, `)`)
  149. mapName := `mapStringFor` + fieldname
  150. p.P(mapName, ` := "`, mapgoTyp, `{"`)
  151. p.P(`for _, k := range `, keysName, ` {`)
  152. p.In()
  153. if keygoAliasTyp == keygoTyp {
  154. p.P(mapName, ` += fmt.Sprintf("%v: %v,", k, this.`, fieldname, `[k])`)
  155. } else {
  156. p.P(mapName, ` += fmt.Sprintf("%v: %v,", k, this.`, fieldname, `[`, keygoAliasTyp, `(k)])`)
  157. }
  158. p.Out()
  159. p.P(`}`)
  160. p.P(mapName, ` += "}"`)
  161. }
  162. p.P("s := ", stringsPkg.Use(), ".Join([]string{`&", ccTypeName, "{`,")
  163. oneofs := make(map[string]struct{})
  164. for _, field := range message.Field {
  165. nullable := gogoproto.IsNullable(field)
  166. repeated := field.IsRepeated()
  167. fieldname := p.GetFieldName(message, field)
  168. oneof := field.OneofIndex != nil
  169. if oneof {
  170. if _, ok := oneofs[fieldname]; ok {
  171. continue
  172. } else {
  173. oneofs[fieldname] = struct{}{}
  174. }
  175. p.P("`", fieldname, ":`", ` + `, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, ") + `,", "`,")
  176. } else if p.IsMap(field) {
  177. mapName := `mapStringFor` + fieldname
  178. p.P("`", fieldname, ":`", ` + `, mapName, " + `,", "`,")
  179. } else if (field.IsMessage() && !gogoproto.IsCustomType(field)) || p.IsGroup(field) {
  180. desc := p.ObjectNamed(field.GetTypeName())
  181. msgname := p.TypeName(desc)
  182. msgnames := strings.Split(msgname, ".")
  183. typeName := msgnames[len(msgnames)-1]
  184. if nullable {
  185. p.P("`", fieldname, ":`", ` + `, stringsPkg.Use(), `.Replace(`, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, `), "`, typeName, `","`, msgname, `"`, ", 1) + `,", "`,")
  186. } else if repeated {
  187. p.P("`", fieldname, ":`", ` + `, stringsPkg.Use(), `.Replace(`, stringsPkg.Use(), `.Replace(`, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, `), "`, typeName, `","`, msgname, `"`, ", 1),`&`,``,1) + `,", "`,")
  188. } else {
  189. p.P("`", fieldname, ":`", ` + `, stringsPkg.Use(), `.Replace(`, stringsPkg.Use(), `.Replace(this.`, fieldname, `.String(), "`, typeName, `","`, msgname, `"`, ", 1),`&`,``,1) + `,", "`,")
  190. }
  191. } else {
  192. if nullable && !repeated && !proto3 {
  193. p.P("`", fieldname, ":`", ` + valueToString`, p.localName, `(this.`, fieldname, ") + `,", "`,")
  194. } else {
  195. p.P("`", fieldname, ":`", ` + `, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, ") + `,", "`,")
  196. }
  197. }
  198. }
  199. if message.DescriptorProto.HasExtension() {
  200. if gogoproto.HasExtensionsMap(file.FileDescriptorProto, message.DescriptorProto) {
  201. p.P("`XXX_InternalExtensions:` + ", protoPkg.Use(), ".StringFromInternalExtension(this) + `,`,")
  202. } else {
  203. p.P("`XXX_extensions:` + ", protoPkg.Use(), ".StringFromExtensionsBytes(this.XXX_extensions) + `,`,")
  204. }
  205. }
  206. if gogoproto.HasUnrecognized(file.FileDescriptorProto, message.DescriptorProto) {
  207. p.P("`XXX_unrecognized:` + ", fmtPkg.Use(), `.Sprintf("%v", this.XXX_unrecognized) + `, "`,`,")
  208. }
  209. p.P("`}`,")
  210. p.P(`}`, `,""`, ")")
  211. p.P(`return s`)
  212. p.Out()
  213. p.P(`}`)
  214. //Generate String methods for oneof fields
  215. for _, field := range message.Field {
  216. oneof := field.OneofIndex != nil
  217. if !oneof {
  218. continue
  219. }
  220. ccTypeName := p.OneOfTypeName(message, field)
  221. p.P(`func (this *`, ccTypeName, `) String() string {`)
  222. p.In()
  223. p.P(`if this == nil {`)
  224. p.In()
  225. p.P(`return "nil"`)
  226. p.Out()
  227. p.P(`}`)
  228. p.P("s := ", stringsPkg.Use(), ".Join([]string{`&", ccTypeName, "{`,")
  229. fieldname := p.GetOneOfFieldName(message, field)
  230. if field.IsMessage() || p.IsGroup(field) {
  231. desc := p.ObjectNamed(field.GetTypeName())
  232. msgname := p.TypeName(desc)
  233. msgnames := strings.Split(msgname, ".")
  234. typeName := msgnames[len(msgnames)-1]
  235. p.P("`", fieldname, ":`", ` + `, stringsPkg.Use(), `.Replace(`, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, `), "`, typeName, `","`, msgname, `"`, ", 1) + `,", "`,")
  236. } else {
  237. p.P("`", fieldname, ":`", ` + `, fmtPkg.Use(), `.Sprintf("%v", this.`, fieldname, ") + `,", "`,")
  238. }
  239. p.P("`}`,")
  240. p.P(`}`, `,""`, ")")
  241. p.P(`return s`)
  242. p.Out()
  243. p.P(`}`)
  244. }
  245. }
  246. if !p.atleastOne {
  247. return
  248. }
  249. p.P(`func valueToString`, p.localName, `(v interface{}) string {`)
  250. p.In()
  251. p.P(`rv := `, reflectPkg.Use(), `.ValueOf(v)`)
  252. p.P(`if rv.IsNil() {`)
  253. p.In()
  254. p.P(`return "nil"`)
  255. p.Out()
  256. p.P(`}`)
  257. p.P(`pv := `, reflectPkg.Use(), `.Indirect(rv).Interface()`)
  258. p.P(`return `, fmtPkg.Use(), `.Sprintf("*%v", pv)`)
  259. p.Out()
  260. p.P(`}`)
  261. }
  262. func init() {
  263. generator.RegisterPlugin(NewStringer())
  264. }