2
0

plugin.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /*
  2. * Copyright 2022, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import PackagePlugin
  18. @main
  19. struct GRPCSwiftPlugin: BuildToolPlugin {
  20. /// Errors thrown by the `GRPCSwiftPlugin`
  21. enum PluginError: Error {
  22. /// Indicates that the target where the plugin was applied to was not `SourceModuleTarget`.
  23. case invalidTarget
  24. /// Indicates that the file extension of an input file was not `.proto`.
  25. case invalidInputFileExtension
  26. }
  27. /// The configuration of the plugin.
  28. struct Configuration: Codable {
  29. /// Encapsulates a single invocation of protoc.
  30. struct Invocation: Codable {
  31. /// The visibility of the generated files.
  32. enum Visibility: String, Codable {
  33. /// The generated files should have `internal` access level.
  34. case `internal`
  35. /// The generated files should have `public` access level.
  36. case `public`
  37. }
  38. /// An array of paths to `.proto` files for this invocation.
  39. var protoFiles: [String]
  40. /// The visibility of the generated files.
  41. var visibility: Visibility?
  42. /// Whether server code is generated.
  43. var server: Bool?
  44. /// Whether client code is generated.
  45. var client: Bool?
  46. /// Determines whether the casing of generated function names is kept.
  47. var keepMethodCasing: Bool?
  48. }
  49. /// The path to the `protoc` binary.
  50. ///
  51. /// If this is not set, SPM will try to find the tool itself.
  52. var protocPath: String?
  53. /// A list of invocations of `protoc` with the `GRPCSwiftPlugin`.
  54. var invocations: [Invocation]
  55. }
  56. static let configurationFileName = "grpc-swift-config.json"
  57. func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
  58. // Let's check that this is a source target
  59. guard let target = target as? SourceModuleTarget else {
  60. throw PluginError.invalidTarget
  61. }
  62. // We need to find the configuration file at the root of the target
  63. let configurationFilePath = target.directory.appending(subpath: Self.configurationFileName)
  64. let data = try Data(contentsOf: URL(fileURLWithPath: "\(configurationFilePath)"))
  65. let configuration = try JSONDecoder().decode(Configuration.self, from: data)
  66. try self.validateConfiguration(configuration)
  67. // We need to find the path of protoc and protoc-gen-grpc-swift
  68. let protocPath: Path
  69. if let configuredProtocPath = configuration.protocPath {
  70. protocPath = Path(configuredProtocPath)
  71. } else if let environmentPath = ProcessInfo.processInfo.environment["PROTOC_PATH"] {
  72. // The user set the env variable, so let's take that
  73. protocPath = Path(environmentPath)
  74. } else {
  75. // The user didn't set anything so let's try see if SPM can find a binary for us
  76. protocPath = try context.tool(named: "protoc").path
  77. }
  78. let protocGenGRPCSwiftPath = try context.tool(named: "protoc-gen-grpc-swift").path
  79. // This plugin generates its output into GeneratedSources
  80. let outputDirectory = context.pluginWorkDirectory
  81. return configuration.invocations.map { invocation in
  82. self.invokeProtoc(
  83. target: target,
  84. invocation: invocation,
  85. protocPath: protocPath,
  86. protocGenGRPCSwiftPath: protocGenGRPCSwiftPath,
  87. outputDirectory: outputDirectory
  88. )
  89. }
  90. }
  91. /// Invokes `protoc` with the given inputs
  92. ///
  93. /// - Parameters:
  94. /// - target: The plugin's target.
  95. /// - invocation: The `protoc` invocation.
  96. /// - protocPath: The path to the `protoc` binary.
  97. /// - protocGenSwiftPath: The path to the `protoc-gen-swift` binary.
  98. /// - outputDirectory: The output directory for the generated files.
  99. /// - Returns: The build command.
  100. private func invokeProtoc(
  101. target: Target,
  102. invocation: Configuration.Invocation,
  103. protocPath: Path,
  104. protocGenGRPCSwiftPath: Path,
  105. outputDirectory: Path
  106. ) -> Command {
  107. // Construct the `protoc` arguments.
  108. var protocArgs = [
  109. "--plugin=protoc-gen-grpc-swift=\(protocGenGRPCSwiftPath)",
  110. "--grpc-swift_out=\(outputDirectory)",
  111. // We include the target directory as a proto search path
  112. "-I",
  113. "\(target.directory)",
  114. ]
  115. if let visibility = invocation.visibility {
  116. protocArgs.append("--grpc-swift_opt=Visibility=\(visibility.rawValue.capitalized)")
  117. }
  118. if let generateServerCode = invocation.server {
  119. protocArgs.append("--grpc-swift_opt=Server=\(generateServerCode)")
  120. }
  121. if let generateClientCode = invocation.client {
  122. protocArgs.append("--grpc-swift_opt=Client=\(generateClientCode)")
  123. }
  124. if let keepMethodCasingOption = invocation.keepMethodCasing {
  125. protocArgs.append("--grpc-swift_opt=KeepMethodCasing=\(keepMethodCasingOption)")
  126. }
  127. var inputFiles = [Path]()
  128. var outputFiles = [Path]()
  129. for var file in invocation.protoFiles {
  130. // Append the file to the protoc args so that it is used for generating
  131. protocArgs.append("\(file)")
  132. inputFiles.append(target.directory.appending(file))
  133. // The name of the output file is based on the name of the input file.
  134. // We validated in the beginning that every file has the suffix of .proto
  135. // This means we can just drop the last 5 elements and append the new suffix
  136. file.removeLast(5)
  137. file.append("grpc.swift")
  138. let protobufOutputPath = outputDirectory.appending(file)
  139. // Add the outputPath as an output file
  140. outputFiles.append(protobufOutputPath)
  141. }
  142. // Construct the command. Specifying the input and output paths lets the build
  143. // system know when to invoke the command. The output paths are passed on to
  144. // the rule engine in the build system.
  145. return Command.buildCommand(
  146. displayName: "Generating gRPC Swift files from proto files",
  147. executable: protocPath,
  148. arguments: protocArgs,
  149. inputFiles: inputFiles + [protocGenGRPCSwiftPath],
  150. outputFiles: outputFiles
  151. )
  152. }
  153. /// Validates the configuration file for various user errors.
  154. private func validateConfiguration(_ configuration: Configuration) throws {
  155. for invocation in configuration.invocations {
  156. for protoFile in invocation.protoFiles {
  157. if !protoFile.hasSuffix(".proto") {
  158. throw PluginError.invalidInputFileExtension
  159. }
  160. }
  161. }
  162. }
  163. }