Skip to content

[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 1 commit into from
Apr 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Sources/Commands/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ add_library(Commands
PackageCommands/AddProduct.swift
PackageCommands/AddTarget.swift
PackageCommands/AddTargetDependency.swift
PackageCommands/AddSetting.swift
PackageCommands/APIDiff.swift
PackageCommands/ArchiveSource.swift
PackageCommands/CompletionCommand.swift
Expand Down
148 changes: 148 additions & 0 deletions Sources/Commands/PackageCommands/AddSetting.swift
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(
Copy link
Contributor

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?

Copy link
Contributor Author

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.

Copy link
Contributor

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.

Copy link
Contributor Author

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...

Copy link
Contributor

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?

Copy link
Contributor Author

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.

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
)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public struct SwiftPackageCommand: AsyncParsableCommand {
AddProduct.self,
AddTarget.self,
AddTargetDependency.self,
AddSetting.self,
Clean.self,
PurgeCache.self,
Reset.self,
Expand Down
154 changes: 154 additions & 0 deletions Sources/PackageModelSyntax/AddSwiftSetting.swift
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)"
}
}
1 change: 1 addition & 0 deletions Sources/PackageModelSyntax/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
add_library(PackageModelSyntax
AddPackageDependency.swift
AddProduct.swift
AddSwiftSetting.swift
AddTarget.swift
AddTargetDependency.swift
ManifestEditError.swift
Expand Down
18 changes: 14 additions & 4 deletions Sources/PackageModelSyntax/ManifestEditError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ package enum ManifestEditError: Error {
case cannotFindTargets
case cannotFindTarget(targetName: String)
case cannotFindArrayLiteralArgument(argumentName: String, node: Syntax)
case oldManifest(ToolsVersion)
case oldManifest(ToolsVersion, expected: ToolsVersion)
case cannotAddSettingsToPluginTarget
}

extension ToolsVersion {
Expand All @@ -41,8 +42,10 @@ extension ManifestEditError: CustomStringConvertible {
"unable to find target named '\(name)' in package"
case .cannotFindArrayLiteralArgument(argumentName: let name, node: _):
"unable to find array literal for '\(name)' argument"
case .oldManifest(let version):
"package manifest version \(version) is too old: please update to manifest version \(ToolsVersion.minimumManifestEditVersion) or newer"
case .oldManifest(let version, let expectedVersion):
"package manifest version \(version) is too old: please update to manifest version \(expectedVersion) or newer"
case .cannotAddSettingsToPluginTarget:
"plugin targets do not support settings"
}
}
}
Expand All @@ -53,7 +56,14 @@ extension SourceFileSyntax {
func checkEditManifestToolsVersion() throws {
let toolsVersion = try ToolsVersionParser.parse(utf8String: description)
if toolsVersion < ToolsVersion.minimumManifestEditVersion {
throw ManifestEditError.oldManifest(toolsVersion)
throw ManifestEditError.oldManifest(toolsVersion, expected: ToolsVersion.minimumManifestEditVersion)
}
}

func checkManifestAtLeast(_ version: ToolsVersion) throws {
let toolsVersion = try ToolsVersionParser.parse(utf8String: description)
if toolsVersion < version {
throw ManifestEditError.oldManifest(toolsVersion, expected: version)
}
}
}
Loading