plugin.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 {
  20. /// Errors thrown by the `GRPCSwiftPlugin`
  21. enum PluginError: Error, CustomStringConvertible {
  22. /// Indicates that the target where the plugin was applied to was not `SourceModuleTarget`.
  23. case invalidTarget(Target)
  24. /// Indicates that the file extension of an input file was not `.proto`.
  25. case invalidInputFileExtension(String)
  26. /// Indicates that there was no configuration file at the required location.
  27. case noConfigFound(String)
  28. var description: String {
  29. switch self {
  30. case let .invalidTarget(target):
  31. return "Expected a SwiftSourceModuleTarget but got '\(type(of: target))'."
  32. case let .invalidInputFileExtension(path):
  33. return "The input file '\(path)' does not have a '.proto' extension."
  34. case let .noConfigFound(path):
  35. return """
  36. No configuration file found named '\(path)'. The file must not be listed in the \
  37. 'exclude:' argument for the target in Package.swift.
  38. """
  39. }
  40. }
  41. }
  42. /// The configuration of the plugin.
  43. struct Configuration: Codable {
  44. /// Encapsulates a single invocation of protoc.
  45. struct Invocation: Codable {
  46. /// The visibility of the generated files.
  47. enum Visibility: String, Codable {
  48. /// The generated files should have `internal` access level.
  49. case `internal`
  50. /// The generated files should have `public` access level.
  51. case `public`
  52. /// The generated files should have `package` access level.
  53. case `package`
  54. }
  55. /// An array of paths to `.proto` files for this invocation.
  56. var protoFiles: [String]
  57. /// The visibility of the generated files.
  58. var visibility: Visibility?
  59. /// Whether server code is generated.
  60. var server: Bool?
  61. /// Whether client code is generated.
  62. var client: Bool?
  63. /// Whether reflection data is generated.
  64. var reflectionData: Bool?
  65. /// Determines whether the casing of generated function names is kept.
  66. var keepMethodCasing: Bool?
  67. /// Whether the invocation is for `grpc-swift` v2.
  68. var _V2: Bool?
  69. }
  70. /// Specify the directory in which to search for
  71. /// imports. May be specified multiple times;
  72. /// directories will be searched in order.
  73. /// The target source directory is always appended
  74. /// to the import paths.
  75. var importPaths: [String]?
  76. /// The path to the `protoc` binary.
  77. ///
  78. /// If this is not set, SPM will try to find the tool itself.
  79. var protocPath: String?
  80. /// A list of invocations of `protoc` with the `GRPCSwiftPlugin`.
  81. var invocations: [Invocation]
  82. }
  83. static let configurationFileName = "grpc-swift-config.json"
  84. /// Create build commands for the given arguments
  85. /// - Parameters:
  86. /// - pluginWorkDirectory: The path of a writable directory into which the plugin or the build
  87. /// commands it constructs can write anything it wants.
  88. /// - sourceFiles: The input files that are associated with the target.
  89. /// - tool: The tool method from the context.
  90. /// - Returns: The build commands configured based on the arguments.
  91. func createBuildCommands(
  92. pluginWorkDirectory: PackagePlugin.Path,
  93. sourceFiles: FileList,
  94. tool: (String) throws -> PackagePlugin.PluginContext.Tool
  95. ) throws -> [Command] {
  96. guard
  97. let configurationFilePath = sourceFiles.first(
  98. where: {
  99. $0.path.lastComponent == Self.configurationFileName
  100. }
  101. )?.path
  102. else {
  103. throw PluginError.noConfigFound(Self.configurationFileName)
  104. }
  105. let data = try Data(contentsOf: URL(fileURLWithPath: "\(configurationFilePath)"))
  106. let configuration = try JSONDecoder().decode(Configuration.self, from: data)
  107. try self.validateConfiguration(configuration)
  108. let targetDirectory = configurationFilePath.removingLastComponent()
  109. var importPaths: [Path] = [targetDirectory]
  110. if let configuredImportPaths = configuration.importPaths {
  111. importPaths.append(contentsOf: configuredImportPaths.map { Path($0) })
  112. }
  113. // We need to find the path of protoc and protoc-gen-grpc-swift
  114. let protocPath: Path
  115. if let configuredProtocPath = configuration.protocPath {
  116. protocPath = Path(configuredProtocPath)
  117. } else if let environmentPath = ProcessInfo.processInfo.environment["PROTOC_PATH"] {
  118. // The user set the env variable, so let's take that
  119. protocPath = Path(environmentPath)
  120. } else {
  121. // The user didn't set anything so let's try see if SPM can find a binary for us
  122. protocPath = try tool("protoc").path
  123. }
  124. let protocGenGRPCSwiftPath = try tool("protoc-gen-grpc-swift").path
  125. return configuration.invocations.map { invocation in
  126. self.invokeProtoc(
  127. directory: targetDirectory,
  128. invocation: invocation,
  129. protocPath: protocPath,
  130. protocGenGRPCSwiftPath: protocGenGRPCSwiftPath,
  131. outputDirectory: pluginWorkDirectory,
  132. importPaths: importPaths
  133. )
  134. }
  135. }
  136. /// Invokes `protoc` with the given inputs
  137. ///
  138. /// - Parameters:
  139. /// - directory: The plugin's target directory.
  140. /// - invocation: The `protoc` invocation.
  141. /// - protocPath: The path to the `protoc` binary.
  142. /// - protocGenSwiftPath: The path to the `protoc-gen-swift` binary.
  143. /// - outputDirectory: The output directory for the generated files.
  144. /// - importPaths: List of paths to pass with "-I <path>" to `protoc`.
  145. /// - Returns: The build command configured based on the arguments
  146. private func invokeProtoc(
  147. directory: Path,
  148. invocation: Configuration.Invocation,
  149. protocPath: Path,
  150. protocGenGRPCSwiftPath: Path,
  151. outputDirectory: Path,
  152. importPaths: [Path]
  153. ) -> Command {
  154. // Construct the `protoc` arguments.
  155. var protocArgs = [
  156. "--plugin=protoc-gen-grpc-swift=\(protocGenGRPCSwiftPath)",
  157. "--grpc-swift_out=\(outputDirectory)",
  158. ]
  159. importPaths.forEach { path in
  160. protocArgs.append("-I")
  161. protocArgs.append("\(path)")
  162. }
  163. if let visibility = invocation.visibility {
  164. protocArgs.append("--grpc-swift_opt=Visibility=\(visibility.rawValue.capitalized)")
  165. }
  166. if let generateServerCode = invocation.server {
  167. protocArgs.append("--grpc-swift_opt=Server=\(generateServerCode)")
  168. }
  169. if let generateClientCode = invocation.client {
  170. protocArgs.append("--grpc-swift_opt=Client=\(generateClientCode)")
  171. }
  172. if let generateReflectionData = invocation.reflectionData {
  173. protocArgs.append("--grpc-swift_opt=ReflectionData=\(generateReflectionData)")
  174. }
  175. if let keepMethodCasingOption = invocation.keepMethodCasing {
  176. protocArgs.append("--grpc-swift_opt=KeepMethodCasing=\(keepMethodCasingOption)")
  177. }
  178. if let v2 = invocation._V2 {
  179. protocArgs.append("--grpc-swift_opt=_V2=\(v2)")
  180. }
  181. var inputFiles = [Path]()
  182. var outputFiles = [Path]()
  183. for var file in invocation.protoFiles {
  184. // Append the file to the protoc args so that it is used for generating
  185. protocArgs.append("\(file)")
  186. inputFiles.append(directory.appending(file))
  187. // The name of the output file is based on the name of the input file.
  188. // We validated in the beginning that every file has the suffix of .proto
  189. // This means we can just drop the last 5 elements and append the new suffix
  190. file.removeLast(5)
  191. file.append("grpc.swift")
  192. let protobufOutputPath = outputDirectory.appending(file)
  193. // Add the outputPath as an output file
  194. outputFiles.append(protobufOutputPath)
  195. if invocation.reflectionData == true {
  196. // Remove .swift extension and add .reflection extension
  197. file.removeLast(5)
  198. file.append("reflection")
  199. let reflectionOutputPath = outputDirectory.appending(file)
  200. outputFiles.append(reflectionOutputPath)
  201. }
  202. }
  203. // Construct the command. Specifying the input and output paths lets the build
  204. // system know when to invoke the command. The output paths are passed on to
  205. // the rule engine in the build system.
  206. return Command.buildCommand(
  207. displayName: "Generating gRPC Swift files from proto files",
  208. executable: protocPath,
  209. arguments: protocArgs,
  210. inputFiles: inputFiles + [protocGenGRPCSwiftPath],
  211. outputFiles: outputFiles
  212. )
  213. }
  214. /// Validates the configuration file for various user errors.
  215. private func validateConfiguration(_ configuration: Configuration) throws {
  216. for invocation in configuration.invocations {
  217. for protoFile in invocation.protoFiles {
  218. if !protoFile.hasSuffix(".proto") {
  219. throw PluginError.invalidInputFileExtension(protoFile)
  220. }
  221. }
  222. }
  223. }
  224. }
  225. extension GRPCSwiftPlugin: BuildToolPlugin {
  226. func createBuildCommands(
  227. context: PluginContext,
  228. target: Target
  229. ) async throws -> [Command] {
  230. guard let swiftTarget = target as? SwiftSourceModuleTarget else {
  231. throw PluginError.invalidTarget(target)
  232. }
  233. return try self.createBuildCommands(
  234. pluginWorkDirectory: context.pluginWorkDirectory,
  235. sourceFiles: swiftTarget.sourceFiles,
  236. tool: context.tool
  237. )
  238. }
  239. }
  240. #if canImport(XcodeProjectPlugin)
  241. import XcodeProjectPlugin
  242. extension GRPCSwiftPlugin: XcodeBuildToolPlugin {
  243. func createBuildCommands(
  244. context: XcodePluginContext,
  245. target: XcodeTarget
  246. ) throws -> [Command] {
  247. return try self.createBuildCommands(
  248. pluginWorkDirectory: context.pluginWorkDirectory,
  249. sourceFiles: target.inputFiles,
  250. tool: context.tool
  251. )
  252. }
  253. }
  254. #endif