Skip to content

armgit / xtool

Public Imported from GitHub
0

Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.

Add support for App Extensions (#97)

Erik Bautista Santibanezedd6b90f532a
diff --git a/Sources/PackLib/PackSchema.swift b/Sources/PackLib/PackSchema.swift
index b7f1f80..e696d2d 100644
--- a/Sources/PackLib/PackSchema.swift
+++ b/Sources/PackLib/PackSchema.swift
@@ -18,9 +18,22 @@ public struct PackSchemaBase: Codable, Sendable {
public var iconPath: String?
public var resources: [String]?
+
+ public var extensions: [Extension]?
+
+ public struct Extension: Codable, Sendable {
+ public var product: String
+ public var bundleID: String?
+ public var infoPath: String
+ public var resources: [String]?
+ public var entitlementsPath: String?
+ }
}
+@dynamicMemberLookup
public struct PackSchema: Sendable {
+ public typealias Extension = PackSchemaBase.Extension
+
public enum IDSpecifier: Sendable {
case orgID(String)
case bundleID(String)
@@ -71,4 +84,8 @@ public struct PackSchema: Sendable {
let base = try YAMLDecoder().decode(PackSchemaBase.self, from: data)
try self.init(validating: base)
}
+
+ public subscript<Subject>(dynamicMember keyPath: KeyPath<PackSchemaBase, Subject>) -> Subject {
+ self.base[keyPath: keyPath]
+ }
}
diff --git a/Sources/PackLib/Packer.swift b/Sources/PackLib/Packer.swift
index 266c4b7..b852343 100644
--- a/Sources/PackLib/Packer.swift
+++ b/Sources/PackLib/Packer.swift
@@ -20,34 +20,44 @@ public struct Packer: Sendable {
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
- name: "\(plan.product)-Builder",
+ name: "\(plan.app.product)-Builder",
platforms: [
- .iOS("\(plan.deploymentTarget)"),
+ .iOS("\(plan.app.deploymentTarget)"),
],
dependencies: [
.package(name: "RootPackage", path: "../.."),
],
targets: [
- .executableTarget(
- name: "\(plan.product)-App",
- dependencies: [
- .product(name: "\(plan.product)", package: "RootPackage"),
- ]
- ),
+ \(
+ plan.allProducts.map {
+ """
+ .executableTarget(
+ name: "\($0.targetName)",
+ dependencies: [
+ .product(name: "\($0.product)", package: "RootPackage"),
+ ],
+ linkerSettings: \($0.linkerSettings)
+ )
+ """
+ }
+ .joined(separator: ",\n")
+ )
]
)\n
"""
try Data(contents.utf8).write(to: packageSwift)
- let sources = packageDir.appendingPathComponent("Sources")
- try? FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true)
- try Data().write(to: sources.appendingPathComponent("stub.c"))
+
+ for product in plan.allProducts {
+ let sources: URL = packageDir.appendingPathComponent("Sources/\(product.targetName)", isDirectory: true)
+ try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true)
+ try Data().write(to: sources.appendingPathComponent("stub.c", isDirectory: false))
+ }
let builder = try await buildSettings.swiftPMInvocation(
forTool: "build",
arguments: [
"--package-path", packageDir.path,
"--scratch-path", ".build",
- "--product", "\(plan.product)-App",
// resolving can cause SwiftPM to overwrite the root package deps
// with just the deps needed for the builder package (which is to
// say, any "dev dependencies" of the root package may be removed.)
@@ -55,7 +65,6 @@ public struct Packer: Sendable {
// in order to dump the plan, so we can skip resolution here to skirt
// the issue.
"--disable-automatic-resolution",
- "-Xlinker", "-rpath", "-Xlinker", "@executable_path/Frameworks",
]
)
builder.standardOutput = FileHandle.standardError
@@ -65,15 +74,49 @@ public struct Packer: Sendable {
public func pack() async throws -> URL {
try await build()
- let output = try TemporaryDirectory(name: "\(plan.product).app")
+ let output = try TemporaryDirectory(name: "\(plan.app.product).app")
+
+ let outputURL = output.url
let binDir = URL(
fileURLWithPath: ".build/\(buildSettings.triple)/\(buildSettings.configuration.rawValue)",
isDirectory: true
)
- let outputURL = output.url
+ try await withThrowingTaskGroup(of: Void.self) { group in
+ for product in plan.allProducts {
+ try pack(
+ product: product,
+ binDir: binDir,
+ outputURL: product.directory(inApp: outputURL),
+ &group
+ )
+ }
+ while !group.isEmpty {
+ do {
+ try await group.next()
+ } catch is CancellationError {
+ // continue
+ } catch {
+ group.cancelAll()
+ throw error
+ }
+ }
+ }
+
+ let dest = URL(fileURLWithPath: "xtool").appendingPathComponent(outputURL.lastPathComponent)
+ try? FileManager.default.removeItem(at: dest)
+ try output.persist(at: dest)
+ return dest
+ }
+
+ @Sendable private func pack(
+ product: Plan.Product,
+ binDir: URL,
+ outputURL: URL,
+ _ group: inout ThrowingTaskGroup<Void, Error>
+ ) throws {
@Sendable func packFileToRoot(srcName: String) async throws {
let srcURL = URL(fileURLWithPath: srcName)
let destURL = outputURL.appendingPathComponent(srcURL.lastPathComponent)
@@ -91,70 +134,89 @@ public struct Packer: Sendable {
try Task.checkCancellation()
}
- try await withThrowingTaskGroup(of: Void.self) { group in
- for command in plan.resources {
- group.addTask {
- switch command {
- case .bundle(let package, let target):
- try await packFile(srcName: "\(package)_\(target).bundle")
- case .binaryTarget(let name):
- let src = URL(fileURLWithPath: "\(name).framework/\(name)", relativeTo: binDir)
- let magic = Data("!<arch>\n".utf8)
- let thinMagic = Data("!<thin>\n".utf8)
- let bytes = try FileHandle(forReadingFrom: src).read(upToCount: magic.count)
- // if the magic matches one of these it's a static archive; don't embed it.
- // https://github.com/apple/llvm-project/blob/e716ff14c46490d2da6b240806c04e2beef01f40/llvm/include/llvm/Object/Archive.h#L33
- // swiftlint:disable:previous line_length
- if bytes != magic && bytes != thinMagic {
- try await packFile(srcName: "\(name).framework", dstName: "Frameworks/\(name).framework", sign: true)
- }
- case .library(let name):
- try await packFile(srcName: "lib\(name).dylib", dstName: "Frameworks/lib\(name).dylib", sign: true)
- case .root(let source):
- try await packFileToRoot(srcName: source)
+ // Ensure output directory is available
+ try? FileManager.default.createDirectory(at: outputURL, withIntermediateDirectories: true)
+
+ for command in product.resources {
+ group.addTask {
+ switch command {
+ case .bundle(let package, let target):
+ try await packFile(srcName: "\(package)_\(target).bundle")
+ case .binaryTarget(let name):
+ let src = URL(fileURLWithPath: "\(name).framework/\(name)", relativeTo: binDir)
+ let magic = Data("!<arch>\n".utf8)
+ let thinMagic = Data("!<thin>\n".utf8)
+ let bytes = try FileHandle(forReadingFrom: src).read(upToCount: magic.count)
+ // if the magic matches one of these it's a static archive; don't embed it.
+ // https://github.com/apple/llvm-project/blob/e716ff14c46490d2da6b240806c04e2beef01f40/llvm/include/llvm/Object/Archive.h#L33
+ // swiftlint:disable:previous line_length
+ if bytes != magic && bytes != thinMagic {
+ try await packFile(srcName: "\(name).framework", dstName: "Frameworks/\(name).framework", sign: true)
}
+ case .library(let name):
+ try await packFile(srcName: "lib\(name).dylib", dstName: "Frameworks/lib\(name).dylib", sign: true)
+ case .root(let source):
+ try await packFileToRoot(srcName: source)
}
}
- if let iconPath = plan.iconPath {
- group.addTask {
- try await packFileToRoot(srcName: iconPath)
- }
- }
+ }
+ if let iconPath = product.iconPath {
group.addTask {
- try await packFile(srcName: "\(plan.product)-App", dstName: plan.product)
+ try await packFileToRoot(srcName: iconPath)
}
- group.addTask {
- var info = plan.infoPlist
-
- if let iconPath = plan.iconPath {
- let iconName = URL(fileURLWithPath: iconPath).deletingPathExtension().lastPathComponent
- info["CFBundleIconFile"] = iconName
- }
+ }
+ group.addTask {
+ try await packFile(srcName: product.targetName, dstName: product.product)
+ }
+ group.addTask {
+ var info = product.infoPlist
- let infoPath = outputURL.appendingPathComponent("Info.plist")
- let encodedPlist = try PropertyListSerialization.data(
- fromPropertyList: info,
- format: .xml,
- options: 0
- )
- try encodedPlist.write(to: infoPath)
+ if product.type == .application {
+ info["UIRequiredDeviceCapabilities"] = ["arm64"]
+ info["LSRequiresIPhoneOS"] = true
+ info["CFBundleSupportedPlatforms"] = ["iPhoneOS"]
}
- while !group.isEmpty {
- do {
- try await group.next()
- } catch is CancellationError {
- // continue
- } catch {
- group.cancelAll()
- throw error
- }
+
+ if let iconPath = product.iconPath {
+ let iconName = URL(fileURLWithPath: iconPath).deletingPathExtension().lastPathComponent
+ info["CFBundleIconFile"] = iconName
}
+
+ let infoPath = outputURL.appendingPathComponent("Info.plist")
+ let encodedPlist = try PropertyListSerialization.data(
+ fromPropertyList: info,
+ format: .xml,
+ options: 0
+ )
+ try encodedPlist.write(to: infoPath)
}
+ }
+}
- let dest = URL(fileURLWithPath: "xtool")
- .appendingPathComponent(output.url.lastPathComponent)
- try? FileManager.default.removeItem(at: dest)
- try output.persist(at: dest)
- return dest
+extension Plan.Product {
+ fileprivate var linkerSettings: String {
+ switch self.type {
+ case .application: """
+ [
+ .unsafeFlags([
+ "-Xlinker", "-rpath", "-Xlinker", "@executable_path/Frameworks",
+ ]),
+ ]
+ """
+ case .appExtension: """
+ [
+ // Link to Foundation framework which implements the _NSExtensionMain entrypoint
+ .linkedFramework("Foundation"),
+ .unsafeFlags([
+ // Set the entry point to Foundation`_NSExtensionMain
+ "-Xlinker", "-e", "-Xlinker", "_NSExtensionMain",
+ // Include frameworks that the host app may use
+ "-Xlinker", "-rpath", "-Xlinker", "@executable_path/../../Frameworks",
+ // ...as well as our own
+ "-Xlinker", "-rpath", "-Xlinker", "@executable_path/Frameworks",
+ ]),
+ ]
+ """
+ }
}
}
diff --git a/Sources/PackLib/Planner.swift b/Sources/PackLib/Planner.swift
index 19b4ff8..cf56430 100644
--- a/Sources/PackLib/Planner.swift
+++ b/Sources/PackLib/Planner.swift
@@ -18,15 +18,12 @@ public struct Planner: Sendable {
return decoder
}()
- // swiftlint:disable:next function_body_length cyclomatic_complexity
- public func createPlan() async throws -> Plan {
- // TODO: cache plan using (Package.swift+Package.resolved) as the key?
+ // anything older than this requires bundling the stdlib which
+ // is doable but probably not worth the effort
+ private static let minSupportedIOSVersion = "13.0"
- let dependencyData = try await _dumpAction(
- arguments: ["show-dependencies", "--format", "json"],
- path: buildSettings.packagePath
- )
- let dependencyRoot = try Self.decoder.decode(PackageDependency.self, from: dependencyData)
+ private func buildGraph() async throws -> PackageGraph {
+ let dependencyRoot = try await dumpDependencies()
let packages = try await withThrowingTaskGroup(
of: (PackageDependency, PackageDump).self,
@@ -65,18 +62,74 @@ public struct Planner: Sendable {
}
let rootPackage = packages[dependencyRoot.identity]!
- let deploymentTarget = rootPackage.platforms?.first { $0.name == "ios" }?.version ?? "13.0"
- let libraries = rootPackage.products?.filter { $0.type == .autoLibrary } ?? []
+ return PackageGraph(
+ root: rootPackage,
+ packages: packages,
+ packagesByProductName: packagesByProductName
+ )
+ }
- let library = try selectLibrary(
- from: libraries,
- matching: schema.base.product
+ public func createPlan() async throws -> Plan {
+ // TODO: cache plan using (Package.swift+Package.resolved) as the key?
+
+ let graph = try await buildGraph()
+
+ let app = try await product(
+ from: graph,
+ matching: schema.product,
+ type: .application,
+ plist: schema.infoPath,
+ idSpecifier: schema.idSpecifier,
+ iconPath: schema.iconPath,
+ rootResources: schema.resources,
+ entitlementsPath: schema.entitlementsPath
)
- var resources: [Resource] = []
+ let extensionProducts: [Plan.Product]
+ if let extensions = schema.extensions, !extensions.isEmpty {
+ extensionProducts = try await withThrowingTaskGroup(of: Plan.Product.self) { group in
+ for ext in extensions {
+ group.addTask {
+ try await product(
+ from: graph,
+ matching: ext.product,
+ type: .appExtension,
+ plist: ext.infoPath,
+ idSpecifier: ext.bundleID.flatMap(PackSchema.IDSpecifier.bundleID) ?? .orgID(app.bundleID),
+ iconPath: nil,
+ rootResources: ext.resources,
+ entitlementsPath: ext.entitlementsPath
+ )
+ }
+ }
+ return try await group.reduce(into: []) { $0.append($1) }
+ }
+ } else {
+ extensionProducts = []
+ }
+
+ return Plan(app: app, extensions: extensionProducts)
+ }
+
+ // swiftlint:disable cyclomatic_complexity function_parameter_count
+ private func product(
+ from graph: PackageGraph,
+ matching name: String?,
+ type: Plan.ProductType,
+ plist: String?,
+ idSpecifier: PackSchema.IDSpecifier,
+ iconPath: String?,
+ rootResources: [String]?,
+ entitlementsPath: String?
+ ) async throws -> Plan.Product {
+ let library = try selectLibrary(
+ from: graph.root.products?.filter { $0.type == .autoLibrary } ?? [],
+ matching: name
+ )
+ var resources: [Plan.Resource] = []
var visited: Set<String> = []
- var targets = library.targets.map { (rootPackage, $0) }
+ var targets = library.targets.map { (graph.root, $0) }
while let (targetPackage, targetName) = targets.popLast() {
guard let target = targetPackage.targets?.first(where: { $0.name == targetName }) else {
throw StringError("Could not find target '\(targetName)' in package '\(targetPackage.name)'")
@@ -92,15 +145,7 @@ public struct Planner: Sendable {
targets.append((targetPackage, targetName))
}
for productName in (target.productDependencies ?? []) {
- guard let packageID = packagesByProductName[productName] else {
- throw StringError("Could not find package containing product '\(productName)'")
- }
- guard let package = packages[packageID] else {
- throw StringError("Could not find package by id '\(packageID)'")
- }
- guard let product = package.products?.first(where: { $0.name == productName }) else {
- throw StringError("Could not find product '\(productName)' in package '\(packageID)'")
- }
+ let (package, product) = try graph.product(name: productName)
if product.type == .dynamicLibrary {
resources.append(.library(name: productName))
}
@@ -108,37 +153,44 @@ public struct Planner: Sendable {
}
}
- if let rootResources = schema.base.resources {
+ if let rootResources {
resources += rootResources.map { .root(source: $0) }
}
- let bundleID = schema.idSpecifier.formBundleID(product: library.name)
+ let bundleID = idSpecifier.formBundleID(product: library.name)
+ let deploymentTarget = graph.root.platforms?.first { $0.name == "ios" }?.version
+ ?? Self.minSupportedIOSVersion
var infoPlist: [String: Sendable] = [
"CFBundleInfoDictionaryVersion": "6.0",
- "UIRequiredDeviceCapabilities": ["arm64"],
- "LSRequiresIPhoneOS": true,
- "CFBundleSupportedPlatforms": ["iPhoneOS"],
- "CFBundlePackageType": "APPL",
- "UIDeviceFamily": [1, 2],
"CFBundleDevelopmentRegion": "en",
- "UISupportedInterfaceOrientations": ["UIInterfaceOrientationPortrait"],
- "UISupportedInterfaceOrientations~ipad": [
- "UIInterfaceOrientationPortrait",
- "UIInterfaceOrientationPortraitUpsideDown",
- "UIInterfaceOrientationLandscapeLeft",
- "UIInterfaceOrientationLandscapeRight"
- ],
- "UILaunchScreen": [:] as [String: Sendable],
"CFBundleVersion": "1",
"CFBundleShortVersionString": "1.0.0",
"MinimumOSVersion": deploymentTarget,
"CFBundleIdentifier": bundleID,
- "CFBundleName": "\(library.name)",
- "CFBundleExecutable": "\(library.name)",
+ "CFBundleName": library.name,
+ "CFBundleExecutable": library.name,
+ "CFBundleDisplayName": library.name,
+ "CFBundlePackageType": type.fourCharCode,
]
- if let plist = self.schema.base.infoPath {
+ switch type {
+ case .application:
+ infoPlist["UIDeviceFamily"] = [1, 2]
+ infoPlist["UISupportedInterfaceOrientations"] = ["UIInterfaceOrientationPortrait"]
+ infoPlist["UISupportedInterfaceOrientations~ipad"] = [
+ "UIInterfaceOrientationPortrait",
+ "UIInterfaceOrientationPortraitUpsideDown",
+ "UIInterfaceOrientationLandscapeLeft",
+ "UIInterfaceOrientationLandscapeRight",
+ ]
+ infoPlist["UILaunchScreen"] = [:] as [String: Sendable]
+ case .appExtension:
+ // Should set default parameters?
+ infoPlist["NSExtension"] = [:] as [String: Sendable]
+ }
+
+ if let plist {
let data = try await Data(reading: URL(fileURLWithPath: plist))
let info = try PropertyListSerialization.propertyList(from: data, format: nil)
if let info = info as? [String: Sendable] {
@@ -148,21 +200,45 @@ public struct Planner: Sendable {
}
}
- return Plan(
+ return Plan.Product(
+ type: type,
product: library.name,
deploymentTarget: deploymentTarget,
bundleID: bundleID,
infoPlist: infoPlist,
resources: resources,
- iconPath: self.schema.base.iconPath,
- entitlementsPath: self.schema.base.entitlementsPath
+ iconPath: iconPath,
+ entitlementsPath: entitlementsPath
+ )
+ }
+
+ private func dumpDependencies() async throws -> PackageDependency {
+ let tempDir = try TemporaryDirectory(name: "xtool-dump-\(UUID().uuidString)")
+ let tempFileURL = tempDir.url.appendingPathComponent("dump.json")
+
+ // SwiftPM sometimes prints extraneous data to stdout, so ask
+ // it to write the JSON to a temp file instead. See:
+ // https://github.com/xtool-org/xtool/pull/97#discussion_r2203618825
+ _ = try await _dumpAction(
+ arguments: ["-q", "show-dependencies", "--format", "json", "-o", tempFileURL.path],
+ path: buildSettings.packagePath
+ )
+
+ return try Self.decoder.decode(
+ PackageDependency.self,
+ from: Data(contentsOf: tempFileURL)
)
}
private func dumpPackage(at path: String) async throws -> PackageDump {
- let data = try await _dumpAction(arguments: ["describe", "--type", "json"], path: path)
+ let data = try await _dumpAction(arguments: ["-q", "describe", "--type", "json"], path: path)
try Task.checkCancellation()
- return try Self.decoder.decode(PackageDump.self, from: data)
+
+ // As in dumpDependencies, we may end up with extraneous data, but `describe`
+ // doesn't have a `-o` flag for a clean workaround. Resort to a heuristic,
+ // looking for the opening brace.
+ let fromBrace = data.drop(while: { $0 != Character("{").asciiValue })
+ return try Self.decoder.decode(PackageDump.self, from: fromBrace)
}
private func _dumpAction(arguments: [String], path: String) async throws -> Data {
@@ -213,20 +289,66 @@ public struct Planner: Sendable {
}
public struct Plan: Sendable {
- public var product: String
- public var deploymentTarget: String
- public var bundleID: String
- public var infoPlist: [String: any Sendable]
- public var resources: [Resource]
- public var iconPath: String?
- public var entitlementsPath: String?
-}
+ public var app: Product
+ public var extensions: [Product]
+
+ public var allProducts: [Product] {
+ [app] + extensions
+ }
+
+ public enum Resource: Codable, Sendable, Hashable {
+ case bundle(package: String, target: String)
+ case binaryTarget(name: String)
+ case library(name: String)
+ case root(source: String)
+ }
+
+ public struct Product: Sendable {
+ public var type: ProductType
+ public var product: String
+ public var deploymentTarget: String
+ public var bundleID: String
+ public var infoPlist: [String: any Sendable]
+ public var resources: [Resource]
+ public var iconPath: String?
+ public var entitlementsPath: String?
+
+ public var targetName: String {
+ "\(self.product)-\(self.type.targetSuffix)"
+ }
+
+ public func directory(inApp baseDir: URL) -> URL {
+ switch type {
+ case .application:
+ baseDir
+ .appendingPathComponent(".", isDirectory: true)
+ case .appExtension:
+ baseDir
+ .appendingPathComponent("PlugIns", isDirectory: true)
+ .appendingPathComponent(product, isDirectory: true)
+ .appendingPathExtension("appex")
+ }
+ }
+ }
-public enum Resource: Codable, Sendable {
- case bundle(package: String, target: String)
- case binaryTarget(name: String)
- case library(name: String)
- case root(source: String)
+ public enum ProductType: Sendable {
+ case application
+ case appExtension
+
+ fileprivate var targetSuffix: String {
+ switch self {
+ case .application: "App"
+ case .appExtension: "Extension"
+ }
+ }
+
+ fileprivate var fourCharCode: String {
+ switch self {
+ case .application: "APPL"
+ case .appExtension: "XPC!"
+ }
+ }
+ }
}
private struct PackageDependency: Decodable {
@@ -302,3 +424,22 @@ private struct PackageDump: Decodable {
let targets: [Target]?
let platforms: [Platform]?
}
+
+private struct PackageGraph {
+ let root: PackageDump
+ let packages: [String: PackageDump]
+ let packagesByProductName: [String: String]
+
+ func product(name productName: String) throws -> (PackageDump, PackageDump.Product) {
+ guard let packageID = packagesByProductName[productName] else {
+ throw StringError("Could not find package containing product '\(productName)'")
+ }
+ guard let package = packages[packageID] else {
+ throw StringError("Could not find package by id '\(packageID)'")
+ }
+ guard let product = package.products?.first(where: { $0.name == productName }) else {
+ throw StringError("Could not find product '\(productName)' in package '\(packageID)'")
+ }
+ return (package, product)
+ }
+}
diff --git a/Sources/PackLib/XcodePacker.swift b/Sources/PackLib/XcodePacker.swift
index af39c5c..c9f828d 100644
--- a/Sources/PackLib/XcodePacker.swift
+++ b/Sources/PackLib/XcodePacker.swift
@@ -15,67 +15,91 @@ public struct XcodePacker {
// swiftlint:disable:next function_body_length
public func createProject() async throws -> URL {
- let targetName = "\(plan.product)-App"
-
let xtoolDir: Path = "xtool"
let projectDir: Path = xtoolDir + ".xtool-tmp"
try? xtoolDir.delete()
try projectDir.mkpath()
- let infoPath = projectDir + "Info.plist"
+ let fromProjectToRoot = try Path(".").relativePath(from: projectDir)
- var plist = plan.infoPlist
- let families = (plist.removeValue(forKey: "UIDeviceFamily") as? [Int]) ?? [1, 2]
- plist["CFBundleExecutable"] = targetName
- plist["CFBundleName"] = targetName
- plist["CFBundleDisplayName"] = plan.product
+ guard let deploymentTarget = Version(tolerant: plan.app.deploymentTarget) else {
+ throw StringError("Could not parse deployment target '\(plan.app.deploymentTarget)'")
+ }
- let encodedPlist = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
- try infoPath.write(encodedPlist)
+ let emptyText = Data("""
+ // leave this file empty
+ """.utf8)
- let emptyFile = projectDir + "empty.c"
- try emptyFile.write(Data("// leave this file empty".utf8))
+ let targets = try plan.allProducts.map { product in
+ let productDir = projectDir + product.product
+ try productDir.mkpath()
- let fromProjectToRoot = try Path(".").relativePath(from: projectDir)
+ let emptyFile = productDir + "empty.c"
+ try emptyFile.write(emptyText)
- guard let deploymentTarget = Version(tolerant: plan.deploymentTarget) else {
- throw StringError("Could not parse deployment target '\(plan.deploymentTarget)'")
- }
+ let infoPath = productDir + "Info.plist"
- var buildSettings: [String: Any] = [
- "PRODUCT_BUNDLE_IDENTIFIER": plan.bundleID,
- "TARGETED_DEVICE_FAMILY": families.map { "\($0)" }.joined(separator: ","),
- ]
+ var plist = product.infoPlist
+ let families = (plist.removeValue(forKey: "UIDeviceFamily") as? [Int]) ?? [1, 2]
+ plist["CFBundleExecutable"] = product.targetName
+ plist["CFBundleName"] = product.targetName
+ plist["CFBundleDisplayName"] = product.product
- if let entitlementsPath = plan.entitlementsPath {
- buildSettings["CODE_SIGN_ENTITLEMENTS"] = fromProjectToRoot + Path(entitlementsPath)
- }
+ let encodedPlist = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
+ try infoPath.write(encodedPlist)
- let project = Project(
- name: plan.product,
- targets: [
- Target(
- name: targetName,
- type: .application,
- platform: .iOS,
- deploymentTarget: deploymentTarget,
- settings: Settings(buildSettings: buildSettings),
- sources: [
- TargetSource(path: (fromProjectToRoot + emptyFile).string),
- ],
- dependencies: [
- Dependency(
- type: .package(products: [plan.product]),
- reference: "RootPackage"
- ),
- ],
- info: Plist(
- path: (fromProjectToRoot + infoPath).string,
- attributes: [:]
+ var buildSettings: [String: Any] = [
+ "PRODUCT_BUNDLE_IDENTIFIER": product.bundleID,
+ "TARGETED_DEVICE_FAMILY": families.map { "\($0)" }.joined(separator: ","),
+ ]
+
+ if product.type == .appExtension {
+ buildSettings["APPLICATION_EXTENSION_API_ONLY"] = true
+ }
+
+ if let entitlementsPath = product.entitlementsPath {
+ buildSettings["CODE_SIGN_ENTITLEMENTS"] = fromProjectToRoot + Path(entitlementsPath)
+ }
+
+ let additionalDependencies: [Dependency] = if product.type == .application {
+ plan.extensions.map {
+ Dependency(
+ type: .target,
+ reference: $0.targetName
)
+ }
+ } else {
+ []
+ }
+ return Target(
+ name: product.targetName,
+ type: product.type == .application ? .application : .appExtension,
+ platform: .iOS,
+ deploymentTarget: deploymentTarget,
+ settings: Settings(buildSettings: buildSettings),
+ sources: [
+ TargetSource(
+ path: try emptyFile.relativePath(from: projectDir).string,
+ buildPhase: .sources
+ ),
+ ],
+ dependencies: [
+ Dependency(
+ type: .package(products: [product.product]),
+ reference: "RootPackage"
+ ),
+ ] + additionalDependencies,
+ info: Plist(
+ path: try infoPath.relativePath(from: projectDir).string,
+ attributes: [:]
)
- ],
+ )
+ }
+
+ let project = Project(
+ name: plan.app.targetName,
+ targets: targets,
packages: [
"RootPackage": .local(
path: fromProjectToRoot.string,
@@ -92,8 +116,8 @@ public struct XcodePacker {
// TODO: Handle plan.iconPath
let generator = ProjectGenerator(project: project)
- let xcodeproj = projectDir + "\(plan.product).xcodeproj"
- let xcworkspace = xtoolDir + "\(plan.product).xcworkspace"
+ let xcodeproj = projectDir + "\(plan.app.product).xcodeproj"
+ let xcworkspace = xtoolDir + "\(plan.app.product).xcworkspace"
do {
let current = Path.current
Path.current = xcodeproj.parent()
@@ -106,18 +130,6 @@ public struct XcodePacker {
xcodeProject.pbxproj.delete(object: packageRef)
}
- if let emptyFileRef = xcodeProject.pbxproj.fileReferences.first(where: { $0.path == "empty.c" }),
- let existingGroup = xcodeProject.pbxproj.groups.first(where: {
- $0.children.contains { $0.uuid == emptyFileRef.uuid }
- }),
- let existingGroupGroup = xcodeProject.pbxproj.groups.first(where: {
- $0.children.contains { $0.uuid == existingGroup.uuid }
- }) {
- existingGroupGroup.children.removeAll(where: { $0.uuid == existingGroup.uuid })
- existingGroupGroup.children.insert(emptyFileRef, at: 0)
- xcodeProject.pbxproj.delete(object: existingGroup)
- }
-
try xcodeProject.write(path: Path(xcodeproj.lastComponent))
}
diff --git a/Sources/XKit/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift b/Sources/XKit/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
index 8848ccc..7db2689 100644
--- a/Sources/XKit/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
+++ b/Sources/XKit/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
@@ -235,8 +235,10 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
/// Registers the app + its extensions, returning the profile and entitlements of each
public func perform() async throws -> [URL: ProvisioningInfo] {
var apps: [URL] = [root]
- let plugins = root.appendingPathComponent("PlugIns")
- if plugins.dirExists {
+
+ for pluginsDir in ["PlugIns", "Extensions"] {
+ let plugins = root.appendingPathComponent(pluginsDir)
+ guard plugins.dirExists else { continue }
apps += plugins.implicitContents.filter { $0.pathExtension.lowercased() == "appex" }
}
diff --git a/Sources/XKit/Signer/SignerImpl.swift b/Sources/XKit/Signer/SignerImpl.swift
index 6dda1e9..3217a95 100644
--- a/Sources/XKit/Signer/SignerImpl.swift
+++ b/Sources/XKit/Signer/SignerImpl.swift
@@ -152,6 +152,9 @@ public actor Signer {
entitlementMapping: [URL: Entitlements],
progress: @escaping (Double?) -> Void
) async throws {
+ // TODO: #131: update Zupersign to handle multiple entitlements files
+ // this is a temp hack to just pass along the root app entitlements
+ let entitlementMapping = entitlementMapping.filter { $0.key.path == app.path }
try self._sign(
app: app,
identity: identity,
diff --git a/Sources/XToolSupport/DevCommand.swift b/Sources/XToolSupport/DevCommand.swift
index 42d55b0..d2a57ff 100644
--- a/Sources/XToolSupport/DevCommand.swift
+++ b/Sources/XToolSupport/DevCommand.swift
@@ -64,15 +64,26 @@ struct PackOperation {
)
let bundle = try await packer.pack()
- if let entitlementsPath = plan.entitlementsPath {
- let data = try await Data(reading: URL(fileURLWithPath: entitlementsPath))
- let decoder = PropertyListDecoder()
- let entitlements = try decoder.decode(Entitlements.self, from: data)
+ let productsWithEntitlements = plan
+ .allProducts
+ .compactMap { p in p.entitlementsPath.map { (p, $0) } }
+ if !productsWithEntitlements.isEmpty {
+ let mapping = try await withThrowingTaskGroup(of: (URL, Entitlements).self) { group in
+ for (product, path) in productsWithEntitlements {
+ group.addTask {
+ let data = try await Data(reading: URL(fileURLWithPath: path))
+ let decoder = PropertyListDecoder()
+ let entitlements = try decoder.decode(Entitlements.self, from: data)
+ return (product.directory(inApp: bundle), entitlements)
+ }
+ }
+ return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
+ }
print("Pseudo-signing...")
try await Signer.first().sign(
app: bundle,
identity: .adhoc,
- entitlementMapping: [bundle: entitlements],
+ entitlementMapping: mapping,
progress: { _ in }
)
}