xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / PackLib / Packer.swift
Packer.swift390 lines · 17.1 KiBRaw
| 1 | import Foundation |
| 2 | import XUtils |
| 3 | import Subprocess |
| 4 | |
| 5 | public struct Packer: Sendable { |
| 6 | public let buildSettings: BuildSettings |
| 7 | public let plan: Plan |
| 8 | |
| 9 | public init(buildSettings: BuildSettings, plan: Plan) { |
| 10 | self.plan = plan |
| 11 | self.buildSettings = buildSettings |
| 12 | } |
| 13 | |
| 14 | private func build() async throws { |
| 15 | let xtoolDir = URL(fileURLWithPath: "xtool") |
| 16 | let packageDir = xtoolDir.appendingPathComponent(".xtool-tmp") |
| 17 | try? FileManager.default.removeItem(at: packageDir) |
| 18 | try FileManager.default.createDirectory(at: packageDir, withIntermediateDirectories: true) |
| 19 | |
| 20 | if URL(fileURLWithPath: "Packages").dirExists { |
| 21 | try FileManager.default.createSymbolicLink( |
| 22 | atPath: packageDir.appendingPathComponent("Packages").path, |
| 23 | withDestinationPath: "../../Packages" |
| 24 | ) |
| 25 | } |
| 26 | |
| 27 | let packageSwift = packageDir.appendingPathComponent("Package.swift") |
| 28 | let contents = """ |
| 29 | // swift-tools-version: 6.0 |
| 30 | import PackageDescription |
| 31 | let package = Package( |
| 32 | name: "\(plan.app.product)-Builder", |
| 33 | platforms: [ |
| 34 | .iOS("\(plan.app.deploymentTarget)"), |
| 35 | ], |
| 36 | dependencies: [ |
| 37 | .package(name: "RootPackage", path: "../.."), |
| 38 | ], |
| 39 | targets: [ |
| 40 | \( |
| 41 | plan.allProducts.map { |
| 42 | """ |
| 43 | .executableTarget( |
| 44 | name: "\($0.targetName)", |
| 45 | dependencies: [ |
| 46 | .product(name: "\($0.product)", package: "RootPackage"), |
| 47 | ], |
| 48 | linkerSettings: \($0.linkerSettings) |
| 49 | ) |
| 50 | """ |
| 51 | } |
| 52 | .joined(separator: ",\n") |
| 53 | ) |
| 54 | ] |
| 55 | )\n |
| 56 | """ |
| 57 | try Data(contents.utf8).write(to: packageSwift) |
| 58 | |
| 59 | for product in plan.allProducts { |
| 60 | let sources: URL = packageDir.appendingPathComponent("Sources/\(product.targetName)", isDirectory: true) |
| 61 | try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true) |
| 62 | try Data().write(to: sources.appendingPathComponent("stub.c", isDirectory: false)) |
| 63 | } |
| 64 | |
| 65 | let buildConfig = try await buildSettings |
| 66 | .withPackagePath(packageDir.path) |
| 67 | .swiftPMInvocation( |
| 68 | forTool: "build", |
| 69 | arguments: [ |
| 70 | "--scratch-path", ".build", |
| 71 | // resolving can cause SwiftPM to overwrite the root package deps |
| 72 | // with just the deps needed for the builder package (which is to |
| 73 | // say, any "dev dependencies" of the root package may be removed.) |
| 74 | // fortunately we've already resolved the root package by this point |
| 75 | // in order to dump the plan, so we can skip resolution here to skirt |
| 76 | // the issue. |
| 77 | "--disable-automatic-resolution", |
| 78 | ], |
| 79 | ) |
| 80 | try await Subprocess.run( |
| 81 | buildConfig, |
| 82 | output: .currentStandardOutput, |
| 83 | error: .currentStandardError, |
| 84 | ) |
| 85 | .checkSuccess() |
| 86 | } |
| 87 | |
| 88 | public func pack() async throws -> URL { |
| 89 | try await build() |
| 90 | |
| 91 | let output = try TemporaryDirectory(name: "\(plan.app.product).app") |
| 92 | |
| 93 | let outputURL = output.url |
| 94 | |
| 95 | let binPath: String |
| 96 | switch buildSettings.buildSystem { |
| 97 | case .swiftPM: |
| 98 | binPath = "\(buildSettings.triple)/\(buildSettings.configuration.rawValue)" |
| 99 | case .swiftBuild: |
| 100 | let platformName = buildSettings.triple.contains("simulator") ? "iphonesimulator" : "iphoneos" |
| 101 | binPath = "out/Products/\(buildSettings.configuration.swiftBuildValue)-\(platformName)" |
| 102 | } |
| 103 | let binDir = URL( |
| 104 | fileURLWithPath: ".build/\(binPath)", |
| 105 | isDirectory: true |
| 106 | ) |
| 107 | |
| 108 | try await withThrowingTaskGroup(of: Void.self) { group in |
| 109 | for product in plan.allProducts { |
| 110 | try pack( |
| 111 | product: product, |
| 112 | binDir: binDir, |
| 113 | outputURL: product.directory(inApp: outputURL), |
| 114 | &group |
| 115 | ) |
| 116 | } |
| 117 | |
| 118 | while !group.isEmpty { |
| 119 | do { |
| 120 | try await group.next() |
| 121 | } catch is CancellationError { |
| 122 | // continue |
| 123 | } catch { |
| 124 | group.cancelAll() |
| 125 | throw error |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | let dest = URL(fileURLWithPath: "xtool").appendingPathComponent(outputURL.lastPathComponent) |
| 131 | try? FileManager.default.removeItem(at: dest) |
| 132 | try output.persist(at: dest) |
| 133 | return dest |
| 134 | } |
| 135 | |
| 136 | @Sendable private func pack( |
| 137 | product: Plan.Product, |
| 138 | binDir: URL, |
| 139 | outputURL: URL, |
| 140 | _ group: inout ThrowingTaskGroup<Void, Error> |
| 141 | ) throws { |
| 142 | @Sendable func packFileToRoot(srcName: String) async throws { |
| 143 | let srcURL = URL(fileURLWithPath: srcName) |
| 144 | let destURL = outputURL.appendingPathComponent(srcURL.lastPathComponent) |
| 145 | try FileManager.default.copyItem(at: srcURL, to: destURL) |
| 146 | |
| 147 | try Task.checkCancellation() |
| 148 | } |
| 149 | |
| 150 | @Sendable func packFile(srcName: String, dstName: String? = nil, sign: Bool = false) async throws { |
| 151 | let srcURL = URL(fileURLWithPath: srcName, relativeTo: binDir) |
| 152 | let dstURL = URL(fileURLWithPath: dstName ?? srcURL.lastPathComponent, relativeTo: outputURL) |
| 153 | try? FileManager.default.createDirectory(at: dstURL.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 154 | try FileManager.default.copyItem(at: srcURL, to: dstURL) |
| 155 | |
| 156 | try Task.checkCancellation() |
| 157 | } |
| 158 | |
| 159 | // Ensure output directory is available |
| 160 | try? FileManager.default.createDirectory(at: outputURL, withIntermediateDirectories: true) |
| 161 | |
| 162 | for command in product.resources { |
| 163 | group.addTask { |
| 164 | switch command { |
| 165 | case .bundle(let package, let target): |
| 166 | try await packFile(srcName: "\(package)_\(target).bundle") |
| 167 | case .binaryTarget(let name): |
| 168 | let src = URL(fileURLWithPath: "\(name).framework/\(name)", relativeTo: binDir) |
| 169 | let magic = Data("!<arch>\n".utf8) |
| 170 | let thinMagic = Data("!<thin>\n".utf8) |
| 171 | guard let bytes = try? FileHandle(forReadingFrom: src).read(upToCount: magic.count) else { |
| 172 | // if we can't find the binary, it might be a static framework that SwiftPM |
| 173 | // did not copy into the .build directory. we don't need to pack it anyway. |
| 174 | break |
| 175 | } |
| 176 | // if the magic matches one of these it's a static archive; don't embed it. |
| 177 | // https://github.com/apple/llvm-project/blob/e716ff14c46490d2da6b240806c04e2beef01f40/llvm/include/llvm/Object/Archive.h#L33 |
| 178 | // swiftlint:disable:previous line_length |
| 179 | if bytes != magic && bytes != thinMagic { |
| 180 | try await packFile(srcName: "\(name).framework", dstName: "Frameworks/\(name).framework", sign: true) |
| 181 | } |
| 182 | case .library(let name): |
| 183 | try await packFile(srcName: "lib\(name).dylib", dstName: "Frameworks/lib\(name).dylib", sign: true) |
| 184 | case .root(let source): |
| 185 | try await packFileToRoot(srcName: source) |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | if let iconPath = product.iconPath { |
| 190 | group.addTask { |
| 191 | try await packFileToRoot(srcName: iconPath) |
| 192 | } |
| 193 | } |
| 194 | if let compiledAssetDir = product.compiledAssetDir { |
| 195 | group.addTask { |
| 196 | try await Packer.copyCompiledAssets(from: URL(fileURLWithPath: compiledAssetDir), to: outputURL) |
| 197 | } |
| 198 | } |
| 199 | group.addTask { |
| 200 | try await packFile(srcName: product.targetName, dstName: product.product) |
| 201 | } |
| 202 | group.addTask { |
| 203 | var info = product.infoPlist |
| 204 | |
| 205 | if product.type == .application { |
| 206 | info["UIRequiredDeviceCapabilities"] = ["arm64"] |
| 207 | info["LSRequiresIPhoneOS"] = true |
| 208 | info["CFBundleSupportedPlatforms"] = Packer.cfBundleSupportedPlatforms(for: buildSettings.triple) |
| 209 | // App Store upload validation requires the DT* keys Xcode |
| 210 | // stamps (missing DTPlatformName is error 90507, and an |
| 211 | // unrecognized SDK is 90534). |
| 212 | let simulator = buildSettings.triple.contains("simulator") |
| 213 | info["DTPlatformName"] = simulator ? "iphonesimulator" : "iphoneos" |
| 214 | if let sdk = Packer.darwinSDKInfo() { |
| 215 | info["DTPlatformVersion"] = sdk.version |
| 216 | info["DTSDKName"] = "\(simulator ? "iphonesimulator" : "iphoneos")\(sdk.version)" |
| 217 | // DTSDKBuild must be the SDK's ProductBuildVersion |
| 218 | // (e.g. 24A94232), not the marketing version — App Store |
| 219 | // rejects unknown values (BUILD_SDK_NOT_ALLOWED). |
| 220 | info["DTSDKBuild"] = sdk.sdkBuild ?? sdk.xcodeBuild ?? sdk.version |
| 221 | info["DTPlatformBuild"] = sdk.sdkBuild ?? sdk.xcodeBuild ?? sdk.version |
| 222 | if let xcode = sdk.xcode { info["DTXcode"] = xcode } |
| 223 | if let xcodeBuild = sdk.xcodeBuild { info["DTXcodeBuild"] = xcodeBuild } |
| 224 | } |
| 225 | info["DTCompiler"] = "com.apple.compilers.llvm.clang.1_0" |
| 226 | } |
| 227 | |
| 228 | if let iconPath = product.iconPath { |
| 229 | let iconName = URL(fileURLWithPath: iconPath).deletingPathExtension().lastPathComponent |
| 230 | info["CFBundleIconFile"] = iconName |
| 231 | } |
| 232 | |
| 233 | if let compiledAssetDir = product.compiledAssetDir { |
| 234 | let partialURL = URL(fileURLWithPath: compiledAssetDir) |
| 235 | .appendingPathComponent("assets-partial-Info.plist") |
| 236 | if FileManager.default.fileExists(atPath: partialURL.path) { |
| 237 | let data = try Data(contentsOf: partialURL) |
| 238 | let partial = try PropertyListSerialization.propertyList(from: data, format: nil) |
| 239 | guard let partial = partial as? [String: any Sendable] else { |
| 240 | throw StringError("assets-partial-Info.plist has invalid format: expected a dictionary.") |
| 241 | } |
| 242 | info.merge(partial, uniquingKeysWith: { $1 }) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | let infoPath = outputURL.appendingPathComponent("Info.plist") |
| 247 | let encodedPlist = try PropertyListSerialization.data( |
| 248 | fromPropertyList: info, |
| 249 | format: .xml, |
| 250 | options: 0 |
| 251 | ) |
| 252 | try encodedPlist.write(to: infoPath) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | public struct DarwinSDKInfo: Sendable { |
| 257 | public var version: String |
| 258 | public var sdkBuild: String? |
| 259 | public var xcode: String? |
| 260 | public var xcodeBuild: String? |
| 261 | } |
| 262 | |
| 263 | /// Version/build of the installed iPhoneOS SDK (version from its |
| 264 | /// directory name, e.g. `iPhoneOS27.1.sdk`; build from the sibling |
| 265 | /// Xcode.app when present), used for the `DT*` Info.plist keys and the |
| 266 | /// SDK-versioned build triple. |
| 267 | public static func darwinSDKInfo() -> DarwinSDKInfo? { |
| 268 | guard let sdk = try? DarwinSDK.current() else { return nil } |
| 269 | let sdksDir = sdk.bundle |
| 270 | .appendingPathComponent("Developer/Platforms/iPhoneOS.platform/Developer/SDKs") |
| 271 | guard let names = try? FileManager.default.contentsOfDirectory(atPath: sdksDir.path) else { return nil } |
| 272 | var version: String? |
| 273 | for name in names.sorted() { |
| 274 | // iPhoneOS27.1.sdk (skip the iPhoneOS.sdk alias) |
| 275 | guard name.hasPrefix("iPhoneOS"), name.hasSuffix(".sdk") else { continue } |
| 276 | let candidate = name.dropFirst("iPhoneOS".count).dropLast(".sdk".count) |
| 277 | guard !candidate.isEmpty, candidate.first?.isNumber == true else { continue } |
| 278 | version = String(candidate) |
| 279 | break |
| 280 | } |
| 281 | guard let version else { return nil } |
| 282 | |
| 283 | var sdkBuild: String? |
| 284 | let sdkVersionPlist = sdksDir |
| 285 | .appendingPathComponent("iPhoneOS\(version).sdk/System/Library/CoreServices/SystemVersion.plist") |
| 286 | if let data = try? Data(contentsOf: sdkVersionPlist), |
| 287 | let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] { |
| 288 | sdkBuild = plist["ProductBuildVersion"] as? String |
| 289 | } |
| 290 | |
| 291 | var xcode: String? |
| 292 | var xcodeBuild: String? |
| 293 | let xcodeInfo = sdk.bundle.appendingPathComponent("Xcode.app/Contents/Info.plist") |
| 294 | if let data = try? Data(contentsOf: xcodeInfo), |
| 295 | let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] { |
| 296 | xcode = plist["DTXcode"] as? String |
| 297 | xcodeBuild = plist["DTXcodeBuild"] as? String |
| 298 | } |
| 299 | // The build number Xcode stamps into apps (DTXcodeBuild) is the |
| 300 | // version.plist ProductBuildVersion (e.g. 27A9275); the Info.plist |
| 301 | // DTXcodeBuild in the SDK bundle lags it by one and is rejected by |
| 302 | // App Store Connect as an unknown Xcode build. |
| 303 | let xcodeVersion = sdk.bundle.appendingPathComponent("Xcode.app/Contents/version.plist") |
| 304 | if let data = try? Data(contentsOf: xcodeVersion), |
| 305 | let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], |
| 306 | let productBuild = plist["ProductBuildVersion"] as? String { |
| 307 | xcodeBuild = productBuild |
| 308 | } |
| 309 | return DarwinSDKInfo(version: version, sdkBuild: sdkBuild, xcode: xcode, xcodeBuild: xcodeBuild) |
| 310 | } |
| 311 | |
| 312 | /// Files in a compiled asset directory that belong in the `.app`: |
| 313 | /// everything except `*.sha256` sidecars and the partial Info.plist |
| 314 | /// (the latter is merged into `Info.plist`, not copied). |
| 315 | static func compiledAssetFileNames(in dir: URL) throws -> [String] { |
| 316 | guard FileManager.default.fileExists(atPath: dir.path) else { |
| 317 | throw StringError("assetCatalog.compiledDir not found: '\(dir.path)'") |
| 318 | } |
| 319 | return try FileManager.default.contentsOfDirectory(atPath: dir.path) |
| 320 | .filter { !$0.hasSuffix(".sha256") && $0 != "assets-partial-Info.plist" } |
| 321 | .sorted() |
| 322 | } |
| 323 | |
| 324 | static func copyCompiledAssets(from dir: URL, to outputURL: URL) async throws { |
| 325 | for name in try compiledAssetFileNames(in: dir) { |
| 326 | let src = dir.appendingPathComponent(name) |
| 327 | var isDir: ObjCBool = false |
| 328 | guard FileManager.default.fileExists(atPath: src.path, isDirectory: &isDir) else { continue } |
| 329 | let dest = outputURL.appendingPathComponent(name) |
| 330 | if isDir.boolValue { |
| 331 | try FileManager.default.copyItem(at: src, to: dest) |
| 332 | } else { |
| 333 | try FileManager.default.copyItem(at: src, to: dest) |
| 334 | } |
| 335 | try Task.checkCancellation() |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | static func cfBundleSupportedPlatforms(for triple: String) -> [String] { |
| 340 | let components = triple.split(separator: "-").map(String.init) |
| 341 | guard let appleIndex = components.firstIndex(of: "apple"), |
| 342 | components.indices.contains(appleIndex + 1) else { |
| 343 | return ["iPhoneOS"] |
| 344 | } |
| 345 | |
| 346 | let os = components[appleIndex + 1].prefix { !$0.isNumber } |
| 347 | switch os { |
| 348 | case "ios" where components.contains("simulator"): |
| 349 | return ["iPhoneSimulator"] |
| 350 | case "ios": |
| 351 | return ["iPhoneOS"] |
| 352 | case "macos", "macosx": |
| 353 | return ["MacOSX"] |
| 354 | default: |
| 355 | return ["iPhoneOS"] |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | extension Plan.Product { |
| 361 | fileprivate var linkerSettings: String { |
| 362 | switch self.type { |
| 363 | case .application: """ |
| 364 | [ |
| 365 | .unsafeFlags([ |
| 366 | "-Xlinker", "-rpath", "-Xlinker", "@executable_path/Frameworks", |
| 367 | // Decouple LC_BUILD_VERSION's minos from its sdk: the build |
| 368 | // triple carries the SDK version (so App Store sees a current |
| 369 | // SDK, error 90725), while this pins the deployment target. |
| 370 | "-Xlinker", "-platform_version", "-Xlinker", "ios", "-Xlinker", "\(deploymentTarget)", "-Xlinker", "\(Packer.darwinSDKInfo()?.version ?? deploymentTarget)", |
| 371 | ]), |
| 372 | ] |
| 373 | """ |
| 374 | case .appExtension: """ |
| 375 | [ |
| 376 | // Link to Foundation framework which implements the _NSExtensionMain entrypoint |
| 377 | .linkedFramework("Foundation"), |
| 378 | .unsafeFlags([ |
| 379 | // Set the entry point to Foundation`_NSExtensionMain |
| 380 | "-Xlinker", "-e", "-Xlinker", "_NSExtensionMain", |
| 381 | // Include frameworks that the host app may use |
| 382 | "-Xlinker", "-rpath", "-Xlinker", "@executable_path/../../Frameworks", |
| 383 | // ...as well as our own |
| 384 | "-Xlinker", "-rpath", "-Xlinker", "@executable_path/Frameworks", |
| 385 | ]), |
| 386 | ] |
| 387 | """ |
| 388 | } |
| 389 | } |
| 390 | } |