|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import PackagePlugin |
| 14 | + |
| 15 | +/// The name of the Swift file to generate for a particular target. |
| 16 | +let targetGeneratedSourceMapping = [ |
| 17 | + "SwiftFormat": "Pipelines+Generated.swift", |
| 18 | + "SwiftFormatConfiguration": "RuleRegistry+Generated.swift", |
| 19 | + "SwiftFormatRules": "RuleNameCache+Generated.swift", |
| 20 | +] |
| 21 | + |
| 22 | +/// A Swift Package Manager build tool that runs `generate-pipeline` to generate the format/lint |
| 23 | +/// pipelines from the current state of the rules. |
| 24 | +@main |
| 25 | +struct GeneratePipelinePlugin: BuildToolPlugin { |
| 26 | + enum Error: Swift.Error, CustomStringConvertible { |
| 27 | + /// The plugin was applied to a target that isn't supported. |
| 28 | + case notApplicableToTarget(String) |
| 29 | + |
| 30 | + var description: String { |
| 31 | + switch self { |
| 32 | + case .notApplicableToTarget(let target): |
| 33 | + return """ |
| 34 | + 'generate-pipeline-plugin' cannot be applied to '\(target)'; \ |
| 35 | + supported targets are \(targetGeneratedSourceMapping.keys) |
| 36 | + """ |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] { |
| 42 | + guard let generatedSourceName = targetGeneratedSourceMapping[target.name] else { |
| 43 | + throw Error.notApplicableToTarget(target.name) |
| 44 | + } |
| 45 | + |
| 46 | + let generatePipelineTool = try context.tool(named: "generate-pipeline") |
| 47 | + let sourcesDir = context.package.directory.appending("Sources") |
| 48 | + let outputFile = context.pluginWorkDirectory |
| 49 | + .appending("GeneratedSources") |
| 50 | + .appending(generatedSourceName) |
| 51 | + |
| 52 | + return [ |
| 53 | + .buildCommand( |
| 54 | + displayName: "Generating \(generatedSourceName) for \(target.name)", |
| 55 | + executable: generatePipelineTool.path, |
| 56 | + arguments: [ |
| 57 | + "--sources-directory", |
| 58 | + sourcesDir.string, |
| 59 | + "--output-file", |
| 60 | + outputFile.string, |
| 61 | + "--target", |
| 62 | + target.name, |
| 63 | + ], |
| 64 | + outputFiles: [outputFile] |
| 65 | + ) |
| 66 | + ] |
| 67 | + } |
| 68 | +} |
0 commit comments