proto.go 9.1 KB

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