descriptor.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2016 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 descriptor provides functions for obtaining protocol buffer
  5. // descriptors for generated Go types.
  6. //
  7. // Deprecated: Do not use. The new v2 Message interface provides direct support
  8. // for programmatically interacting with the descriptor information.
  9. package descriptor
  10. import (
  11. "bytes"
  12. "compress/gzip"
  13. "fmt"
  14. "io/ioutil"
  15. "github.com/golang/protobuf/proto"
  16. descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
  17. )
  18. // extractFile extracts a FileDescriptorProto from a gzip'd buffer.
  19. func extractFile(gz []byte) (*descriptorpb.FileDescriptorProto, error) {
  20. r, err := gzip.NewReader(bytes.NewReader(gz))
  21. if err != nil {
  22. return nil, fmt.Errorf("failed to open gzip reader: %v", err)
  23. }
  24. defer r.Close()
  25. b, err := ioutil.ReadAll(r)
  26. if err != nil {
  27. return nil, fmt.Errorf("failed to uncompress descriptor: %v", err)
  28. }
  29. fd := new(descriptorpb.FileDescriptorProto)
  30. if err := proto.Unmarshal(b, fd); err != nil {
  31. return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err)
  32. }
  33. return fd, nil
  34. }
  35. // Message is a proto.Message with a method to return its descriptor.
  36. //
  37. // Message types generated by the protocol compiler always satisfy
  38. // the Message interface.
  39. type Message interface {
  40. proto.Message
  41. Descriptor() ([]byte, []int)
  42. }
  43. // ForMessage returns a FileDescriptorProto and a DescriptorProto from within it
  44. // describing the given message.
  45. func ForMessage(msg Message) (fd *descriptorpb.FileDescriptorProto, md *descriptorpb.DescriptorProto) {
  46. gz, path := msg.Descriptor()
  47. fd, err := extractFile(gz)
  48. if err != nil {
  49. panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err))
  50. }
  51. md = fd.MessageType[path[0]]
  52. for _, i := range path[1:] {
  53. md = md.NestedType[i]
  54. }
  55. return fd, md
  56. }