plugin.swift 9.3 KB

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