plugin.swift 9.8 KB

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