plugin.swift 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. /// Determines whether the casing of generated function names is kept.
  64. var keepMethodCasing: Bool?
  65. }
  66. /// Specify the directory in which to search for
  67. /// imports. May be specified multiple times;
  68. /// directories will be searched in order.
  69. /// The target source directory is always appended
  70. /// to the import paths.
  71. var importPaths: [String]?
  72. /// The path to the `protoc` binary.
  73. ///
  74. /// If this is not set, SPM will try to find the tool itself.
  75. var protocPath: String?
  76. /// A list of invocations of `protoc` with the `GRPCSwiftPlugin`.
  77. var invocations: [Invocation]
  78. }
  79. static let configurationFileName = "grpc-swift-config.json"
  80. /// Create build commands for the given arguments
  81. /// - Parameters:
  82. /// - pluginWorkDirectory: The path of a writable directory into which the plugin or the build
  83. /// commands it constructs can write anything it wants.
  84. /// - sourceFiles: The input files that are associated with the target.
  85. /// - tool: The tool method from the context.
  86. /// - Returns: The build commands configured based on the arguments.
  87. func createBuildCommands(
  88. pluginWorkDirectory: PackagePlugin.Path,
  89. sourceFiles: FileList,
  90. tool: (String) throws -> PackagePlugin.PluginContext.Tool
  91. ) throws -> [Command] {
  92. guard let configurationFilePath = sourceFiles.first(
  93. where: {
  94. $0.path.lastComponent == Self.configurationFileName
  95. }
  96. )?.path else {
  97. throw PluginError.noConfigFound(Self.configurationFileName)
  98. }
  99. let data = try Data(contentsOf: URL(fileURLWithPath: "\(configurationFilePath)"))
  100. let configuration = try JSONDecoder().decode(Configuration.self, from: data)
  101. try self.validateConfiguration(configuration)
  102. let targetDirectory = configurationFilePath.removingLastComponent()
  103. var importPaths: [Path] = [targetDirectory]
  104. if let configuredImportPaths = configuration.importPaths {
  105. importPaths.append(contentsOf: configuredImportPaths.map { Path($0) })
  106. }
  107. // We need to find the path of protoc and protoc-gen-grpc-swift
  108. let protocPath: Path
  109. if let configuredProtocPath = configuration.protocPath {
  110. protocPath = Path(configuredProtocPath)
  111. } else if let environmentPath = ProcessInfo.processInfo.environment["PROTOC_PATH"] {
  112. // The user set the env variable, so let's take that
  113. protocPath = Path(environmentPath)
  114. } else {
  115. // The user didn't set anything so let's try see if SPM can find a binary for us
  116. protocPath = try tool("protoc").path
  117. }
  118. let protocGenGRPCSwiftPath = try tool("protoc-gen-grpc-swift").path
  119. return configuration.invocations.map { invocation in
  120. self.invokeProtoc(
  121. directory: targetDirectory,
  122. invocation: invocation,
  123. protocPath: protocPath,
  124. protocGenGRPCSwiftPath: protocGenGRPCSwiftPath,
  125. outputDirectory: pluginWorkDirectory,
  126. importPaths: importPaths
  127. )
  128. }
  129. }
  130. /// Invokes `protoc` with the given inputs
  131. ///
  132. /// - Parameters:
  133. /// - directory: The plugin's target directory.
  134. /// - invocation: The `protoc` invocation.
  135. /// - protocPath: The path to the `protoc` binary.
  136. /// - protocGenSwiftPath: The path to the `protoc-gen-swift` binary.
  137. /// - outputDirectory: The output directory for the generated files.
  138. /// - importPaths: List of paths to pass with "-I <path>" to `protoc`
  139. /// - Returns: The build command configured based on the arguments
  140. private func invokeProtoc(
  141. directory: Path,
  142. invocation: Configuration.Invocation,
  143. protocPath: Path,
  144. protocGenGRPCSwiftPath: Path,
  145. outputDirectory: Path,
  146. importPaths: [Path]
  147. ) -> Command {
  148. // Construct the `protoc` arguments.
  149. var protocArgs = [
  150. "--plugin=protoc-gen-grpc-swift=\(protocGenGRPCSwiftPath)",
  151. "--grpc-swift_out=\(outputDirectory)",
  152. ]
  153. importPaths.forEach { path in
  154. protocArgs.append("-I")
  155. protocArgs.append("\(path)")
  156. }
  157. if let visibility = invocation.visibility {
  158. protocArgs.append("--grpc-swift_opt=Visibility=\(visibility.rawValue.capitalized)")
  159. }
  160. if let generateServerCode = invocation.server {
  161. protocArgs.append("--grpc-swift_opt=Server=\(generateServerCode)")
  162. }
  163. if let generateClientCode = invocation.client {
  164. protocArgs.append("--grpc-swift_opt=Client=\(generateClientCode)")
  165. }
  166. if let keepMethodCasingOption = invocation.keepMethodCasing {
  167. protocArgs.append("--grpc-swift_opt=KeepMethodCasing=\(keepMethodCasingOption)")
  168. }
  169. var inputFiles = [Path]()
  170. var outputFiles = [Path]()
  171. for var file in invocation.protoFiles {
  172. // Append the file to the protoc args so that it is used for generating
  173. protocArgs.append("\(file)")
  174. inputFiles.append(directory.appending(file))
  175. // The name of the output file is based on the name of the input file.
  176. // We validated in the beginning that every file has the suffix of .proto
  177. // This means we can just drop the last 5 elements and append the new suffix
  178. file.removeLast(5)
  179. file.append("grpc.swift")
  180. let protobufOutputPath = outputDirectory.appending(file)
  181. // Add the outputPath as an output file
  182. outputFiles.append(protobufOutputPath)
  183. }
  184. // Construct the command. Specifying the input and output paths lets the build
  185. // system know when to invoke the command. The output paths are passed on to
  186. // the rule engine in the build system.
  187. return Command.buildCommand(
  188. displayName: "Generating gRPC Swift files from proto files",
  189. executable: protocPath,
  190. arguments: protocArgs,
  191. inputFiles: inputFiles + [protocGenGRPCSwiftPath],
  192. outputFiles: outputFiles
  193. )
  194. }
  195. /// Validates the configuration file for various user errors.
  196. private func validateConfiguration(_ configuration: Configuration) throws {
  197. for invocation in configuration.invocations {
  198. for protoFile in invocation.protoFiles {
  199. if !protoFile.hasSuffix(".proto") {
  200. throw PluginError.invalidInputFileExtension(protoFile)
  201. }
  202. }
  203. }
  204. }
  205. }
  206. extension GRPCSwiftPlugin: BuildToolPlugin {
  207. func createBuildCommands(
  208. context: PluginContext,
  209. target: Target
  210. ) async throws -> [Command] {
  211. guard let swiftTarget = target as? SwiftSourceModuleTarget else {
  212. throw PluginError.invalidTarget(target)
  213. }
  214. return try self.createBuildCommands(
  215. pluginWorkDirectory: context.pluginWorkDirectory,
  216. sourceFiles: swiftTarget.sourceFiles,
  217. tool: context.tool
  218. )
  219. }
  220. }
  221. #if canImport(XcodeProjectPlugin)
  222. import XcodeProjectPlugin
  223. extension GRPCSwiftPlugin: XcodeBuildToolPlugin {
  224. func createBuildCommands(
  225. context: XcodePluginContext,
  226. target: XcodeTarget
  227. ) throws -> [Command] {
  228. return try self.createBuildCommands(
  229. pluginWorkDirectory: context.pluginWorkDirectory,
  230. sourceFiles: target.inputFiles,
  231. tool: context.tool
  232. )
  233. }
  234. }
  235. #endif