main.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright 2016 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Stencil
  15. import Foundation
  16. import SwiftProtobuf
  17. import PluginLibrary
  18. func protoMessageName(_ name :String?) -> String {
  19. guard let name = name else {
  20. return ""
  21. }
  22. let parts = name.components(separatedBy:".")
  23. if parts.count == 3 {
  24. return parts[1].capitalized + "_" + parts[2]
  25. } else {
  26. return name
  27. }
  28. }
  29. func stripMarkers(_ code:String) -> String {
  30. let inputLines = code.components(separatedBy:"\n")
  31. var outputLines : [String] = []
  32. for line in inputLines {
  33. if line.contains("//-") {
  34. let removed = line.replacingOccurrences(of:"//-", with:"")
  35. if (removed.trimmingCharacters(in:CharacterSet.whitespaces) != "") {
  36. outputLines.append(removed)
  37. }
  38. } else {
  39. outputLines.append(line)
  40. }
  41. }
  42. return outputLines.joined(separator:"\n")
  43. }
  44. func main() throws {
  45. // initialize template engine
  46. let fileSystemLoader = FileSystemLoader(paths: ["templates/"])
  47. let ext = Extension()
  48. ext.registerFilter("callname") { (value: Any?, arguments: [Any?]) in
  49. if arguments.count != 3 {
  50. throw TemplateSyntaxError("expects 3 arguments")
  51. }
  52. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  53. else {
  54. throw TemplateSyntaxError("tag must be called with a " +
  55. "Google_Protobuf_FileDescriptorProto" +
  56. " argument, received \(arguments[0])")
  57. }
  58. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  59. else {
  60. throw TemplateSyntaxError("tag must be called with a " +
  61. "Google_Protobuf_ServiceDescriptorProto" +
  62. " argument, received \(arguments[1])")
  63. }
  64. guard let method = arguments[2] as? Google_Protobuf_MethodDescriptorProto
  65. else {
  66. throw TemplateSyntaxError("tag must be called with a " +
  67. "Google_Protobuf_MethodDescriptorProto" +
  68. " argument, received \(arguments[2])")
  69. }
  70. return protoFile.package!.capitalized + "_" + service.name! + method.name! + "Call"
  71. }
  72. ext.registerFilter("callpath") { (value: Any?, arguments: [Any?]) in
  73. if arguments.count != 3 {
  74. throw TemplateSyntaxError("expects 3 arguments")
  75. }
  76. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  77. else {
  78. throw TemplateSyntaxError("tag must be called with a " +
  79. "Google_Protobuf_FileDescriptorProto" +
  80. " argument, received \(arguments[0])")
  81. }
  82. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  83. else {
  84. throw TemplateSyntaxError("tag must be called with a " +
  85. "Google_Protobuf_ServiceDescriptorProto" +
  86. " argument, received \(arguments[1])")
  87. }
  88. guard let method = arguments[2] as? Google_Protobuf_MethodDescriptorProto
  89. else {
  90. throw TemplateSyntaxError("tag must be called with a " +
  91. "Google_Protobuf_MethodDescriptorProto" +
  92. " argument, received \(arguments[2])")
  93. }
  94. return "/" + protoFile.package! + "." + service.name! + "/" + method.name!
  95. }
  96. ext.registerFilter("errorname") { (value: Any?, arguments: [Any?]) in
  97. if arguments.count != 2 {
  98. throw TemplateSyntaxError("expects 2 arguments")
  99. }
  100. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  101. else {
  102. throw TemplateSyntaxError("tag must be called with a " +
  103. "Google_Protobuf_FileDescriptorProto" +
  104. " argument, received \(arguments[0])")
  105. }
  106. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  107. else {
  108. throw TemplateSyntaxError("tag must be called with a " +
  109. "Google_Protobuf_ServiceDescriptorProto" +
  110. " argument, received \(arguments[1])")
  111. }
  112. return protoFile.package!.capitalized + "_" + service.name! + "ClientError"
  113. }
  114. ext.registerFilter("inputType") { (value: Any?) in
  115. if let value = value as? Google_Protobuf_MethodDescriptorProto {
  116. return protoMessageName(value.inputType)
  117. }
  118. throw TemplateSyntaxError("message: invalid argument \(value)")
  119. }
  120. ext.registerFilter("outputType") { (value: Any?) in
  121. if let value = value as? Google_Protobuf_MethodDescriptorProto {
  122. return protoMessageName(value.outputType)
  123. }
  124. throw TemplateSyntaxError("message: invalid argument \(value)")
  125. }
  126. let templateEnvironment = Environment(loader: fileSystemLoader,
  127. extensions:[ext])
  128. // initialize responses
  129. var response = Google_Protobuf_Compiler_CodeGeneratorResponse()
  130. var log = ""
  131. // read plugin input
  132. let rawRequest = try Stdin.readall()
  133. let request = try Google_Protobuf_Compiler_CodeGeneratorRequest(protobuf: rawRequest)
  134. // process each .proto file separately
  135. for protoFile in request.protoFile {
  136. // a package declaration is required
  137. guard let package = protoFile.package else {
  138. print("ERROR: no package")
  139. continue
  140. }
  141. // log info about the service
  142. log += "File \(protoFile.name!)\n"
  143. for service in protoFile.service {
  144. log += "Service \(service.name!)\n"
  145. for method in service.method {
  146. log += " Method \(method.name!)\n"
  147. log += " input \(method.inputType!)\n"
  148. log += " output \(method.outputType!)\n"
  149. log += " client_streaming \(method.clientStreaming!)\n"
  150. log += " server_streaming \(method.serverStreaming!)\n"
  151. }
  152. log += " Options \(service.options)\n"
  153. }
  154. // generate separate implementation files for client and server
  155. let context = ["protoFile": protoFile]
  156. do {
  157. let clientcode = try templateEnvironment.renderTemplate(name:"client.pb.swift",
  158. context: context)
  159. var clientfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  160. clientfile.name = package + ".client.pb.swift"
  161. clientfile.content = stripMarkers(clientcode)
  162. response.file.append(clientfile)
  163. let servercode = try templateEnvironment.renderTemplate(name:"server.pb.swift",
  164. context: context)
  165. var serverfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  166. serverfile.name = package + ".server.pb.swift"
  167. serverfile.content = servercode
  168. response.file.append(serverfile)
  169. } catch (let error) {
  170. log += "ERROR: \(error)\n"
  171. }
  172. }
  173. // log the entire request proto
  174. log += "\n\n\n\(request)"
  175. // add the logfile to the code generation response
  176. var logfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  177. logfile.name = "swiftgrpc.log"
  178. logfile.content = log
  179. response.file.append(logfile)
  180. // return everything to the caller
  181. let serializedResponse = try response.serializeProtobuf()
  182. Stdout.write(bytes: serializedResponse)
  183. }
  184. try main()