proto.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package protodesc
  5. import (
  6. "fmt"
  7. "strings"
  8. "google.golang.org/protobuf/internal/encoding/defval"
  9. "google.golang.org/protobuf/internal/strs"
  10. "google.golang.org/protobuf/proto"
  11. "google.golang.org/protobuf/reflect/protoreflect"
  12. "google.golang.org/protobuf/types/descriptorpb"
  13. )
  14. // ToFileDescriptorProto copies a protoreflect.FileDescriptor into a
  15. // google.protobuf.FileDescriptorProto message.
  16. func ToFileDescriptorProto(file protoreflect.FileDescriptor) *descriptorpb.FileDescriptorProto {
  17. p := &descriptorpb.FileDescriptorProto{
  18. Name: proto.String(file.Path()),
  19. Options: proto.Clone(file.Options()).(*descriptorpb.FileOptions),
  20. }
  21. if file.Package() != "" {
  22. p.Package = proto.String(string(file.Package()))
  23. }
  24. for i, imports := 0, file.Imports(); i < imports.Len(); i++ {
  25. imp := imports.Get(i)
  26. p.Dependency = append(p.Dependency, imp.Path())
  27. if imp.IsPublic {
  28. p.PublicDependency = append(p.PublicDependency, int32(i))
  29. }
  30. if imp.IsWeak {
  31. p.WeakDependency = append(p.WeakDependency, int32(i))
  32. }
  33. }
  34. for i, locs := 0, file.SourceLocations(); i < locs.Len(); i++ {
  35. loc := locs.Get(i)
  36. l := &descriptorpb.SourceCodeInfo_Location{}
  37. l.Path = append(l.Path, loc.Path...)
  38. if loc.StartLine == loc.EndLine {
  39. l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndColumn)}
  40. } else {
  41. l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndLine), int32(loc.EndColumn)}
  42. }
  43. l.LeadingDetachedComments = append([]string(nil), loc.LeadingDetachedComments...)
  44. if loc.LeadingComments != "" {
  45. l.LeadingComments = proto.String(loc.LeadingComments)
  46. }
  47. if loc.TrailingComments != "" {
  48. l.TrailingComments = proto.String(loc.TrailingComments)
  49. }
  50. if p.SourceCodeInfo == nil {
  51. p.SourceCodeInfo = &descriptorpb.SourceCodeInfo{}
  52. }
  53. p.SourceCodeInfo.Location = append(p.SourceCodeInfo.Location, l)
  54. }
  55. for i, messages := 0, file.Messages(); i < messages.Len(); i++ {
  56. p.MessageType = append(p.MessageType, ToDescriptorProto(messages.Get(i)))
  57. }
  58. for i, enums := 0, file.Enums(); i < enums.Len(); i++ {
  59. p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))
  60. }
  61. for i, services := 0, file.Services(); i < services.Len(); i++ {
  62. p.Service = append(p.Service, ToServiceDescriptorProto(services.Get(i)))
  63. }
  64. for i, exts := 0, file.Extensions(); i < exts.Len(); i++ {
  65. p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))
  66. }
  67. if syntax := file.Syntax(); syntax != protoreflect.Proto2 {
  68. p.Syntax = proto.String(file.Syntax().String())
  69. }
  70. return p
  71. }
  72. // ToDescriptorProto copies a protoreflect.MessageDescriptor into a
  73. // google.protobuf.DescriptorProto message.
  74. func ToDescriptorProto(message protoreflect.MessageDescriptor) *descriptorpb.DescriptorProto {
  75. p := &descriptorpb.DescriptorProto{
  76. Name: proto.String(string(message.Name())),
  77. Options: proto.Clone(message.Options()).(*descriptorpb.MessageOptions),
  78. }
  79. for i, fields := 0, message.Fields(); i < fields.Len(); i++ {
  80. p.Field = append(p.Field, ToFieldDescriptorProto(fields.Get(i)))
  81. }
  82. for i, exts := 0, message.Extensions(); i < exts.Len(); i++ {
  83. p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))
  84. }
  85. for i, messages := 0, message.Messages(); i < messages.Len(); i++ {
  86. p.NestedType = append(p.NestedType, ToDescriptorProto(messages.Get(i)))
  87. }
  88. for i, enums := 0, message.Enums(); i < enums.Len(); i++ {
  89. p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))
  90. }
  91. for i, xranges := 0, message.ExtensionRanges(); i < xranges.Len(); i++ {
  92. xrange := xranges.Get(i)
  93. p.ExtensionRange = append(p.ExtensionRange, &descriptorpb.DescriptorProto_ExtensionRange{
  94. Start: proto.Int32(int32(xrange[0])),
  95. End: proto.Int32(int32(xrange[1])),
  96. Options: proto.Clone(message.ExtensionRangeOptions(i)).(*descriptorpb.ExtensionRangeOptions),
  97. })
  98. }
  99. for i, oneofs := 0, message.Oneofs(); i < oneofs.Len(); i++ {
  100. p.OneofDecl = append(p.OneofDecl, ToOneofDescriptorProto(oneofs.Get(i)))
  101. }
  102. for i, ranges := 0, message.ReservedRanges(); i < ranges.Len(); i++ {
  103. rrange := ranges.Get(i)
  104. p.ReservedRange = append(p.ReservedRange, &descriptorpb.DescriptorProto_ReservedRange{
  105. Start: proto.Int32(int32(rrange[0])),
  106. End: proto.Int32(int32(rrange[1])),
  107. })
  108. }
  109. for i, names := 0, message.ReservedNames(); i < names.Len(); i++ {
  110. p.ReservedName = append(p.ReservedName, string(names.Get(i)))
  111. }
  112. return p
  113. }
  114. // ToFieldDescriptorProto copies a protoreflect.FieldDescriptor into a
  115. // google.protobuf.FieldDescriptorProto message.
  116. func ToFieldDescriptorProto(field protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto {
  117. p := &descriptorpb.FieldDescriptorProto{
  118. Name: proto.String(string(field.Name())),
  119. Number: proto.Int32(int32(field.Number())),
  120. Label: descriptorpb.FieldDescriptorProto_Label(field.Cardinality()).Enum(),
  121. Options: proto.Clone(field.Options()).(*descriptorpb.FieldOptions),
  122. }
  123. if field.IsExtension() {
  124. p.Extendee = fullNameOf(field.ContainingMessage())
  125. }
  126. if field.Kind().IsValid() {
  127. p.Type = descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum()
  128. }
  129. if field.Enum() != nil {
  130. p.TypeName = fullNameOf(field.Enum())
  131. }
  132. if field.Message() != nil {
  133. p.TypeName = fullNameOf(field.Message())
  134. }
  135. if field.HasJSONName() {
  136. // A bug in older versions of protoc would always populate the
  137. // "json_name" option for extensions when it is meaningless.
  138. // When it did so, it would always use the camel-cased field name.
  139. if field.IsExtension() {
  140. p.JsonName = proto.String(strs.JSONCamelCase(string(field.Name())))
  141. } else {
  142. p.JsonName = proto.String(field.JSONName())
  143. }
  144. }
  145. if field.Syntax() == protoreflect.Proto3 && field.HasOptionalKeyword() {
  146. p.Proto3Optional = proto.Bool(true)
  147. }
  148. if field.HasDefault() {
  149. def, err := defval.Marshal(field.Default(), field.DefaultEnumValue(), field.Kind(), defval.Descriptor)
  150. if err != nil && field.DefaultEnumValue() != nil {
  151. def = string(field.DefaultEnumValue().Name()) // occurs for unresolved enum values
  152. } else if err != nil {
  153. panic(fmt.Sprintf("%v: %v", field.FullName(), err))
  154. }
  155. p.DefaultValue = proto.String(def)
  156. }
  157. if oneof := field.ContainingOneof(); oneof != nil {
  158. p.OneofIndex = proto.Int32(int32(oneof.Index()))
  159. }
  160. return p
  161. }
  162. // ToOneofDescriptorProto copies a protoreflect.OneofDescriptor into a
  163. // google.protobuf.OneofDescriptorProto message.
  164. func ToOneofDescriptorProto(oneof protoreflect.OneofDescriptor) *descriptorpb.OneofDescriptorProto {
  165. return &descriptorpb.OneofDescriptorProto{
  166. Name: proto.String(string(oneof.Name())),
  167. Options: proto.Clone(oneof.Options()).(*descriptorpb.OneofOptions),
  168. }
  169. }
  170. // ToEnumDescriptorProto copies a protoreflect.EnumDescriptor into a
  171. // google.protobuf.EnumDescriptorProto message.
  172. func ToEnumDescriptorProto(enum protoreflect.EnumDescriptor) *descriptorpb.EnumDescriptorProto {
  173. p := &descriptorpb.EnumDescriptorProto{
  174. Name: proto.String(string(enum.Name())),
  175. Options: proto.Clone(enum.Options()).(*descriptorpb.EnumOptions),
  176. }
  177. for i, values := 0, enum.Values(); i < values.Len(); i++ {
  178. p.Value = append(p.Value, ToEnumValueDescriptorProto(values.Get(i)))
  179. }
  180. for i, ranges := 0, enum.ReservedRanges(); i < ranges.Len(); i++ {
  181. rrange := ranges.Get(i)
  182. p.ReservedRange = append(p.ReservedRange, &descriptorpb.EnumDescriptorProto_EnumReservedRange{
  183. Start: proto.Int32(int32(rrange[0])),
  184. End: proto.Int32(int32(rrange[1])),
  185. })
  186. }
  187. for i, names := 0, enum.ReservedNames(); i < names.Len(); i++ {
  188. p.ReservedName = append(p.ReservedName, string(names.Get(i)))
  189. }
  190. return p
  191. }
  192. // ToEnumValueDescriptorProto copies a protoreflect.EnumValueDescriptor into a
  193. // google.protobuf.EnumValueDescriptorProto message.
  194. func ToEnumValueDescriptorProto(value protoreflect.EnumValueDescriptor) *descriptorpb.EnumValueDescriptorProto {
  195. return &descriptorpb.EnumValueDescriptorProto{
  196. Name: proto.String(string(value.Name())),
  197. Number: proto.Int32(int32(value.Number())),
  198. Options: proto.Clone(value.Options()).(*descriptorpb.EnumValueOptions),
  199. }
  200. }
  201. // ToServiceDescriptorProto copies a protoreflect.ServiceDescriptor into a
  202. // google.protobuf.ServiceDescriptorProto message.
  203. func ToServiceDescriptorProto(service protoreflect.ServiceDescriptor) *descriptorpb.ServiceDescriptorProto {
  204. p := &descriptorpb.ServiceDescriptorProto{
  205. Name: proto.String(string(service.Name())),
  206. Options: proto.Clone(service.Options()).(*descriptorpb.ServiceOptions),
  207. }
  208. for i, methods := 0, service.Methods(); i < methods.Len(); i++ {
  209. p.Method = append(p.Method, ToMethodDescriptorProto(methods.Get(i)))
  210. }
  211. return p
  212. }
  213. // ToMethodDescriptorProto copies a protoreflect.MethodDescriptor into a
  214. // google.protobuf.MethodDescriptorProto message.
  215. func ToMethodDescriptorProto(method protoreflect.MethodDescriptor) *descriptorpb.MethodDescriptorProto {
  216. p := &descriptorpb.MethodDescriptorProto{
  217. Name: proto.String(string(method.Name())),
  218. InputType: fullNameOf(method.Input()),
  219. OutputType: fullNameOf(method.Output()),
  220. Options: proto.Clone(method.Options()).(*descriptorpb.MethodOptions),
  221. }
  222. if method.IsStreamingClient() {
  223. p.ClientStreaming = proto.Bool(true)
  224. }
  225. if method.IsStreamingServer() {
  226. p.ServerStreaming = proto.Bool(true)
  227. }
  228. return p
  229. }
  230. func fullNameOf(d protoreflect.Descriptor) *string {
  231. if d == nil {
  232. return nil
  233. }
  234. if strings.HasPrefix(string(d.FullName()), unknownPrefix) {
  235. return proto.String(string(d.FullName()[len(unknownPrefix):]))
  236. }
  237. return proto.String("." + string(d.FullName()))
  238. }