-
Notifications
You must be signed in to change notification settings - Fork 1.4k
[Commands] Initial implementation of swift package add-setting
command
#8532
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift open source project | ||
// | ||
// Copyright (c) 2025 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See http://swift.org/LICENSE.txt for license information | ||
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import ArgumentParser | ||
import Basics | ||
import CoreCommands | ||
import Foundation | ||
import PackageGraph | ||
import PackageModel | ||
import PackageModelSyntax | ||
import SwiftParser | ||
import TSCBasic | ||
import TSCUtility | ||
import Workspace | ||
|
||
extension SwiftPackageCommand { | ||
struct AddSetting: SwiftCommand { | ||
/// The Swift language setting that can be specified on the command line. | ||
enum SwiftSetting: String, Codable, ExpressibleByArgument, CaseIterable { | ||
case experimentalFeature | ||
case upcomingFeature | ||
case languageMode | ||
case strictMemorySafety | ||
} | ||
|
||
package static let configuration = CommandConfiguration( | ||
abstract: "Add a new setting to the manifest" | ||
) | ||
|
||
@OptionGroup(visibility: .hidden) | ||
var globalOptions: GlobalOptions | ||
|
||
@Option(help: "The target to add the setting to") | ||
var target: String | ||
|
||
@Option( | ||
name: .customLong("swift"), | ||
parsing: .unconditionalSingleValue, | ||
help: "The Swift language setting(s) to add. Supported settings: \(SwiftSetting.allCases.map(\.rawValue).joined(separator: ", "))" | ||
) | ||
var _swiftSettings: [String] | ||
|
||
var swiftSettings: [(SwiftSetting, String)] { | ||
get throws { | ||
var settings: [(SwiftSetting, String)] = [] | ||
for rawSetting in self._swiftSettings { | ||
let (name, value) = rawSetting.spm_split(around: "=") | ||
|
||
guard let setting = SwiftSetting(rawValue: name) else { | ||
throw ValidationError("Unknown Swift language setting: \(name)") | ||
} | ||
|
||
settings.append((setting, value ?? "")) | ||
} | ||
|
||
return settings | ||
} | ||
} | ||
|
||
func run(_ swiftCommandState: SwiftCommandState) throws { | ||
let workspace = try swiftCommandState.getActiveWorkspace() | ||
guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else { | ||
throw StringError("unknown package") | ||
} | ||
|
||
try self.applyEdits(packagePath: packagePath, workspace: workspace) | ||
} | ||
|
||
private func applyEdits( | ||
packagePath: Basics.AbsolutePath, | ||
workspace: Workspace | ||
) throws { | ||
// Load the manifest file | ||
let fileSystem = workspace.fileSystem | ||
let manifestPath = packagePath.appending(component: Manifest.filename) | ||
|
||
for (setting, value) in try self.swiftSettings { | ||
let manifestContents: ByteString | ||
do { | ||
manifestContents = try fileSystem.readFileContents(manifestPath) | ||
} catch { | ||
throw StringError("cannot find package manifest in \(manifestPath)") | ||
} | ||
|
||
// Parse the manifest. | ||
let manifestSyntax = manifestContents.withData { data in | ||
data.withUnsafeBytes { buffer in | ||
buffer.withMemoryRebound(to: UInt8.self) { buffer in | ||
Parser.parse(source: buffer) | ||
} | ||
} | ||
} | ||
|
||
let editResult: PackageEditResult | ||
|
||
switch setting { | ||
case .experimentalFeature: | ||
editResult = try AddSwiftSetting.experimentalFeature( | ||
to: self.target, | ||
name: value, | ||
manifest: manifestSyntax | ||
) | ||
case .upcomingFeature: | ||
editResult = try AddSwiftSetting.upcomingFeature( | ||
to: self.target, | ||
name: value, | ||
manifest: manifestSyntax | ||
) | ||
case .languageMode: | ||
guard let mode = SwiftLanguageVersion(string: value) else { | ||
throw ValidationError("Unknown Swift language mode: \(value)") | ||
} | ||
|
||
editResult = try AddSwiftSetting.languageMode( | ||
to: self.target, | ||
mode: mode, | ||
manifest: manifestSyntax | ||
) | ||
case .strictMemorySafety: | ||
guard value.isEmpty else { | ||
throw ValidationError("'strictMemorySafety' doesn't have an argument") | ||
} | ||
|
||
editResult = try AddSwiftSetting.strictMemorySafety( | ||
to: self.target, | ||
manifest: manifestSyntax | ||
) | ||
} | ||
|
||
try editResult.applyEdits( | ||
to: fileSystem, | ||
manifest: manifestSyntax, | ||
manifestPath: manifestPath, | ||
verbose: !self.globalOptions.logging.quiet | ||
) | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift open source project | ||
// | ||
// Copyright (c) 2025 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See http://swift.org/LICENSE.txt for license information | ||
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import Basics | ||
import PackageModel | ||
import SwiftParser | ||
import SwiftSyntax | ||
import SwiftSyntaxBuilder | ||
import struct TSCUtility.Version | ||
|
||
/// Add a swift setting to a manifest's source code. | ||
public enum AddSwiftSetting { | ||
/// The set of argument labels that can occur after the "targets" | ||
/// argument in the Package initializers. | ||
private static let argumentLabelsAfterSwiftSettings: Set<String> = [ | ||
"linkerSettings", | ||
"plugins", | ||
] | ||
|
||
public static func upcomingFeature( | ||
to target: String, | ||
name: String, | ||
manifest: SourceFileSyntax | ||
) throws -> PackageEditResult { | ||
try self.addToTarget( | ||
target, | ||
name: "enableUpcomingFeature", | ||
value: name, | ||
firstIntroduced: .v5_8, | ||
manifest: manifest | ||
) | ||
} | ||
|
||
public static func experimentalFeature( | ||
to target: String, | ||
name: String, | ||
manifest: SourceFileSyntax | ||
) throws -> PackageEditResult { | ||
try self.addToTarget( | ||
target, | ||
name: "enableExperimentalFeature", | ||
value: name, | ||
firstIntroduced: .v5_8, | ||
manifest: manifest | ||
) | ||
} | ||
|
||
public static func languageMode( | ||
to target: String, | ||
mode: SwiftLanguageVersion, | ||
manifest: SourceFileSyntax | ||
) throws -> PackageEditResult { | ||
try self.addToTarget( | ||
target, | ||
name: "swiftLanguageMode", | ||
value: mode, | ||
firstIntroduced: .v6_0, | ||
manifest: manifest | ||
) | ||
} | ||
|
||
public static func strictMemorySafety( | ||
to target: String, | ||
manifest: SourceFileSyntax | ||
) throws -> PackageEditResult { | ||
try self.addToTarget( | ||
target, name: "strictMemorySafety", | ||
value: String?.none, | ||
firstIntroduced: .v6_2, | ||
manifest: manifest | ||
) | ||
} | ||
|
||
private static func addToTarget( | ||
_ target: String, | ||
name: String, | ||
value: (some ManifestSyntaxRepresentable)?, | ||
firstIntroduced: ToolsVersion, | ||
manifest: SourceFileSyntax | ||
) throws -> PackageEditResult { | ||
try manifest.checkManifestAtLeast(firstIntroduced) | ||
|
||
guard let packageCall = manifest.findCall(calleeName: "Package") else { | ||
throw ManifestEditError.cannotFindPackage | ||
} | ||
|
||
guard let targetsArgument = packageCall.findArgument(labeled: "targets"), | ||
let targetArray = targetsArgument.expression.findArrayArgument() | ||
else { | ||
throw ManifestEditError.cannotFindTargets | ||
} | ||
|
||
guard let targetCall = FunctionCallExprSyntax.findFirst(in: targetArray, matching: { | ||
if let nameArgument = $0.findArgument(labeled: "name"), | ||
let nameLiteral = nameArgument.expression.as(StringLiteralExprSyntax.self), | ||
nameLiteral.representedLiteralValue == target | ||
{ | ||
return true | ||
} | ||
return false | ||
}) else { | ||
throw ManifestEditError.cannotFindTarget(targetName: target) | ||
} | ||
|
||
if let memberRef = targetCall.calledExpression.as(MemberAccessExprSyntax.self), | ||
memberRef.declName.baseName.text == "plugin" | ||
{ | ||
throw ManifestEditError.cannotAddSettingsToPluginTarget | ||
} | ||
|
||
let newTargetCall = if let value { | ||
try targetCall.appendingToArrayArgument( | ||
label: "swiftSettings", | ||
trailingLabels: self.argumentLabelsAfterSwiftSettings, | ||
newElement: ".\(raw: name)(\(value.asSyntax()))" | ||
) | ||
} else { | ||
try targetCall.appendingToArrayArgument( | ||
label: "swiftSettings", | ||
trailingLabels: self.argumentLabelsAfterSwiftSettings, | ||
newElement: ".\(raw: name)" | ||
) | ||
} | ||
|
||
return PackageEditResult( | ||
manifestEdits: [ | ||
.replace(targetCall, with: newTargetCall.description), | ||
] | ||
) | ||
} | ||
} | ||
|
||
extension SwiftLanguageVersion: ManifestSyntaxRepresentable { | ||
func asSyntax() -> ExprSyntax { | ||
if !Self.supportedSwiftLanguageVersions.contains(self) { | ||
return ".version(\"\(raw: rawValue)\")" | ||
} | ||
|
||
if minor == 0 { | ||
return ".v\(raw: major)" | ||
} | ||
|
||
return ".v\(raw: major)_\(raw: minor)" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What happens if the user adds the same setting a second time? And if that setting has a different value than the already added setting?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The compiler would take the last value.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did some work in #8534 to make add-dependency idempotent if possible. Doing the same sort of thing here is less important here since adding the same setting twice wont result in a package that wont build, but could be worth looking at just to keep the resulting settings collections free of dupes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I looked into that while working on that and without some support from swift-syntax to match the nodes in general we won't be able to do match...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
would we be able, at a minimum, to inform the user of the duplicate, and different settings? If this is the case, is there value in prompting the user which value they want to use?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I didn't do that because it would lead to false positive warnings since we cannot really figure out what is what so if they have the setting with different conditions we'll just keep warning about it for no reason.