|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2024 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See http://swift.org/LICENSE.txt for license information |
| 9 | +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import SwiftParser |
| 14 | +import SwiftSyntax |
| 15 | +import SwiftSyntaxBuilder |
| 16 | + |
| 17 | +/// Add a plugin usage to a particular target in the manifest's source |
| 18 | +/// code. |
| 19 | +public struct AddPluginUsage: ManifestEditRefactoringProvider { |
| 20 | + public struct Context { |
| 21 | + public let targetName: String |
| 22 | + public let pluginUsage: TargetDescription.PluginUsage |
| 23 | + |
| 24 | + public init(targetName: String, pluginUsage: TargetDescription.PluginUsage) { |
| 25 | + self.targetName = targetName |
| 26 | + self.pluginUsage = pluginUsage |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + /// The set of argument labels that can occur after the "plugins" |
| 31 | + /// argument in the Target initializers. (There aren't any right now) |
| 32 | + /// |
| 33 | + /// TODO: Could we generate this from the the PackageDescription module, so |
| 34 | + /// we don't have keep it up-to-date manually? |
| 35 | + private static let argumentLabelsAfterPluginUsages: Set<String> = [] |
| 36 | + |
| 37 | + /// Produce the set of source edits needed to add the given package |
| 38 | + /// dependency to the given manifest file. |
| 39 | + public static func manifestRefactor( |
| 40 | + syntax manifest: SourceFileSyntax, |
| 41 | + in context: Context |
| 42 | + ) throws -> PackageEditResult { |
| 43 | + let targetName = context.targetName |
| 44 | + let pluginUsage = context.pluginUsage |
| 45 | + |
| 46 | + guard let packageCall = manifest.findCall(calleeName: "Package") else { |
| 47 | + throw ManifestEditError.cannotFindPackage |
| 48 | + } |
| 49 | + |
| 50 | + // Find the target to be modified. |
| 51 | + let targetCall = try packageCall.findManifestTargetCall(targetName: targetName) |
| 52 | + |
| 53 | + let newTargetCall = try targetCall.appendingToArrayArgument( |
| 54 | + label: "plugins", |
| 55 | + trailingLabels: Self.argumentLabelsAfterPluginUsages, |
| 56 | + newElement: pluginUsage.asSyntax() |
| 57 | + ) |
| 58 | + |
| 59 | + return PackageEditResult( |
| 60 | + manifestEdits: [ |
| 61 | + .replace(targetCall, with: newTargetCall.description) |
| 62 | + ] |
| 63 | + ) |
| 64 | + } |
| 65 | +} |
0 commit comments