main.swift 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 pathName(_ arguments: [Any?]) throws -> String {
  30. if arguments.count != 3 {
  31. throw TemplateSyntaxError("path expects 3 arguments")
  32. }
  33. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  34. else {
  35. throw TemplateSyntaxError("tag must be called with a " +
  36. "Google_Protobuf_FileDescriptorProto" +
  37. " argument, received \(arguments[0])")
  38. }
  39. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  40. else {
  41. throw TemplateSyntaxError("tag must be called with a " +
  42. "Google_Protobuf_ServiceDescriptorProto" +
  43. " argument, received \(arguments[1])")
  44. }
  45. guard let method = arguments[2] as? Google_Protobuf_MethodDescriptorProto
  46. else {
  47. throw TemplateSyntaxError("tag must be called with a " +
  48. "Google_Protobuf_MethodDescriptorProto" +
  49. " argument, received \(arguments[2])")
  50. }
  51. return "/" + protoFile.package! + "." + service.name! + "/" + method.name!
  52. }
  53. func packageServiceMethodName(_ arguments: [Any?]) throws -> String {
  54. if arguments.count != 3 {
  55. throw TemplateSyntaxError("tag expects 3 arguments")
  56. }
  57. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  58. else {
  59. throw TemplateSyntaxError("tag must be called with a " +
  60. "Google_Protobuf_FileDescriptorProto" +
  61. " argument, received \(arguments[0])")
  62. }
  63. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  64. else {
  65. throw TemplateSyntaxError("tag must be called with a " +
  66. "Google_Protobuf_ServiceDescriptorProto" +
  67. " argument, received \(arguments[1])")
  68. }
  69. guard let method = arguments[2] as? Google_Protobuf_MethodDescriptorProto
  70. else {
  71. throw TemplateSyntaxError("tag must be called with a " +
  72. "Google_Protobuf_MethodDescriptorProto" +
  73. " argument, received \(arguments[2])")
  74. }
  75. return protoFile.package!.capitalized + "_" + service.name! + method.name!
  76. }
  77. func packageServiceName(_ arguments: [Any?]) throws -> String {
  78. if arguments.count != 2 {
  79. throw TemplateSyntaxError("tag expects 2 arguments")
  80. }
  81. guard let protoFile = arguments[0] as? Google_Protobuf_FileDescriptorProto
  82. else {
  83. throw TemplateSyntaxError("tag must be called with a " +
  84. "Google_Protobuf_FileDescriptorProto" +
  85. " argument, received \(arguments[0])")
  86. }
  87. guard let service = arguments[1] as? Google_Protobuf_ServiceDescriptorProto
  88. else {
  89. throw TemplateSyntaxError("tag must be called with a " +
  90. "Google_Protobuf_ServiceDescriptorProto" +
  91. " argument, received \(arguments[1])")
  92. }
  93. return protoFile.package!.capitalized + "_" + service.name!
  94. }
  95. // Code templates use "//-" prefixes to comment-out template operators
  96. // to keep them from interfering with Swift code formatting tools.
  97. // Use this to remove them after templates have been expanded.
  98. func stripMarkers(_ code:String) -> String {
  99. let inputLines = code.components(separatedBy:"\n")
  100. var outputLines : [String] = []
  101. for line in inputLines {
  102. if line.contains("//-") {
  103. let removed = line.replacingOccurrences(of:"//-", with:"")
  104. if (removed.trimmingCharacters(in:CharacterSet.whitespaces) != "") {
  105. outputLines.append(removed)
  106. }
  107. } else {
  108. outputLines.append(line)
  109. }
  110. }
  111. return outputLines.joined(separator:"\n")
  112. }
  113. func main() throws {
  114. // initialize template engine and add custom filters
  115. let fileSystemLoader = FileSystemLoader(paths: ["templates/"])
  116. let ext = Extension()
  117. ext.registerFilter("call") { (value: Any?, arguments: [Any?]) in
  118. return try packageServiceMethodName(arguments) + "Call"
  119. }
  120. ext.registerFilter("session") { (value: Any?, arguments: [Any?]) in
  121. return try packageServiceMethodName(arguments) + "Session"
  122. }
  123. ext.registerFilter("path") { (value: Any?, arguments: [Any?]) in
  124. return try pathName(arguments)
  125. }
  126. ext.registerFilter("provider") { (value: Any?, arguments: [Any?]) in
  127. return try packageServiceName(arguments) + "Provider"
  128. }
  129. ext.registerFilter("clienterror") { (value: Any?, arguments: [Any?]) in
  130. return try packageServiceName(arguments) + "ClientError"
  131. }
  132. ext.registerFilter("servererror") { (value: Any?, arguments: [Any?]) in
  133. return try packageServiceName(arguments) + "ServerError"
  134. }
  135. ext.registerFilter("server") { (value: Any?, arguments: [Any?]) in
  136. return try packageServiceName(arguments) + "Server"
  137. }
  138. ext.registerFilter("input") { (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("output") { (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. let templateEnvironment = Environment(loader: fileSystemLoader,
  151. extensions:[ext])
  152. // initialize responses
  153. var response = Google_Protobuf_Compiler_CodeGeneratorResponse()
  154. var log = ""
  155. // read plugin input
  156. let rawRequest = try Stdin.readall()
  157. let request = try Google_Protobuf_Compiler_CodeGeneratorRequest(protobuf: rawRequest)
  158. // process each .proto file separately
  159. for protoFile in request.protoFile {
  160. // a package declaration is required
  161. guard let package = protoFile.package else {
  162. print("ERROR: no package for \(protoFile.name)")
  163. continue
  164. }
  165. // log info about the service
  166. log += "File \(protoFile.name!)\n"
  167. for service in protoFile.service {
  168. log += "Service \(service.name!)\n"
  169. for method in service.method {
  170. log += " Method \(method.name!)\n"
  171. log += " input \(method.inputType!)\n"
  172. log += " output \(method.outputType!)\n"
  173. log += " client_streaming \(method.clientStreaming!)\n"
  174. log += " server_streaming \(method.serverStreaming!)\n"
  175. }
  176. log += " Options \(service.options)\n"
  177. }
  178. // generate separate implementation files for client and server
  179. let context = ["protoFile": protoFile]
  180. do {
  181. let clientcode = try templateEnvironment.renderTemplate(name:"client.pb.swift",
  182. context: context)
  183. var clientfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  184. clientfile.name = package + ".client.pb.swift"
  185. clientfile.content = stripMarkers(clientcode)
  186. response.file.append(clientfile)
  187. let servercode = try templateEnvironment.renderTemplate(name:"server.pb.swift",
  188. context: context)
  189. var serverfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  190. serverfile.name = package + ".server.pb.swift"
  191. serverfile.content = stripMarkers(servercode)
  192. response.file.append(serverfile)
  193. } catch (let error) {
  194. log += "ERROR: \(error)\n"
  195. }
  196. }
  197. log += "\(request)"
  198. // add the logfile to the code generation response
  199. var logfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  200. logfile.name = "swiftgrpc.log"
  201. logfile.content = log
  202. response.file.append(logfile)
  203. // return everything to the caller
  204. let serializedResponse = try response.serializeProtobuf()
  205. Stdout.write(bytes: serializedResponse)
  206. }
  207. try main()