xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / PackLib / Planner.swift
Planner.swift459 lines · 16.2 KiBRaw
| 1 | import Foundation |
| 2 | import XUtils |
| 3 | import Subprocess |
| 4 | |
| 5 | public struct Planner: Sendable { |
| 6 | public var buildSettings: BuildSettings |
| 7 | public var schema: PackSchema |
| 8 | |
| 9 | public init( |
| 10 | buildSettings: BuildSettings, |
| 11 | schema: PackSchema |
| 12 | ) { |
| 13 | self.buildSettings = buildSettings |
| 14 | self.schema = schema |
| 15 | } |
| 16 | |
| 17 | private static let decoder: JSONDecoder = { |
| 18 | let decoder = JSONDecoder() |
| 19 | decoder.keyDecodingStrategy = .convertFromSnakeCase |
| 20 | return decoder |
| 21 | }() |
| 22 | |
| 23 | // anything older than this requires bundling the stdlib which |
| 24 | // is doable but probably not worth the effort |
| 25 | private static let minSupportedIOSVersion = "13.0" |
| 26 | |
| 27 | private func buildGraph() async throws -> PackageGraph { |
| 28 | let dependencyRoot = try await dumpDependencies() |
| 29 | |
| 30 | let packages = try await withThrowingTaskGroup( |
| 31 | of: (PackageDependency, PackageDump).self, |
| 32 | returning: [String: PackageDump].self |
| 33 | ) { group in |
| 34 | var visited: Set<String> = [] |
| 35 | var dependencies: [PackageDependency] = [dependencyRoot] |
| 36 | while let dependencyNode = dependencies.popLast() { |
| 37 | guard visited.insert(dependencyNode.identity).inserted else { continue } |
| 38 | dependencies.append(contentsOf: dependencyNode.dependencies) |
| 39 | group.addTask { (dependencyNode, try await dumpPackage(at: dependencyNode.path)) } |
| 40 | } |
| 41 | |
| 42 | var packages: [String: PackageDump] = [:] |
| 43 | while let result = await group.nextResult() { |
| 44 | switch result { |
| 45 | case .success((let dependency, let dump)): |
| 46 | packages[dependency.identity] = dump |
| 47 | case .failure(_ as CancellationError): |
| 48 | // continue loop |
| 49 | break |
| 50 | case .failure(let error): |
| 51 | group.cancelAll() |
| 52 | throw error |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | return packages |
| 57 | } |
| 58 | |
| 59 | var packagesByProductName: [String: String] = [:] |
| 60 | for (packageID, package) in packages { |
| 61 | for product in package.products ?? [] { |
| 62 | packagesByProductName[product.name] = packageID |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | let rootPackage = packages[dependencyRoot.identity]! |
| 67 | |
| 68 | return PackageGraph( |
| 69 | root: rootPackage, |
| 70 | packages: packages, |
| 71 | packagesByProductName: packagesByProductName |
| 72 | ) |
| 73 | } |
| 74 | |
| 75 | public func createPlan() async throws -> Plan { |
| 76 | // TODO: cache plan using (Package.swift+Package.resolved) as the key? |
| 77 | |
| 78 | let graph = try await buildGraph() |
| 79 | |
| 80 | let app = try await product( |
| 81 | from: graph, |
| 82 | matching: schema.product, |
| 83 | type: .application, |
| 84 | plist: schema.infoPath, |
| 85 | idSpecifier: schema.idSpecifier, |
| 86 | iconPath: schema.iconPath, |
| 87 | rootResources: schema.resources, |
| 88 | entitlementsPath: schema.entitlementsPath, |
| 89 | compiledAssetDir: schema.assetCatalog?.compiledDir |
| 90 | ) |
| 91 | |
| 92 | let extensionProducts: [Plan.Product] |
| 93 | if let extensions = schema.extensions, !extensions.isEmpty { |
| 94 | extensionProducts = try await withThrowingTaskGroup(of: Plan.Product.self) { group in |
| 95 | for ext in extensions { |
| 96 | group.addTask { |
| 97 | try await product( |
| 98 | from: graph, |
| 99 | matching: ext.product, |
| 100 | type: .appExtension, |
| 101 | plist: ext.infoPath, |
| 102 | idSpecifier: ext.bundleID.flatMap(PackSchema.IDSpecifier.bundleID) ?? .orgID(app.bundleID), |
| 103 | iconPath: nil, |
| 104 | rootResources: ext.resources, |
| 105 | entitlementsPath: ext.entitlementsPath, |
| 106 | compiledAssetDir: nil |
| 107 | ) |
| 108 | } |
| 109 | } |
| 110 | return try await group.reduce(into: []) { $0.append($1) } |
| 111 | } |
| 112 | } else { |
| 113 | extensionProducts = [] |
| 114 | } |
| 115 | |
| 116 | return Plan(app: app, extensions: extensionProducts) |
| 117 | } |
| 118 | |
| 119 | // swiftlint:disable cyclomatic_complexity function_parameter_count |
| 120 | private func product( |
| 121 | from graph: PackageGraph, |
| 122 | matching name: String?, |
| 123 | type: Plan.ProductType, |
| 124 | plist: String?, |
| 125 | idSpecifier: PackSchema.IDSpecifier, |
| 126 | iconPath: String?, |
| 127 | rootResources: [String]?, |
| 128 | entitlementsPath: String?, |
| 129 | compiledAssetDir: String? |
| 130 | ) async throws -> Plan.Product { |
| 131 | let library = try selectLibrary( |
| 132 | from: graph.root.products?.filter { $0.type == .autoLibrary } ?? [], |
| 133 | matching: name |
| 134 | ) |
| 135 | var resources: [Plan.Resource] = [] |
| 136 | var visited: Set<String> = [] |
| 137 | var targets = library.targets.map { (graph.root, $0) } |
| 138 | while let (targetPackage, targetName) = targets.popLast() { |
| 139 | guard let target = targetPackage.targets?.first(where: { $0.name == targetName }) else { |
| 140 | throw StringError("Could not find target '\(targetName)' in package '\(targetPackage.name)'") |
| 141 | } |
| 142 | guard visited.insert(targetName).inserted else { continue } |
| 143 | // Macro targets are compiler plugins that run on the host, not code |
| 144 | // linked into the iOS app. Skip them to avoid resolving their |
| 145 | // host-only dependencies (e.g. SwiftSyntaxMacros). |
| 146 | if target.type == "macro" { continue } |
| 147 | if target.moduleType == "BinaryTarget" { |
| 148 | resources.append(.binaryTarget(name: targetName)) |
| 149 | } |
| 150 | if target.resources?.isEmpty == false { |
| 151 | resources.append(.bundle(package: targetPackage.name, target: targetName)) |
| 152 | } |
| 153 | for targetName in (target.targetDependencies ?? []) { |
| 154 | targets.append((targetPackage, targetName)) |
| 155 | } |
| 156 | for productName in (target.productDependencies ?? []) { |
| 157 | let (package, product) = try graph.product(name: productName) |
| 158 | if product.type == .dynamicLibrary { |
| 159 | resources.append(.library(name: productName)) |
| 160 | } |
| 161 | targets.append(contentsOf: product.targets.map { (package, $0) }) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | if let rootResources { |
| 166 | resources += rootResources.map { .root(source: $0) } |
| 167 | } |
| 168 | |
| 169 | let bundleID = idSpecifier.formBundleID(product: library.name) |
| 170 | let deploymentTarget = graph.root.platforms?.first { $0.name == "ios" }?.version |
| 171 | ?? Self.minSupportedIOSVersion |
| 172 | |
| 173 | var infoPlist: [String: Sendable] = [ |
| 174 | "CFBundleInfoDictionaryVersion": "6.0", |
| 175 | "CFBundleDevelopmentRegion": "en", |
| 176 | "CFBundleVersion": "1", |
| 177 | "CFBundleShortVersionString": "1.0.0", |
| 178 | "MinimumOSVersion": deploymentTarget, |
| 179 | "CFBundleIdentifier": bundleID, |
| 180 | "CFBundleName": library.name, |
| 181 | "CFBundleExecutable": library.name, |
| 182 | "CFBundleDisplayName": library.name, |
| 183 | "CFBundlePackageType": type.fourCharCode, |
| 184 | ] |
| 185 | |
| 186 | switch type { |
| 187 | case .application: |
| 188 | infoPlist["UIDeviceFamily"] = [1, 2] |
| 189 | infoPlist["UISupportedInterfaceOrientations"] = ["UIInterfaceOrientationPortrait"] |
| 190 | infoPlist["UISupportedInterfaceOrientations~ipad"] = [ |
| 191 | "UIInterfaceOrientationPortrait", |
| 192 | "UIInterfaceOrientationPortraitUpsideDown", |
| 193 | "UIInterfaceOrientationLandscapeLeft", |
| 194 | "UIInterfaceOrientationLandscapeRight", |
| 195 | ] |
| 196 | infoPlist["UILaunchScreen"] = [:] as [String: Sendable] |
| 197 | case .appExtension: |
| 198 | // Should set default parameters? |
| 199 | infoPlist["NSExtension"] = [:] as [String: Sendable] |
| 200 | } |
| 201 | |
| 202 | if let plist { |
| 203 | let data = try await Data(reading: URL(fileURLWithPath: plist)) |
| 204 | let info = try PropertyListSerialization.propertyList(from: data, format: nil) |
| 205 | if let info = info as? [String: Sendable] { |
| 206 | infoPlist.merge(info, uniquingKeysWith: { $1 }) |
| 207 | } else { |
| 208 | throw StringError("Info.plist has invalid format: expected a dictionary.") |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | return Plan.Product( |
| 213 | type: type, |
| 214 | product: library.name, |
| 215 | deploymentTarget: deploymentTarget, |
| 216 | bundleID: bundleID, |
| 217 | infoPlist: infoPlist, |
| 218 | resources: resources, |
| 219 | iconPath: iconPath, |
| 220 | entitlementsPath: entitlementsPath, |
| 221 | compiledAssetDir: compiledAssetDir |
| 222 | ) |
| 223 | } |
| 224 | |
| 225 | private func dumpDependencies() async throws -> PackageDependency { |
| 226 | let tempDir = try TemporaryDirectory(name: "xtool-dump") |
| 227 | let tempFileURL = tempDir.url.appendingPathComponent("dump.json") |
| 228 | |
| 229 | // SwiftPM sometimes prints extraneous data to stdout, so ask |
| 230 | // it to write the JSON to a temp file instead. See: |
| 231 | // https://github.com/xtool-org/xtool/pull/97#discussion_r2203618825 |
| 232 | _ = try await _dumpAction( |
| 233 | arguments: ["-q", "show-dependencies", "--format", "json", "-o", tempFileURL.path], |
| 234 | path: buildSettings.packagePath |
| 235 | ) |
| 236 | |
| 237 | return try Self.decoder.decode( |
| 238 | PackageDependency.self, |
| 239 | from: Data(contentsOf: tempFileURL) |
| 240 | ) |
| 241 | } |
| 242 | |
| 243 | private func dumpPackage(at path: String) async throws -> PackageDump { |
| 244 | let data = try await _dumpAction(arguments: ["-q", "describe", "--type", "json"], path: path) |
| 245 | try Task.checkCancellation() |
| 246 | |
| 247 | // As in dumpDependencies, we may end up with extraneous data, but `describe` |
| 248 | // doesn't have a `-o` flag for a clean workaround. Resort to a heuristic, |
| 249 | // looking for the opening brace. |
| 250 | let fromBrace = data.drop(while: { $0 != Character("{").asciiValue }) |
| 251 | return try Self.decoder.decode(PackageDump.self, from: fromBrace) |
| 252 | } |
| 253 | |
| 254 | private func _dumpAction(arguments: [String], path: String) async throws -> Data { |
| 255 | let dumpConfig = try await buildSettings.withPackagePath(path).swiftPMInvocation( |
| 256 | forTool: "package", |
| 257 | arguments: arguments, |
| 258 | ) |
| 259 | return try await Subprocess.run( |
| 260 | dumpConfig, |
| 261 | output: .data(limit: .max), |
| 262 | error: .currentStandardError, |
| 263 | ) |
| 264 | .checkSuccess() |
| 265 | .standardOutput |
| 266 | } |
| 267 | |
| 268 | private func selectLibrary( |
| 269 | from products: [PackageDump.Product], |
| 270 | matching name: String? |
| 271 | ) throws -> PackageDump.Product { |
| 272 | switch products.count { |
| 273 | case 0: |
| 274 | throw StringError("No library products were found in the package") |
| 275 | case 1: |
| 276 | let product = products[0] |
| 277 | if let name, product.name != name { |
| 278 | throw StringError(""" |
| 279 | Product name ('\(product.name)') does not match the 'product' value in the schema ('\(name)') |
| 280 | """) |
| 281 | } |
| 282 | return product |
| 283 | default: |
| 284 | guard let name else { |
| 285 | throw StringError(""" |
| 286 | Multiple library products were found (\(products.map(\.name))). Please either: |
| 287 | 1) Expose exactly one library product, or |
| 288 | 2) Specify the product you want via the 'product' key in xtool.yml. |
| 289 | """) |
| 290 | } |
| 291 | guard let product = products.first(where: { $0.name == name }) else { |
| 292 | throw StringError(""" |
| 293 | Schema declares a 'product' name of '\(name)' but no matching product was found. |
| 294 | Found: \(products.map(\.name)). |
| 295 | """) |
| 296 | } |
| 297 | return product |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | public struct Plan: Sendable { |
| 303 | public var app: Product |
| 304 | public var extensions: [Product] |
| 305 | |
| 306 | public var allProducts: [Product] { |
| 307 | [app] + extensions |
| 308 | } |
| 309 | |
| 310 | public enum Resource: Codable, Sendable, Hashable { |
| 311 | case bundle(package: String, target: String) |
| 312 | case binaryTarget(name: String) |
| 313 | case library(name: String) |
| 314 | case root(source: String) |
| 315 | } |
| 316 | |
| 317 | public struct Product: Sendable { |
| 318 | public var type: ProductType |
| 319 | public var product: String |
| 320 | public var deploymentTarget: String |
| 321 | public var bundleID: String |
| 322 | public var infoPlist: [String: any Sendable] |
| 323 | public var resources: [Resource] |
| 324 | public var iconPath: String? |
| 325 | public var entitlementsPath: String? |
| 326 | /// Directory of pre-compiled asset-catalog output (see PackSchema). |
| 327 | public var compiledAssetDir: String? |
| 328 | |
| 329 | public var targetName: String { |
| 330 | "\(self.product)-\(self.type.targetSuffix)" |
| 331 | } |
| 332 | |
| 333 | public func directory(inApp baseDir: URL) -> URL { |
| 334 | switch type { |
| 335 | case .application: |
| 336 | baseDir |
| 337 | .appendingPathComponent(".", isDirectory: true) |
| 338 | case .appExtension: |
| 339 | baseDir |
| 340 | .appendingPathComponent("PlugIns", isDirectory: true) |
| 341 | .appendingPathComponent(product, isDirectory: true) |
| 342 | .appendingPathExtension("appex") |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | public enum ProductType: Sendable { |
| 348 | case application |
| 349 | case appExtension |
| 350 | |
| 351 | fileprivate var targetSuffix: String { |
| 352 | switch self { |
| 353 | case .application: "App" |
| 354 | case .appExtension: "Extension" |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | fileprivate var fourCharCode: String { |
| 359 | switch self { |
| 360 | case .application: "APPL" |
| 361 | case .appExtension: "XPC!" |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | private struct PackageDependency: Decodable { |
| 368 | let identity: String |
| 369 | let name: String |
| 370 | let path: String // on disk |
| 371 | let dependencies: [PackageDependency] |
| 372 | } |
| 373 | |
| 374 | private struct PackageDump: Decodable { |
| 375 | enum ProductType: Decodable { |
| 376 | case executable |
| 377 | case dynamicLibrary |
| 378 | case staticLibrary |
| 379 | case autoLibrary |
| 380 | case other |
| 381 | |
| 382 | private enum CodingKeys: String, CodingKey { |
| 383 | case executable |
| 384 | case library |
| 385 | } |
| 386 | |
| 387 | init(from decoder: Decoder) throws { |
| 388 | let container = try decoder.container(keyedBy: CodingKeys.self) |
| 389 | if container.contains(.executable) { |
| 390 | self = .executable |
| 391 | } else if let library = try container.decodeIfPresent([String].self, forKey: .library) { |
| 392 | if library.count == 1 { |
| 393 | switch library[0] { |
| 394 | case "dynamic": |
| 395 | self = .dynamicLibrary |
| 396 | case "static": |
| 397 | self = .staticLibrary |
| 398 | case "automatic": |
| 399 | self = .autoLibrary |
| 400 | default: |
| 401 | self = .other |
| 402 | } |
| 403 | } else { |
| 404 | self = .other |
| 405 | } |
| 406 | } else { |
| 407 | self = .other |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | struct Product: Decodable { |
| 413 | let name: String |
| 414 | let targets: [String] |
| 415 | let type: ProductType |
| 416 | } |
| 417 | |
| 418 | struct Target: Decodable { |
| 419 | let name: String |
| 420 | let moduleType: String |
| 421 | let type: String? |
| 422 | let productDependencies: [String]? |
| 423 | let targetDependencies: [String]? |
| 424 | let resources: [Resource]? |
| 425 | } |
| 426 | |
| 427 | struct Resource: Decodable { |
| 428 | let path: String |
| 429 | } |
| 430 | |
| 431 | struct Platform: Decodable { |
| 432 | let name: String |
| 433 | let version: String |
| 434 | } |
| 435 | |
| 436 | let name: String |
| 437 | let products: [Product]? |
| 438 | let targets: [Target]? |
| 439 | let platforms: [Platform]? |
| 440 | } |
| 441 | |
| 442 | private struct PackageGraph { |
| 443 | let root: PackageDump |
| 444 | let packages: [String: PackageDump] |
| 445 | let packagesByProductName: [String: String] |
| 446 | |
| 447 | func product(name productName: String) throws -> (PackageDump, PackageDump.Product) { |
| 448 | guard let packageID = packagesByProductName[productName] else { |
| 449 | throw StringError("Could not find package containing product '\(productName)'") |
| 450 | } |
| 451 | guard let package = packages[packageID] else { |
| 452 | throw StringError("Could not find package by id '\(packageID)'") |
| 453 | } |
| 454 | guard let product = package.products?.first(where: { $0.name == productName }) else { |
| 455 | throw StringError("Could not find product '\(productName)' in package '\(packageID)'") |
| 456 | } |
| 457 | return (package, product) |
| 458 | } |
| 459 | } |