Skip to content
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

Enable Xcode 16 plugin to use versioned release build #109

Merged
merged 13 commits into from
Sep 3, 2024
18 changes: 18 additions & 0 deletions Package@swift-6.0.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ let package = Package(
name: "SafeDIGenerator",
targets: ["SafeDIGenerator"]
),
.plugin(
name: "InstallSafeDITool",
targets: ["InstallSafeDITool"]
),
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.0"),
Expand Down Expand Up @@ -110,6 +114,20 @@ let package = Package(
.swiftLanguageMode(.v6),
]
),
.plugin(
name: "InstallSafeDITool",
capability: .command(
intent: .custom(
verb: "safedi-release-install",
description: "Installs a release version of the SafeDITool build plugin executable."
),
permissions: [
.writeToPackageDirectory(reason: "Downloads the SafeDI release build plugin executable into your project directory."),
.allowNetworkConnections(scope: .all(ports: []), reason: "Downloads the SafeDI release build plugin executable from GitHub."),
]
),
dependencies: []
),

// Core
.target(
Expand Down
107 changes: 107 additions & 0 deletions Plugins/InstallSafeDITool/InstallCLIPluginCommand.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Distributed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import Foundation
import PackagePlugin

@main
struct InstallSafeDITool: CommandPlugin {
func performCommand(
context: PackagePlugin.PluginContext,
arguments _: [String]
) async throws {
guard let safeDIOrigin = context.package.dependencies.first(where: { $0.package.displayName == "SafeDI" })?.package.origin else {
print("No package origin found for SafeDI package")
return
}
switch safeDIOrigin {
case let .repository(url, displayVersion, _):
guard let versionMatch = try /Optional\((.*?)\)|^(.*?)$/.firstMatch(in: displayVersion),
let versionSubstring = versionMatch.output.1 ?? versionMatch.output.2
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why checking .1 as well as .2?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto in the copied code in the other plugin

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm falling back to a version with no surrounding Optional(...) in case this gets fixed. .1 gets us the optional match. .2 gets us the match without the optional.

else {
print("could not extract version for SafeDI")
return
}
let version = String(versionSubstring)
let safediFolder = context.package.directoryURL.appending(
component: ".safedi"
)
let expectedToolFolder = safediFolder.appending(
component: version
)
let expectedToolLocation = expectedToolFolder.appending(component: "safeditool")

guard let url = URL(string: url)?.deletingPathExtension() else {
print("No package url found for SafeDI package")
return
}
#if arch(arm64)
let toolName = "SafeDITool-arm64"
#elseif arch(x86_64)
let toolName = "SafeDITool-x86_64"
#else
print("Unexpected architecture type")
return
#endif

let downloadURL = url.appending(
components: "releases",
"download",
version,
toolName
)
let (downloadedURL, _) = try await URLSession.shared.download(
for: URLRequest(url: downloadURL)
)
let downloadedFileAttributes = try FileManager.default.attributesOfItem(atPath: downloadedURL.path())
guard let currentPermissions = downloadedFileAttributes[.posixPermissions] as? NSNumber,
// Add executable attributes to the downloaded file.
chmod(downloadedURL.path(), mode_t(currentPermissions.uint16Value | S_IXUSR | S_IXGRP | S_IXOTH)) == 0
else {
print("Failed to make downloaded file executable")
return
}
try FileManager.default.createDirectory(
at: expectedToolFolder,
withIntermediateDirectories: true
)
try FileManager.default.moveItem(
at: downloadedURL,
to: expectedToolLocation
)
let gitIgnoreLocation = safediFolder.appending(component: ".gitignore")
if !FileManager.default.fileExists(atPath: gitIgnoreLocation.path()) {
try """
*/\(expectedToolLocation.lastPathComponent)
""".write(
to: gitIgnoreLocation,
atomically: true,
encoding: .utf8
)
}

case .registry, .root, .local:
fallthrough

@unknown default:
print("Cannot download SafeDITool from \(safeDIOrigin)")
}
}
}
108 changes: 93 additions & 15 deletions Plugins/SafeDIGenerator/SafeDIGenerateDependencyTree.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
// Distributed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Comment on lines +1 to +19
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops. this header should always have been here


import Foundation
import PackagePlugin

Expand Down Expand Up @@ -39,16 +59,32 @@ struct SafeDIGenerateDependencyTree: BuildToolPlugin {
outputSwiftFile.path(),
]

let toolPath: URL = if FileManager.default.fileExists(atPath: Self.armMacBrewInstallLocation) {
// SafeDITool has been installed via homebrew on an ARM Mac.
URL(filePath: Self.armMacBrewInstallLocation)
} else if FileManager.default.fileExists(atPath: Self.intelMacBrewInstallLocation) {
// SafeDITool has been installed via homebrew on an Intel Mac.
URL(filePath: Self.intelMacBrewInstallLocation)
let downloadedToolLocation = context.downloadedToolLocation
if context.hasSafeDIFolder, downloadedToolLocation == nil {
Diagnostics.error("""
\(context.safediFolder.path()) exists, but there is no SafeDITool binary for this release present.

To download the current release SafeDITool binary, run:
\tswift package --package-path \(context.package.directoryURL.path()) --allow-network-connections all --allow-writing-to-package-directory safedi-release-install

To use a debug SafeDITool binary instead, remove the `.safedi` directory by running:
\trm -rf \(context.safediFolder.path())
""")
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what the error looks like in practice:
IMG_9199

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there is a .safedi/ directory at the package root, I'm taking that to mean that the user intended to be using a release version of SafeDITool. Users will likely enter this state after installing SafeDITool, then bumping the SafeDI version they are using.

} else if downloadedToolLocation == nil {
Diagnostics.warning("""
Using a debug SafeDITool binary, which is 15x slower than a release SafeDITool binary.

To download the current release SafeDITool binary, run:
\tswift package --package-path \(context.package.directoryURL.path()) --allow-network-connections all --allow-writing-to-package-directory safedi-release-install
""")
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning shows up nicely too:
IMG_6124

}

let toolLocation = if let downloadedToolLocation {
downloadedToolLocation
} else {
// Fall back to the just-in-time built tool.
try context.tool(named: "SafeDITool").url
}

#else
let outputSwiftFile = context.pluginWorkDirectory.appending(subpath: "SafeDI.swift")
// Swift Package Plugins do not (as of Swift 5.9) allow for
Expand Down Expand Up @@ -79,12 +115,14 @@ struct SafeDIGenerateDependencyTree: BuildToolPlugin {
outputSwiftFile.string,
]

let toolPath: PackagePlugin.Path = if FileManager.default.fileExists(atPath: Self.armMacBrewInstallLocation) {
let armMacBrewInstallLocation = "/opt/homebrew/bin/safeditool"
let intelMacBrewInstallLocation = "/usr/local/bin/safeditool"
let toolLocation: PackagePlugin.Path = if FileManager.default.fileExists(atPath: armMacBrewInstallLocation) {
// SafeDITool has been installed via homebrew on an ARM Mac.
PackagePlugin.Path(Self.armMacBrewInstallLocation)
} else if FileManager.default.fileExists(atPath: Self.intelMacBrewInstallLocation) {
PackagePlugin.Path(armMacBrewInstallLocation)
} else if FileManager.default.fileExists(atPath: intelMacBrewInstallLocation) {
// SafeDITool has been installed via homebrew on an Intel Mac.
PackagePlugin.Path(Self.intelMacBrewInstallLocation)
PackagePlugin.Path(intelMacBrewInstallLocation)
} else {
// Fall back to the just-in-time built tool.
try context.tool(named: "SafeDITool").path
Expand All @@ -94,17 +132,14 @@ struct SafeDIGenerateDependencyTree: BuildToolPlugin {
return [
.buildCommand(
displayName: "SafeDIGenerateDependencyTree",
executable: toolPath,
executable: toolLocation,
arguments: arguments,
environment: [:],
inputFiles: targetSwiftFiles + dependenciesSourceFiles,
outputFiles: [outputSwiftFile]
),
]
}

private static let armMacBrewInstallLocation = "/opt/homebrew/bin/safeditool"
private static let intelMacBrewInstallLocation = "/usr/local/bin/safeditool"
}

extension Target {
Expand Down Expand Up @@ -257,3 +292,46 @@ extension Data {
#endif
}
}

#if compiler(>=6.0)
extension PackagePlugin.PluginContext {
var safeDIVersion: String? {
guard let safeDIOrigin = package.dependencies.first(where: { $0.package.displayName == "SafeDI" })?.package.origin else {
return nil
}
switch safeDIOrigin {
case let .repository(_, displayVersion, _):
guard let versionMatch = try? /Optional\((.*?)\)|^(.*?)$/.firstMatch(in: displayVersion),
let version = versionMatch.output.1 ?? versionMatch.output.2
else {
return nil
}
return String(version)
case .registry, .root, .local:
fallthrough
@unknown default:
return nil
}
}

var hasSafeDIFolder: Bool {
FileManager.default.fileExists(atPath: safediFolder.path())
}

var safediFolder: URL {
package.directoryURL.appending(
component: ".safedi"
)
}

var downloadedToolLocation: URL? {
guard let safeDIVersion else { return nil }
let location = safediFolder.appending(
components: safeDIVersion,
"safeditool"
)
guard FileManager.default.fileExists(atPath: location.path()) else { return nil }
return location
}
}
#endif