proto.go raw

   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  
   5  package protodesc
   6  
   7  import (
   8  	"fmt"
   9  	"strings"
  10  
  11  	"google.golang.org/protobuf/internal/encoding/defval"
  12  	"google.golang.org/protobuf/internal/strs"
  13  	"google.golang.org/protobuf/proto"
  14  	"google.golang.org/protobuf/reflect/protoreflect"
  15  
  16  	"google.golang.org/protobuf/types/descriptorpb"
  17  )
  18  
  19  // ToFileDescriptorProto copies a [protoreflect.FileDescriptor] into a
  20  // google.protobuf.FileDescriptorProto message.
  21  func ToFileDescriptorProto(file protoreflect.FileDescriptor) *descriptorpb.FileDescriptorProto {
  22  	p := &descriptorpb.FileDescriptorProto{
  23  		Name:    proto.String(file.Path()),
  24  		Options: proto.Clone(file.Options()).(*descriptorpb.FileOptions),
  25  	}
  26  	if file.Package() != "" {
  27  		p.Package = proto.String(string(file.Package()))
  28  	}
  29  	for i, imports := 0, file.Imports(); i < imports.Len(); i++ {
  30  		imp := imports.Get(i)
  31  		p.Dependency = append(p.Dependency, imp.Path())
  32  		if imp.IsPublic {
  33  			p.PublicDependency = append(p.PublicDependency, int32(i))
  34  		}
  35  	}
  36  	for i, locs := 0, file.SourceLocations(); i < locs.Len(); i++ {
  37  		loc := locs.Get(i)
  38  		l := &descriptorpb.SourceCodeInfo_Location{}
  39  		l.Path = append(l.Path, loc.Path...)
  40  		if loc.StartLine == loc.EndLine {
  41  			l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndColumn)}
  42  		} else {
  43  			l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndLine), int32(loc.EndColumn)}
  44  		}
  45  		l.LeadingDetachedComments = append([]string(nil), loc.LeadingDetachedComments...)
  46  		if loc.LeadingComments != "" {
  47  			l.LeadingComments = proto.String(loc.LeadingComments)
  48  		}
  49  		if loc.TrailingComments != "" {
  50  			l.TrailingComments = proto.String(loc.TrailingComments)
  51  		}
  52  		if p.SourceCodeInfo == nil {
  53  			p.SourceCodeInfo = &descriptorpb.SourceCodeInfo{}
  54  		}
  55  		p.SourceCodeInfo.Location = append(p.SourceCodeInfo.Location, l)
  56  
  57  	}
  58  	for i, messages := 0, file.Messages(); i < messages.Len(); i++ {
  59  		p.MessageType = append(p.MessageType, ToDescriptorProto(messages.Get(i)))
  60  	}
  61  	for i, enums := 0, file.Enums(); i < enums.Len(); i++ {
  62  		p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))
  63  	}
  64  	for i, services := 0, file.Services(); i < services.Len(); i++ {
  65  		p.Service = append(p.Service, ToServiceDescriptorProto(services.Get(i)))
  66  	}
  67  	for i, exts := 0, file.Extensions(); i < exts.Len(); i++ {
  68  		p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))
  69  	}
  70  	if syntax := file.Syntax(); syntax != protoreflect.Proto2 && syntax.IsValid() {
  71  		p.Syntax = proto.String(file.Syntax().String())
  72  	}
  73  	desc := file
  74  	if fileImportDesc, ok := file.(protoreflect.FileImport); ok {
  75  		desc = fileImportDesc.FileDescriptor
  76  	}
  77  	if file.Syntax() == protoreflect.Editions {
  78  		if editionsInterface, ok := desc.(interface{ Edition() int32 }); ok {
  79  			p.Edition = descriptorpb.Edition(editionsInterface.Edition()).Enum()
  80  		}
  81  	}
  82  	type hasOptionImports interface {
  83  		OptionImports() protoreflect.FileImports
  84  	}
  85  	if opts, ok := desc.(hasOptionImports); ok {
  86  		if optionImports := opts.OptionImports(); optionImports.Len() > 0 {
  87  			optionDeps := make([]string, optionImports.Len())
  88  			for i := range optionImports.Len() {
  89  				optionDeps[i] = optionImports.Get(i).Path()
  90  			}
  91  			p.OptionDependency = optionDeps
  92  		}
  93  	}
  94  	return p
  95  }
  96  
  97  // ToDescriptorProto copies a [protoreflect.MessageDescriptor] into a
  98  // google.protobuf.DescriptorProto message.
  99  func ToDescriptorProto(message protoreflect.MessageDescriptor) *descriptorpb.DescriptorProto {
 100  	p := &descriptorpb.DescriptorProto{
 101  		Name:    proto.String(string(message.Name())),
 102  		Options: proto.Clone(message.Options()).(*descriptorpb.MessageOptions),
 103  	}
 104  	for i, fields := 0, message.Fields(); i < fields.Len(); i++ {
 105  		p.Field = append(p.Field, ToFieldDescriptorProto(fields.Get(i)))
 106  	}
 107  	for i, exts := 0, message.Extensions(); i < exts.Len(); i++ {
 108  		p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))
 109  	}
 110  	for i, messages := 0, message.Messages(); i < messages.Len(); i++ {
 111  		p.NestedType = append(p.NestedType, ToDescriptorProto(messages.Get(i)))
 112  	}
 113  	for i, enums := 0, message.Enums(); i < enums.Len(); i++ {
 114  		p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))
 115  	}
 116  	for i, xranges := 0, message.ExtensionRanges(); i < xranges.Len(); i++ {
 117  		xrange := xranges.Get(i)
 118  		p.ExtensionRange = append(p.ExtensionRange, &descriptorpb.DescriptorProto_ExtensionRange{
 119  			Start:   proto.Int32(int32(xrange[0])),
 120  			End:     proto.Int32(int32(xrange[1])),
 121  			Options: proto.Clone(message.ExtensionRangeOptions(i)).(*descriptorpb.ExtensionRangeOptions),
 122  		})
 123  	}
 124  	for i, oneofs := 0, message.Oneofs(); i < oneofs.Len(); i++ {
 125  		p.OneofDecl = append(p.OneofDecl, ToOneofDescriptorProto(oneofs.Get(i)))
 126  	}
 127  	for i, ranges := 0, message.ReservedRanges(); i < ranges.Len(); i++ {
 128  		rrange := ranges.Get(i)
 129  		p.ReservedRange = append(p.ReservedRange, &descriptorpb.DescriptorProto_ReservedRange{
 130  			Start: proto.Int32(int32(rrange[0])),
 131  			End:   proto.Int32(int32(rrange[1])),
 132  		})
 133  	}
 134  	for i, names := 0, message.ReservedNames(); i < names.Len(); i++ {
 135  		p.ReservedName = append(p.ReservedName, string(names.Get(i)))
 136  	}
 137  	type hasVisibility interface {
 138  		Visibility() int32
 139  	}
 140  	if vis, ok := message.(hasVisibility); ok {
 141  		if visibility := vis.Visibility(); visibility > 0 {
 142  			p.Visibility = descriptorpb.SymbolVisibility(visibility).Enum()
 143  		}
 144  	}
 145  	return p
 146  }
 147  
 148  // ToFieldDescriptorProto copies a [protoreflect.FieldDescriptor] into a
 149  // google.protobuf.FieldDescriptorProto message.
 150  func ToFieldDescriptorProto(field protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto {
 151  	p := &descriptorpb.FieldDescriptorProto{
 152  		Name:    proto.String(string(field.Name())),
 153  		Number:  proto.Int32(int32(field.Number())),
 154  		Label:   descriptorpb.FieldDescriptorProto_Label(field.Cardinality()).Enum(),
 155  		Options: proto.Clone(field.Options()).(*descriptorpb.FieldOptions),
 156  	}
 157  	if field.IsExtension() {
 158  		p.Extendee = fullNameOf(field.ContainingMessage())
 159  	}
 160  	if field.Kind().IsValid() {
 161  		p.Type = descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum()
 162  	}
 163  	if field.Enum() != nil {
 164  		p.TypeName = fullNameOf(field.Enum())
 165  	}
 166  	if field.Message() != nil {
 167  		p.TypeName = fullNameOf(field.Message())
 168  	}
 169  	if field.HasJSONName() {
 170  		// A bug in older versions of protoc would always populate the
 171  		// "json_name" option for extensions when it is meaningless.
 172  		// When it did so, it would always use the camel-cased field name.
 173  		if field.IsExtension() {
 174  			p.JsonName = proto.String(strs.JSONCamelCase(string(field.Name())))
 175  		} else {
 176  			p.JsonName = proto.String(field.JSONName())
 177  		}
 178  	}
 179  	if field.Syntax() == protoreflect.Proto3 && field.HasOptionalKeyword() {
 180  		p.Proto3Optional = proto.Bool(true)
 181  	}
 182  	if field.Syntax() == protoreflect.Editions {
 183  		// Editions have no group keyword, this type is only set so that downstream users continue
 184  		// treating this as delimited encoding.
 185  		if p.GetType() == descriptorpb.FieldDescriptorProto_TYPE_GROUP {
 186  			p.Type = descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum()
 187  		}
 188  		// Editions have no required keyword, this label is only set so that downstream users continue
 189  		// treating it as required.
 190  		if p.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REQUIRED {
 191  			p.Label = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum()
 192  		}
 193  	}
 194  	if field.HasDefault() {
 195  		def, err := defval.Marshal(field.Default(), field.DefaultEnumValue(), field.Kind(), defval.Descriptor)
 196  		if err != nil && field.DefaultEnumValue() != nil {
 197  			def = string(field.DefaultEnumValue().Name()) // occurs for unresolved enum values
 198  		} else if err != nil {
 199  			panic(fmt.Sprintf("%v: %v", field.FullName(), err))
 200  		}
 201  		p.DefaultValue = proto.String(def)
 202  	}
 203  	if oneof := field.ContainingOneof(); oneof != nil {
 204  		p.OneofIndex = proto.Int32(int32(oneof.Index()))
 205  	}
 206  	return p
 207  }
 208  
 209  // ToOneofDescriptorProto copies a [protoreflect.OneofDescriptor] into a
 210  // google.protobuf.OneofDescriptorProto message.
 211  func ToOneofDescriptorProto(oneof protoreflect.OneofDescriptor) *descriptorpb.OneofDescriptorProto {
 212  	return &descriptorpb.OneofDescriptorProto{
 213  		Name:    proto.String(string(oneof.Name())),
 214  		Options: proto.Clone(oneof.Options()).(*descriptorpb.OneofOptions),
 215  	}
 216  }
 217  
 218  // ToEnumDescriptorProto copies a [protoreflect.EnumDescriptor] into a
 219  // google.protobuf.EnumDescriptorProto message.
 220  func ToEnumDescriptorProto(enum protoreflect.EnumDescriptor) *descriptorpb.EnumDescriptorProto {
 221  	p := &descriptorpb.EnumDescriptorProto{
 222  		Name:    proto.String(string(enum.Name())),
 223  		Options: proto.Clone(enum.Options()).(*descriptorpb.EnumOptions),
 224  	}
 225  	for i, values := 0, enum.Values(); i < values.Len(); i++ {
 226  		p.Value = append(p.Value, ToEnumValueDescriptorProto(values.Get(i)))
 227  	}
 228  	for i, ranges := 0, enum.ReservedRanges(); i < ranges.Len(); i++ {
 229  		rrange := ranges.Get(i)
 230  		p.ReservedRange = append(p.ReservedRange, &descriptorpb.EnumDescriptorProto_EnumReservedRange{
 231  			Start: proto.Int32(int32(rrange[0])),
 232  			End:   proto.Int32(int32(rrange[1])),
 233  		})
 234  	}
 235  	for i, names := 0, enum.ReservedNames(); i < names.Len(); i++ {
 236  		p.ReservedName = append(p.ReservedName, string(names.Get(i)))
 237  	}
 238  	type hasVisibility interface {
 239  		Visibility() int32
 240  	}
 241  	if vis, ok := enum.(hasVisibility); ok {
 242  		if visibility := vis.Visibility(); visibility > 0 {
 243  			p.Visibility = descriptorpb.SymbolVisibility(visibility).Enum()
 244  		}
 245  	}
 246  	return p
 247  }
 248  
 249  // ToEnumValueDescriptorProto copies a [protoreflect.EnumValueDescriptor] into a
 250  // google.protobuf.EnumValueDescriptorProto message.
 251  func ToEnumValueDescriptorProto(value protoreflect.EnumValueDescriptor) *descriptorpb.EnumValueDescriptorProto {
 252  	return &descriptorpb.EnumValueDescriptorProto{
 253  		Name:    proto.String(string(value.Name())),
 254  		Number:  proto.Int32(int32(value.Number())),
 255  		Options: proto.Clone(value.Options()).(*descriptorpb.EnumValueOptions),
 256  	}
 257  }
 258  
 259  // ToServiceDescriptorProto copies a [protoreflect.ServiceDescriptor] into a
 260  // google.protobuf.ServiceDescriptorProto message.
 261  func ToServiceDescriptorProto(service protoreflect.ServiceDescriptor) *descriptorpb.ServiceDescriptorProto {
 262  	p := &descriptorpb.ServiceDescriptorProto{
 263  		Name:    proto.String(string(service.Name())),
 264  		Options: proto.Clone(service.Options()).(*descriptorpb.ServiceOptions),
 265  	}
 266  	for i, methods := 0, service.Methods(); i < methods.Len(); i++ {
 267  		p.Method = append(p.Method, ToMethodDescriptorProto(methods.Get(i)))
 268  	}
 269  	return p
 270  }
 271  
 272  // ToMethodDescriptorProto copies a [protoreflect.MethodDescriptor] into a
 273  // google.protobuf.MethodDescriptorProto message.
 274  func ToMethodDescriptorProto(method protoreflect.MethodDescriptor) *descriptorpb.MethodDescriptorProto {
 275  	p := &descriptorpb.MethodDescriptorProto{
 276  		Name:       proto.String(string(method.Name())),
 277  		InputType:  fullNameOf(method.Input()),
 278  		OutputType: fullNameOf(method.Output()),
 279  		Options:    proto.Clone(method.Options()).(*descriptorpb.MethodOptions),
 280  	}
 281  	if method.IsStreamingClient() {
 282  		p.ClientStreaming = proto.Bool(true)
 283  	}
 284  	if method.IsStreamingServer() {
 285  		p.ServerStreaming = proto.Bool(true)
 286  	}
 287  	return p
 288  }
 289  
 290  func fullNameOf(d protoreflect.Descriptor) *string {
 291  	if d == nil {
 292  		return nil
 293  	}
 294  	if strings.HasPrefix(string(d.FullName()), unknownPrefix) {
 295  		return proto.String(string(d.FullName()[len(unknownPrefix):]))
 296  	}
 297  	return proto.String("." + string(d.FullName()))
 298  }
 299