|
| 1 | +import Foundation |
| 2 | +import PackagePlugin |
| 3 | + |
| 4 | +@main |
| 5 | +struct SourceryGenPlugin: BuildToolPlugin { |
| 6 | + func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] { |
| 7 | + let fileManager = FileManager.default |
| 8 | + |
| 9 | + let configurations: [Path] = [context.package.directory, target.directory] |
| 10 | + .map { $0.appending("sourcery.yml") } |
| 11 | + .filter { fileManager.fileExists(atPath: $0.string) } |
| 12 | + |
| 13 | + guard validate(configurations: configurations, target: target) else { |
| 14 | + return [] |
| 15 | + } |
| 16 | + |
| 17 | + fileManager.forceClean(directory: context.pluginWorkDirectory) |
| 18 | + |
| 19 | + return try configurations.map { configuration in |
| 20 | + try .swiftgen(using: configuration, context: context, target: target) |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +// MARK: - Helpers |
| 26 | + |
| 27 | +private extension SourceryGenPlugin { |
| 28 | + /// Validate the given list of configurations |
| 29 | + func validate(configurations: [Path], target: Target) -> Bool { |
| 30 | + guard !configurations.isEmpty else { |
| 31 | + Diagnostics.error(""" |
| 32 | + No SourceryGen configurations found for target \(target.name). If you would like to generate sources for this \ |
| 33 | + target include a `sourcery.yml` in the target's source directory, or include a shared `sourcery.yml` at the \ |
| 34 | + package's root. |
| 35 | + """) |
| 36 | + return false |
| 37 | + } |
| 38 | + |
| 39 | + return true |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +private extension Command { |
| 44 | + static func swiftgen(using configuration: Path, context: PluginContext, target: Target) throws -> Command { |
| 45 | + .prebuildCommand( |
| 46 | + displayName: "SourceryGen BuildTool Plugin", |
| 47 | + executable: try context.tool(named: "sourcery").path, |
| 48 | + arguments: [ |
| 49 | + "--config", |
| 50 | + configuration, |
| 51 | + "--cacheBasePath", |
| 52 | + context.pluginWorkDirectory.string |
| 53 | + ], |
| 54 | + outputFilesDirectory: context.pluginWorkDirectory |
| 55 | + ) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +private extension FileManager { |
| 60 | + /// Re-create the given directory |
| 61 | + func forceClean(directory: Path) { |
| 62 | + try? removeItem(atPath: directory.string) |
| 63 | + try? createDirectory(atPath: directory.string, withIntermediateDirectories: false) |
| 64 | + } |
| 65 | +} |
0 commit comments