main.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. /*
  2. *
  3. * Copyright 2017, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. import Foundation
  34. import SwiftProtobuf
  35. import PluginLibrary
  36. import Stencil
  37. import PathKit
  38. func Log(_ message : String) {
  39. FileHandle.standardError.write((message + "\n").data(using:.utf8)!)
  40. }
  41. // Code templates use "//-" prefixes to comment-out template operators
  42. // to keep them from interfering with Swift code formatting tools.
  43. // Use this to remove them after templates have been expanded.
  44. func stripMarkers(_ code:String) -> String {
  45. let inputLines = code.components(separatedBy:"\n")
  46. var outputLines : [String] = []
  47. for line in inputLines {
  48. if line.contains("//-") {
  49. let removed = line.replacingOccurrences(of:"//-", with:"")
  50. if (removed.trimmingCharacters(in:CharacterSet.whitespaces) != "") {
  51. outputLines.append(removed)
  52. }
  53. } else {
  54. outputLines.append(line)
  55. }
  56. }
  57. return outputLines.joined(separator:"\n")
  58. }
  59. func main() throws {
  60. // initialize template engine and add custom filters
  61. let templateEnvironment = Environment(loader: InternalLoader(),
  62. extensions:[GRPCFilterExtension()])
  63. // initialize responses
  64. var response = Google_Protobuf_Compiler_CodeGeneratorResponse()
  65. var log = ""
  66. // read plugin input
  67. let rawRequest = try Stdin.readall()
  68. let request = try Google_Protobuf_Compiler_CodeGeneratorRequest(serializedData: rawRequest)
  69. var generatedFileNames = Set<String>()
  70. // process each .proto file separately
  71. for protoFile in request.protoFile {
  72. let file = FileDescriptor(proto:protoFile)
  73. // a package declaration is required
  74. let package = file.package
  75. guard package != "" else {
  76. print("ERROR: no package for \(file.name)")
  77. continue
  78. }
  79. // log info about the service
  80. log += "File \(file.name)\n"
  81. for service in file.service {
  82. log += "Service \(service.name)\n"
  83. for method in service.method {
  84. log += " Method \(method.name)\n"
  85. log += " input \(method.inputType)\n"
  86. log += " output \(method.outputType)\n"
  87. log += " client_streaming \(method.clientStreaming)\n"
  88. log += " server_streaming \(method.serverStreaming)\n"
  89. }
  90. }
  91. if file.service.count > 0 {
  92. // generate separate implementation files for client and server
  93. let context : [String:Any] = ["file": file]
  94. do {
  95. let clientFileName = package + ".client.pb.swift"
  96. if !generatedFileNames.contains(clientFileName) {
  97. generatedFileNames.insert(clientFileName)
  98. let clientcode = try templateEnvironment.renderTemplate(name:"client.pb.swift",
  99. context: context)
  100. var clientfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  101. clientfile.name = clientFileName
  102. clientfile.content = stripMarkers(clientcode)
  103. response.file.append(clientfile)
  104. }
  105. let serverFileName = package + ".server.pb.swift"
  106. if !generatedFileNames.contains(serverFileName) {
  107. generatedFileNames.insert(serverFileName)
  108. let servercode = try templateEnvironment.renderTemplate(name:"server.pb.swift",
  109. context: context)
  110. var serverfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  111. serverfile.name = serverFileName
  112. serverfile.content = stripMarkers(servercode)
  113. response.file.append(serverfile)
  114. }
  115. } catch (let error) {
  116. Log("ERROR \(error)")
  117. log += "ERROR: \(error)\n"
  118. }
  119. }
  120. }
  121. log += "\(request)"
  122. // add the logfile to the code generation response
  123. var logfile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
  124. logfile.name = "swiftgrpc.log"
  125. logfile.content = log
  126. response.file.append(logfile)
  127. // return everything to the caller
  128. let serializedResponse = try response.serializedData()
  129. Stdout.write(bytes: serializedResponse)
  130. }
  131. do {
  132. try main()
  133. } catch (let error) {
  134. Log("ERROR: \(error)")
  135. }