|
| 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 | + |
| 17 | +import Foundation |
| 18 | +import PackagePlugin |
| 19 | + |
| 20 | +@main |
| 21 | +struct GRPCSwiftPlugin: BuildToolPlugin { |
| 22 | + /// Errors thrown by the `GRPCSwiftPlugin` |
| 23 | + enum PluginError: Error { |
| 24 | + /// Indicates that the target where the plugin was applied to was not `SourceModuleTarget`. |
| 25 | + case invalidTarget |
| 26 | + /// Indicates that the file extension of an input file was not `.proto`. |
| 27 | + case invalidInputFileExtension |
| 28 | + } |
| 29 | + |
| 30 | + /// The configuration of the plugin. |
| 31 | + struct Configuration: Codable { |
| 32 | + /// Encapsulates a single invocation of protoc. |
| 33 | + struct Invocation: Codable { |
| 34 | + /// The visibility of the generated files. |
| 35 | + enum Visibility: String, Codable { |
| 36 | + /// The generated files should have `internal` access level. |
| 37 | + case `internal` |
| 38 | + /// The generated files should have `public` access level. |
| 39 | + case `public` |
| 40 | + } |
| 41 | + |
| 42 | + /// An array of paths to `.proto` files for this invocation. |
| 43 | + var protoFiles: [String] |
| 44 | + /// The visibility of the generated files. |
| 45 | + var visibility: Visibility? |
| 46 | + /// Whether server code is generated. |
| 47 | + var server: Bool? |
| 48 | + /// Whether client code is generated. |
| 49 | + var client: Bool? |
| 50 | + /// Determines whether the casing of generated function names is kept. |
| 51 | + var keepMethodCasing: Bool? |
| 52 | + } |
| 53 | + |
| 54 | + /// The path to the `protoc` binary. |
| 55 | + /// |
| 56 | + /// If this is not set, SPM will try to find the tool itself. |
| 57 | + var protocPath: String? |
| 58 | + |
| 59 | + /// A list of invocations of `protoc` with the `GRPCSwiftPlugin`. |
| 60 | + var invocations: [Invocation] |
| 61 | + } |
| 62 | + |
| 63 | + static let configurationFileName = "grpc-swift-config.json" |
| 64 | + |
| 65 | + func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] { |
| 66 | + // Let's check that this is a source target |
| 67 | + guard let target = target as? SourceModuleTarget else { |
| 68 | + throw PluginError.invalidTarget |
| 69 | + } |
| 70 | + |
| 71 | + // We need to find the configuration file at the root of the target |
| 72 | + let configurationFilePath = target.directory.appending(subpath: Self.configurationFileName) |
| 73 | + let data = try Data(contentsOf: URL(fileURLWithPath: "\(configurationFilePath)")) |
| 74 | + let configuration = try JSONDecoder().decode(Configuration.self, from: data) |
| 75 | + |
| 76 | + try self.validateConfiguration(configuration) |
| 77 | + |
| 78 | + // We need to find the path of protoc and protoc-gen-grpc-swift |
| 79 | + let protocPath: Path |
| 80 | + if let configuredProtocPath = configuration.protocPath { |
| 81 | + protocPath = Path(configuredProtocPath) |
| 82 | + } else if let environmentPath = ProcessInfo.processInfo.environment["PROTOC_PATH"] { |
| 83 | + // The user set the env variable, so let's take that |
| 84 | + protocPath = Path(environmentPath) |
| 85 | + } else { |
| 86 | + // The user didn't set anything so let's try see if SPM can find a binary for us |
| 87 | + protocPath = try context.tool(named: "protoc").path |
| 88 | + } |
| 89 | + let protocGenGRPCSwiftPath = try context.tool(named: "protoc-gen-grpc-swift").path |
| 90 | + |
| 91 | + // This plugin generates its output into GeneratedSources |
| 92 | + let outputDirectory = context.pluginWorkDirectory |
| 93 | + |
| 94 | + return configuration.invocations.map { invocation in |
| 95 | + self.invokeProtoc( |
| 96 | + target: target, |
| 97 | + invocation: invocation, |
| 98 | + protocPath: protocPath, |
| 99 | + protocGenGRPCSwiftPath: protocGenGRPCSwiftPath, |
| 100 | + outputDirectory: outputDirectory |
| 101 | + ) |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + /// Invokes `protoc` with the given inputs |
| 106 | + /// |
| 107 | + /// - Parameters: |
| 108 | + /// - target: The plugin's target. |
| 109 | + /// - invocation: The `protoc` invocation. |
| 110 | + /// - protocPath: The path to the `protoc` binary. |
| 111 | + /// - protocGenSwiftPath: The path to the `protoc-gen-swift` binary. |
| 112 | + /// - outputDirectory: The output directory for the generated files. |
| 113 | + /// - Returns: The build command. |
| 114 | + private func invokeProtoc( |
| 115 | + target: Target, |
| 116 | + invocation: Configuration.Invocation, |
| 117 | + protocPath: Path, |
| 118 | + protocGenGRPCSwiftPath: Path, |
| 119 | + outputDirectory: Path |
| 120 | + ) -> Command { |
| 121 | + // Construct the `protoc` arguments. |
| 122 | + var protocArgs = [ |
| 123 | + "--plugin=protoc-gen-grpc-swift=\(protocGenGRPCSwiftPath)", |
| 124 | + "--grpc-swift_out=\(outputDirectory)", |
| 125 | + // We include the target directory as a proto search path |
| 126 | + "-I", |
| 127 | + "\(target.directory)", |
| 128 | + ] |
| 129 | + |
| 130 | + if let visibility = invocation.visibility { |
| 131 | + protocArgs.append("--grpc-swift_opt=Visibility=\(visibility.rawValue.capitalized)") |
| 132 | + } |
| 133 | + |
| 134 | + if let generateServerCode = invocation.server { |
| 135 | + protocArgs.append("--grpc-swift_opt=Server=\(generateServerCode)") |
| 136 | + } |
| 137 | + |
| 138 | + if let generateClientCode = invocation.client { |
| 139 | + protocArgs.append("--grpc-swift_opt=Client=\(generateClientCode)") |
| 140 | + } |
| 141 | + |
| 142 | + if let keepMethodCasingOption = invocation.keepMethodCasing { |
| 143 | + protocArgs.append("--grpc-swift_opt=KeepMethodCasing=\(keepMethodCasingOption)") |
| 144 | + } |
| 145 | + |
| 146 | + var inputFiles = [Path]() |
| 147 | + var outputFiles = [Path]() |
| 148 | + |
| 149 | + for var file in invocation.protoFiles { |
| 150 | + // Append the file to the protoc args so that it is used for generating |
| 151 | + protocArgs.append("\(file)") |
| 152 | + inputFiles.append(target.directory.appending(file)) |
| 153 | + |
| 154 | + // The name of the output file is based on the name of the input file. |
| 155 | + // We validated in the beginning that every file has the suffix of .proto |
| 156 | + // This means we can just drop the last 5 elements and append the new suffix |
| 157 | + file.removeLast(5) |
| 158 | + file.append("grpc.swift") |
| 159 | + let protobufOutputPath = outputDirectory.appending(file) |
| 160 | + |
| 161 | + // Add the outputPath as an output file |
| 162 | + outputFiles.append(protobufOutputPath) |
| 163 | + } |
| 164 | + |
| 165 | + // Construct the command. Specifying the input and output paths lets the build |
| 166 | + // system know when to invoke the command. The output paths are passed on to |
| 167 | + // the rule engine in the build system. |
| 168 | + return Command.buildCommand( |
| 169 | + displayName: "Generating gRPC Swift files from proto files", |
| 170 | + executable: protocPath, |
| 171 | + arguments: protocArgs, |
| 172 | + inputFiles: inputFiles + [protocGenGRPCSwiftPath], |
| 173 | + outputFiles: outputFiles |
| 174 | + ) |
| 175 | + } |
| 176 | + |
| 177 | + /// Validates the configuration file for various user errors. |
| 178 | + private func validateConfiguration(_ configuration: Configuration) throws { |
| 179 | + for invocation in configuration.invocations { |
| 180 | + for protoFile in invocation.protoFiles { |
| 181 | + if !protoFile.hasSuffix(".proto") { |
| 182 | + throw PluginError.invalidInputFileExtension |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments