plugin.swift 9.2 KB

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