|
| 1 | +import PackagePlugin |
| 2 | +import struct Foundation.URL |
| 3 | + |
| 4 | +@main |
| 5 | +struct graphql_generator: BuildToolPlugin { |
| 6 | + /// Entry point for creating build commands for targets in Swift packages. |
| 7 | + func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] { |
| 8 | + // This plugin only runs for package targets that can have source files. |
| 9 | + guard let sourceFiles = target.sourceModule?.sourceFiles else { return [] } |
| 10 | + |
| 11 | + // Find the code generator tool to run (replace this with the actual one). |
| 12 | + let generatorTool = try context.tool(named: "my-code-generator") |
| 13 | + |
| 14 | + // Construct a build command for each source file with a particular suffix. |
| 15 | + return sourceFiles.map(\.url).compactMap { |
| 16 | + createBuildCommand(for: $0, in: context.pluginWorkDirectoryURL, with: generatorTool.url) |
| 17 | + } |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +#if canImport(XcodeProjectPlugin) |
| 22 | +import XcodeProjectPlugin |
| 23 | + |
| 24 | +extension graphql_generator: XcodeBuildToolPlugin { |
| 25 | + // Entry point for creating build commands for targets in Xcode projects. |
| 26 | + func createBuildCommands(context: XcodePluginContext, target: XcodeTarget) throws -> [Command] { |
| 27 | + // Find the code generator tool to run (replace this with the actual one). |
| 28 | + let generatorTool = try context.tool(named: "my-code-generator") |
| 29 | + |
| 30 | + // Construct a build command for each source file with a particular suffix. |
| 31 | + return target.inputFiles.map(\.url).compactMap { |
| 32 | + createBuildCommand(for: $0, in: context.pluginWorkDirectoryURL, with: generatorTool.url) |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +#endif |
| 38 | + |
| 39 | +extension graphql_generator { |
| 40 | + /// Shared function that returns a configured build command if the input files is one that should be processed. |
| 41 | + func createBuildCommand(for inputPath: URL, in outputDirectoryPath: URL, with generatorToolPath: URL) -> Command? { |
| 42 | + // Skip any file that doesn't have the extension we're looking for (replace this with the actual one). |
| 43 | + guard inputPath.pathExtension == "my-input-suffix" else { return .none } |
| 44 | + |
| 45 | + // Return a command that will run during the build to generate the output file. |
| 46 | + let inputName = inputPath.lastPathComponent |
| 47 | + let outputName = inputPath.deletingPathExtension().lastPathComponent + ".swift" |
| 48 | + let outputPath = outputDirectoryPath.appendingPathComponent(outputName) |
| 49 | + return .buildCommand( |
| 50 | + displayName: "Generating \(outputName) from \(inputName)", |
| 51 | + executable: generatorToolPath, |
| 52 | + arguments: ["\(inputPath)", "-o", "\(outputPath)"], |
| 53 | + inputFiles: [inputPath], |
| 54 | + outputFiles: [outputPath] |
| 55 | + ) |
| 56 | + } |
| 57 | +} |
0 commit comments