main.swift 8.4 KB

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