main.swift 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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("sessionname") { (value: Any?, arguments: [Any?]) in
  97. if arguments.count != 3 {
  98. throw TemplateSyntaxError("expects 3 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. guard let method = arguments[2] as? Google_Protobuf_MethodDescriptorProto
  113. else {
  114. throw TemplateSyntaxError("tag must be called with a " +
  115. "Google_Protobuf_MethodDescriptorProto" +
  116. " argument, received \(arguments[2])")
  117. }
  118. return protoFile.package!.capitalized + "_" + service.name! + method.name! + "Session"
  119. }
  120. ext.registerFilter("errorname") { (value: Any?, arguments: [Any?]) in
  121. if arguments.count != 2 {
  122. throw TemplateSyntaxError("expects 2 arguments")
  123. }
  124. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  125. else {
  126. throw TemplateSyntaxError("tag must be called with a " +
  127. "Google_Protobuf_FileDescriptorProto" +
  128. " argument, received \(arguments[0])")
  129. }
  130. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  131. else {
  132. throw TemplateSyntaxError("tag must be called with a " +
  133. "Google_Protobuf_ServiceDescriptorProto" +
  134. " argument, received \(arguments[1])")
  135. }
  136. return protoFile.package!.capitalized + "_" + service.name! + "ClientError"
  137. }
  138. ext.registerFilter("inputType") { (value: Any?) in
  139. if let value = value as? Google_Protobuf_MethodDescriptorProto {
  140. return protoMessageName(value.inputType)
  141. }
  142. throw TemplateSyntaxError("message: invalid argument \(value)")
  143. }
  144. ext.registerFilter("outputType") { (value: Any?) in
  145. if let value = value as? Google_Protobuf_MethodDescriptorProto {
  146. return protoMessageName(value.outputType)
  147. }
  148. throw TemplateSyntaxError("message: invalid argument \(value)")
  149. }
  150. ext.registerFilter("servererrorname") { (value: Any?, arguments: [Any?]) in
  151. if arguments.count != 2 {
  152. throw TemplateSyntaxError("expects 2 arguments")
  153. }
  154. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  155. else {
  156. throw TemplateSyntaxError("tag must be called with a " +
  157. "Google_Protobuf_FileDescriptorProto" +
  158. " argument, received \(arguments[0])")
  159. }
  160. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  161. else {
  162. throw TemplateSyntaxError("tag must be called with a " +
  163. "Google_Protobuf_ServiceDescriptorProto" +
  164. " argument, received \(arguments[1])")
  165. }
  166. return protoFile.package!.capitalized + "_" + service.name! + "ServerError"
  167. }
  168. let templateEnvironment = Environment(loader: fileSystemLoader,
  169. extensions:[ext])
  170. // initialize responses
  171. var response = Google_Protobuf_Compiler_CodeGeneratorResponse()
  172. var log = ""
  173. // read plugin input
  174. let rawRequest = try Stdin.readall()
  175. let request = try Google_Protobuf_Compiler_CodeGeneratorRequest(protobuf: rawRequest)
  176. // process each .proto file separately
  177. for protoFile in request.protoFile {
  178. // a package declaration is required
  179. guard let package = protoFile.package else {
  180. print("ERROR: no package")
  181. continue
  182. }
  183. // log info about the service
  184. log += "File \(protoFile.name!)\n"
  185. for service in protoFile.service {
  186. log += "Service \(service.name!)\n"
  187. for method in service.method {
  188. log += " Method \(method.name!)\n"
  189. log += " input \(method.inputType!)\n"
  190. log += " output \(method.outputType!)\n"
  191. log += " client_streaming \(method.clientStreaming!)\n"
  192. log += " server_streaming \(method.serverStreaming!)\n"
  193. }
  194. log += " Options \(service.options)\n"
  195. }
  196. // generate separate implementation files for client and server
  197. let context = ["protoFile": protoFile]
  198. do {
  199. let clientcode = try templateEnvironment.renderTemplate(name:"client.pb.swift",
  200. context: context)
  201. var clientfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  202. clientfile.name = package + ".client.pb.swift"
  203. clientfile.content = stripMarkers(clientcode)
  204. response.file.append(clientfile)
  205. let servercode = try templateEnvironment.renderTemplate(name:"server.pb.swift",
  206. context: context)
  207. var serverfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  208. serverfile.name = package + ".server.pb.swift"
  209. serverfile.content = stripMarkers(servercode)
  210. response.file.append(serverfile)
  211. } catch (let error) {
  212. log += "ERROR: \(error)\n"
  213. }
  214. }
  215. // log the entire request proto
  216. log += "\n\n\n\(request)"
  217. // add the logfile to the code generation response
  218. var logfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  219. logfile.name = "swiftgrpc.log"
  220. logfile.content = log
  221. response.file.append(logfile)
  222. // return everything to the caller
  223. let serializedResponse = try response.serializeProtobuf()
  224. Stdout.write(bytes: serializedResponse)
  225. }
  226. try main()