parser.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package parser
  2. import (
  3. "errors"
  4. "go/token"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "unicode"
  9. "unicode/utf8"
  10. "github.com/emicklei/proto"
  11. )
  12. type (
  13. // DefaultProtoParser types an empty struct
  14. DefaultProtoParser struct{}
  15. )
  16. var ErrGoPackage = errors.New(`option go_package = "" field is not filled in`)
  17. // NewDefaultProtoParser creates a new instance
  18. func NewDefaultProtoParser() *DefaultProtoParser {
  19. return &DefaultProtoParser{}
  20. }
  21. // Parse provides to parse the proto file into a golang structure,
  22. // which is convenient for subsequent rpc generation and use
  23. func (p *DefaultProtoParser) Parse(src string, multiple ...bool) (Proto, error) {
  24. var ret Proto
  25. abs, err := filepath.Abs(src)
  26. if err != nil {
  27. return Proto{}, err
  28. }
  29. r, err := os.Open(abs)
  30. if err != nil {
  31. return ret, err
  32. }
  33. defer r.Close()
  34. parser := proto.NewParser(r)
  35. set, err := parser.Parse()
  36. if err != nil {
  37. return ret, err
  38. }
  39. var serviceList Services
  40. proto.Walk(
  41. set,
  42. proto.WithImport(func(i *proto.Import) {
  43. ret.Import = append(ret.Import, Import{Import: i})
  44. }),
  45. proto.WithMessage(func(message *proto.Message) {
  46. ret.Message = append(ret.Message, Message{Message: message})
  47. }),
  48. proto.WithPackage(func(p *proto.Package) {
  49. ret.Package = Package{Package: p}
  50. }),
  51. proto.WithService(func(service *proto.Service) {
  52. serv := Service{Service: service}
  53. elements := service.Elements
  54. for _, el := range elements {
  55. v, _ := el.(*proto.RPC)
  56. if v == nil {
  57. continue
  58. }
  59. serv.RPC = append(serv.RPC, &RPC{RPC: v})
  60. }
  61. serviceList = append(serviceList, serv)
  62. }),
  63. proto.WithOption(func(option *proto.Option) {
  64. if option.Name == "go_package" {
  65. ret.GoPackage = option.Constant.Source
  66. }
  67. }),
  68. )
  69. if err = serviceList.validate(abs, multiple...); err != nil {
  70. return ret, err
  71. }
  72. if len(ret.GoPackage) == 0 {
  73. if ret.Package.Package == nil {
  74. return ret, ErrGoPackage
  75. }
  76. ret.GoPackage = ret.Package.Name
  77. }
  78. ret.PbPackage = GoSanitized(filepath.Base(ret.GoPackage))
  79. ret.Src = abs
  80. ret.Name = filepath.Base(abs)
  81. ret.Service = serviceList
  82. return ret, nil
  83. }
  84. // GoSanitized copy from protobuf, for more information, please see google.golang.org/protobuf@v1.25.0/internal/strs/strings.go:71
  85. func GoSanitized(s string) string {
  86. // Sanitize the input to the set of valid characters,
  87. // which must be '_' or be in the Unicode L or N categories.
  88. s = strings.Map(func(r rune) rune {
  89. if unicode.IsLetter(r) || unicode.IsDigit(r) {
  90. return r
  91. }
  92. return '_'
  93. }, s)
  94. // Prepend '_' in the event of a Go keyword conflict or if
  95. // the identifier is invalid (does not start in the Unicode L category).
  96. r, _ := utf8.DecodeRuneInString(s)
  97. if token.Lookup(s).IsKeyword() || !unicode.IsLetter(r) {
  98. return "_" + s
  99. }
  100. return s
  101. }
  102. // CamelCase copy from protobuf, for more information, please see github.com/golang/protobuf@v1.4.2/protoc-gen-go/generator/generator.go:2648
  103. func CamelCase(s string) string {
  104. if s == "" {
  105. return ""
  106. }
  107. t := make([]byte, 0, 32)
  108. i := 0
  109. if s[0] == '_' {
  110. // Need a capital letter; drop the '_'.
  111. t = append(t, 'X')
  112. i++
  113. }
  114. // Invariant: if the next letter is lower case, it must be converted
  115. // to upper case.
  116. // That is, we process a word at a time, where words are marked by _ or
  117. // upper case letter. Digits are treated as words.
  118. for ; i < len(s); i++ {
  119. c := s[i]
  120. if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
  121. continue // Skip the underscore in s.
  122. }
  123. if isASCIIDigit(c) {
  124. t = append(t, c)
  125. continue
  126. }
  127. // Assume we have a letter now - if not, it's a bogus identifier.
  128. // The next word is a sequence of characters that must start upper case.
  129. if isASCIILower(c) {
  130. c ^= ' ' // Make it a capital letter.
  131. }
  132. t = append(t, c) // Guaranteed not lower case.
  133. // Accept lower case sequence that follows.
  134. for i+1 < len(s) && isASCIILower(s[i+1]) {
  135. i++
  136. t = append(t, s[i])
  137. }
  138. }
  139. return string(t)
  140. }
  141. func isASCIILower(c byte) bool {
  142. return 'a' <= c && c <= 'z'
  143. }
  144. // Is c an ASCII digit?
  145. func isASCIIDigit(c byte) bool {
  146. return '0' <= c && c <= '9'
  147. }