Modern Apps git

← xtool.git

Integrate swiftpack

Commit
dd04f66cb6ed427698770fddaa07c2de5b207ecb
Author
Kabir Oberai <[email protected]>
When
2024-12-31 12:09 UTC (1 year ago)
Parents
026f4f6

Diff

Package.resolved
diff --git a/Package.resolved b/Package.resolvedindex 907580a..7ee587d 100644--- a/Package.resolved+++ b/Package.resolved@@ -1,5 +1,5 @@ {-  "originHash" : "19c490b9f4eaa20eede93f53a3b352116957402a682ed84a47bfaf23c195de03",+  "originHash" : "360bc3ae9f3e8613a4fb4b6583a90d4819977ed68df921d928f49717dad97299",   "pins" : [     {       "identity" : "aexml",@@ -316,15 +316,6 @@         "version" : "6.0.3"       }     },-    {-      "identity" : "swiftpack",-      "kind" : "remoteSourceControl",-      "location" : "https://github.com/kabiroberai/swiftpack",-      "state" : {-        "revision" : "3610144c5fd3b1a50c323476ac7f42cebb9780bc",-        "version" : "1.0.1"-      }-    },     {       "identity" : "swiftymobiledevice",       "kind" : "remoteSourceControl",
Package.swift
diff --git a/Package.swift b/Package.swiftindex 310d730..004c9a0 100644--- a/Package.swift+++ b/Package.swift@@ -29,7 +29,6 @@ let package = Package(     dependencies: [         .package(url: "https://github.com/SuperchargeApp/SuperchargeCore", .upToNextMinor(from: "1.2.0")),         .package(url: "https://github.com/SuperchargeApp/SwiftyMobileDevice", .upToNextMinor(from: "1.3.1")),-        .package(url: "https://github.com/kabiroberai/swiftpack", .upToNextMinor(from: "1.0.1")),         .package(url: "https://github.com/kabiroberai/zsign", .upToNextMinor(from: "1.3.0")),          .package(url: "https://github.com/apple/swift-system", from: "1.4.0"),@@ -51,6 +50,10 @@ let package = Package(          .package(url: "https://github.com/attaswift/BigInt", from: "5.5.0"),         .package(url: "https://github.com/mxcl/Version", from: "2.1.0"),+        .package(url: "https://github.com/jpsim/Yams", from: "5.1.3"),++        // TODO: just depend on tuist/XcodeProj instead+        .package(url: "https://github.com/yonaskolb/XcodeGen", from: "2.42.0"),     ],     targets: [         .systemLibrary(name: "CSupersette"),@@ -125,7 +128,7 @@ let package = Package(             dependencies: [                 "SwiftyMobileDevice",                 "Supersign",-                .product(name: "PackLib", package: "swiftpack"),+                "PackLib",                 .product(name: "ArgumentParser", package: "swift-argument-parser"),                 .product(name: "SystemPackage", package: "swift-system"),                 .product(name: "NIOPosix", package: "swift-nio"),@@ -133,6 +136,13 @@ let package = Package(             ],             cSettings: cSettings         ),+        .target(+            name: "PackLib",+            dependencies: [+                .product(name: "Yams", package: "Yams"),+                .product(name: "XcodeGenKit", package: "XcodeGen", condition: .when(platforms: [.macOS])),+            ]+        ),         .executableTarget(             name: "SupersignCLI",             dependencies: [
Sources/PackLib/BuildSettings.swift
diff --git a/Sources/PackLib/BuildSettings.swift b/Sources/PackLib/BuildSettings.swiftnew file mode 100644index 0000000..8c960a1--- /dev/null+++ b/Sources/PackLib/BuildSettings.swift@@ -0,0 +1,97 @@+import Foundation++public struct BuildSettings: Sendable {+    private static let customBinDir =+        // this is the same option used by SwiftPM itself for dev builds+        ProcessInfo.processInfo.environment["SWIFTPM_CUSTOM_BIN_DIR"].map { URL(fileURLWithPath: $0) }++    private static let envURL = URL(fileURLWithPath: "/usr/bin/env")++    public let packagePath: String+    public let configuration: BuildConfiguration+    public let triple: String+    public let sdkOptions: [String]+    public let options: [String]++    public init(+        configuration: BuildConfiguration,+        packagePath: String = ".",+        options: [String] = []+    ) async throws {+        self.packagePath = packagePath+        self.configuration = configuration+        self.options = options++        // TODO: allow customizing?+        self.triple = "arm64-apple-ios"++        #if os(macOS)+        let sdkPath = try await Self.xcrun(["-show-sdk-path", "--sdk", "iphoneos"])+        self.sdkOptions = [+            "--triple", triple,+            "--sdk", sdkPath,+        ]+        #else+        self.sdkOptions = [+            "--swift-sdk", triple+        ]+        #endif+    }++    #if os(macOS)+    private static func xcrun(_ arguments: [String]) async throws -> String {+        let xcrun = Process()+        let pipe = Pipe()+        xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")+        xcrun.arguments = arguments+        xcrun.standardOutput = pipe+        try await xcrun.runUntilExit()+        return String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)+            .trimmingCharacters(in: .whitespacesAndNewlines)+    }++    private static let swiftURL = Task {+        try await URL(fileURLWithPath: xcrun(["-f", "swift"]))+    }+    #endif++    public func swiftPMInvocation(+        forTool tool: String,+        arguments: [String],+        packagePathOverride: String? = nil+    ) async throws -> Process {+        let process = Process()++        let baseArguments: [String]+        if let customBinDir = Self.customBinDir {+            process.executableURL = customBinDir.appendingPathComponent("swift-\(tool)")+            baseArguments = []+        } else {+            #if os(macOS)+            // xcrun/libxcrun (via the /usr/bin/swift trampoline) is very trigger-happy+            // to add SDKROOT=.../MacOSX.sdk to our invocations. We avoid this by+            // 1) invoking the real swift executable (located with `xcrun -f`) and+            // 2) explicitly removing SDKROOT from the env, as it may be inherited+            // through the `swift run pack` invocation.+            process.executableURL = try await Self.swiftURL.value+            #else+            process.executableURL = try await ToolRegistry.locate("swift")+            #endif+            baseArguments = [tool]+        }++        var env = ProcessInfo.processInfo.environment+        env.removeValue(forKey: "SDKROOT")+        process.environment = env+        process.arguments = baseArguments + [+            "--package-path", packagePathOverride ?? packagePath,+            "--configuration", configuration.rawValue,+        ] + sdkOptions + options + arguments+        return process+    }+}++public enum BuildConfiguration: String, CaseIterable, Sendable {+    case debug+    case release+}
Sources/PackLib/Foundation+Utils.swift
diff --git a/Sources/PackLib/Foundation+Utils.swift b/Sources/PackLib/Foundation+Utils.swiftnew file mode 100644index 0000000..e2feb82--- /dev/null+++ b/Sources/PackLib/Foundation+Utils.swift@@ -0,0 +1,56 @@+import Foundation++struct TemporaryDirectory: ~Copyable {+    private var shouldDelete = true++    let url: URL++    init(name: String) throws {+        self.url = FileManager.default.temporaryDirectory.appendingPathComponent(name, isDirectory: true)+        _delete()+        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+    }++    private func _delete() {+        try? FileManager.default.removeItem(at: url)+    }++    consuming func persist() -> URL {+        shouldDelete = false+        return url+    }++    consuming func persist(at location: URL) throws {+        try FileManager.default.moveItem(at: url, to: location)+        // we do this after moving, so that if the move fails we clean up+        shouldDelete = false+    }++    deinit {+        if shouldDelete { _delete() }+    }+}++extension Data {+    // AsyncBytes is Darwin-only :/++    package init(reading fileHandle: FileHandle) async throws {+        #if canImport(Darwin)+        self = try await fileHandle.bytes.reduce(into: Data()) { $0.append($1) }+        #else+        self = try fileHandle.readToEnd() ?? Data()+        #endif+    }++    package init(reading file: URL) async throws {+        #if canImport(Darwin)+        self = try await file.resourceBytes.reduce(into: Data()) { $0.append($1) }+        #else+        try self.init(contentsOf: file)+        #endif+    }+}++package func stderrPrint(_ message: String, terminator: String = "\n") {+    try? FileHandle.standardError.write(contentsOf: Data("\(message)\(terminator)".utf8))+}
Sources/PackLib/PackSchema.swift
diff --git a/Sources/PackLib/PackSchema.swift b/Sources/PackLib/PackSchema.swiftnew file mode 100644index 0000000..2073fa7--- /dev/null+++ b/Sources/PackLib/PackSchema.swift@@ -0,0 +1,62 @@+import Foundation+import Yams++public struct PackSchemaBase: Codable, Sendable {+    public enum Version: Int, Codable, Sendable {+        case v1 = 1+    }++    public var version: Version++    public var orgID: String?+    public var bundleID: String?++    public var product: String?++    public var infoPath: String?+}++public struct PackSchema: Sendable {+    public enum IDSpecifier: Sendable {+        case orgID(String)+        case bundleID(String)++        func formBundleID(product: String) -> String {+            switch self {+            case .orgID(let orgID): "\(orgID).\(product)"+            case .bundleID(let bundleID): bundleID+            }+        }+    }++    public let base: PackSchemaBase+    public let idSpecifier: IDSpecifier++    public init(validating base: PackSchemaBase) throws {+        self.base = base++        if base.version != .v1 {+            throw StringError("supersign.yml: Unsupported schema version: \(base.version.rawValue)")+        }++        switch (base.bundleID, base.orgID) {+        case (let bundleID?, _):+            idSpecifier = .bundleID(bundleID)+        case (nil, let orgID?):+            idSpecifier = .orgID(orgID)+        case (nil, nil):+            throw StringError("supersign.yml: Must specify either orgID or bundleID")+        }+    }++    public static let `default` = try! PackSchema(validating: .init(+        version: .v1,+        orgID: "com.example"+    ))++    public init(url: URL) async throws {+        let data = try await Data(reading: url)+        let base = try YAMLDecoder().decode(PackSchemaBase.self, from: data)+        try self.init(validating: base)+    }+}
Sources/PackLib/Packer.swift
diff --git a/Sources/PackLib/Packer.swift b/Sources/PackLib/Packer.swiftnew file mode 100644index 0000000..748d1e2--- /dev/null+++ b/Sources/PackLib/Packer.swift@@ -0,0 +1,136 @@+import Foundation++public struct Packer: Sendable {+    public let buildSettings: BuildSettings+    public let plan: Plan++    public init(buildSettings: BuildSettings, plan: Plan) {+        self.plan = plan+        self.buildSettings = buildSettings+    }++    private func build() async throws {+        let supersignDir = URL(fileURLWithPath: "supersign")+        let packageDir = supersignDir.appendingPathComponent(".supersign-tmp")+        try? FileManager.default.removeItem(at: packageDir)+        try FileManager.default.createDirectory(at: packageDir, withIntermediateDirectories: true)++        let packageSwift = packageDir.appendingPathComponent("Package.swift")+        let contents = """+        // swift-tools-version: 6.0+        import PackageDescription+        let package = Package(+            name: "\(plan.product)-Builder",+            platforms: [+                .iOS("\(plan.deploymentTarget)"),+            ],+            dependencies: [+                .package(name: "RootPackage", path: "../.."),+            ],+            targets: [+                .executableTarget(+                    name: "\(plan.product)-App",+                    dependencies: [+                        .product(name: "\(plan.product)", package: "RootPackage"),+                    ]+                ),+            ]+        )\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"))++        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.)+                // fortunately we've already resolved the root package by this point+                // 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+        try await builder.runUntilExit()+    }++    public func pack() async throws -> URL {+        try await build()++        let output = try TemporaryDirectory(name: "\(plan.product).app")++        let binDir = URL(+            fileURLWithPath: ".build/\(buildSettings.triple)/\(buildSettings.configuration.rawValue)",+            isDirectory: true+        )++        let outputURL = output.url+        @Sendable func packFile(srcName: String, dstName: String? = nil, sign: Bool = false) async throws {+            let srcURL = URL(fileURLWithPath: srcName, relativeTo: binDir)+            let dstURL = URL(fileURLWithPath: dstName ?? srcURL.lastPathComponent, relativeTo: outputURL)+            try? FileManager.default.createDirectory(at: dstURL.deletingLastPathComponent(), withIntermediateDirectories: true)+            try FileManager.default.copyItem(at: srcURL, to: dstURL)++            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+                        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)+                    }+                }+            }+            group.addTask {+                try await packFile(srcName: "\(plan.product)-App", dstName: plan.product)+            }+            group.addTask {+                let infoPath = outputURL.appendingPathComponent("Info.plist")+                let encodedPlist = try PropertyListSerialization.data(+                    fromPropertyList: plan.infoPlist,+                    format: .xml,+                    options: 0+                )+                try encodedPlist.write(to: infoPath)+            }+            while !group.isEmpty {+                do {+                    try await group.next()+                } catch is CancellationError {+                    // continue+                } catch {+                    group.cancelAll()+                    throw error+                }+            }+        }++        let dest = URL(fileURLWithPath: "supersign")+            .appendingPathComponent(output.url.lastPathComponent)+        try? FileManager.default.removeItem(at: dest)+        try output.persist(at: dest)+        return dest+    }+}
Sources/PackLib/Planner.swift
diff --git a/Sources/PackLib/Planner.swift b/Sources/PackLib/Planner.swiftnew file mode 100644index 0000000..4aeb431--- /dev/null+++ b/Sources/PackLib/Planner.swift@@ -0,0 +1,295 @@+import Foundation++public struct Planner: Sendable {+    public var buildSettings: BuildSettings+    public var schema: PackSchema++    public init(+        buildSettings: BuildSettings,+        schema: PackSchema+    ) {+        self.buildSettings = buildSettings+        self.schema = schema+    }++    private static let decoder: JSONDecoder = {+        let decoder = JSONDecoder()+        decoder.keyDecodingStrategy = .convertFromSnakeCase+        return decoder+    }()++    public func createPlan() async throws -> Plan {+        // TODO: cache plan using (Package.swift+Package.resolved) as the key?++        let dependencyData = try await _dumpAction(+            arguments: ["show-dependencies", "--format", "json"],+            path: buildSettings.packagePath+        )+        let dependencyRoot = try Self.decoder.decode(PackageDependency.self, from: dependencyData)++        let packages = try await withThrowingTaskGroup(+            of: (PackageDependency, PackageDump).self,+            returning: [String: PackageDump].self+        ) { group in+            var visited: Set<String> = []+            var dependencies: [PackageDependency] = [dependencyRoot]+            while let dependencyNode = dependencies.popLast() {+                guard visited.insert(dependencyNode.identity).inserted else { continue }+                dependencies.append(contentsOf: dependencyNode.dependencies)+                group.addTask { (dependencyNode, try await dumpPackage(at: dependencyNode.path)) }+            }++            var packages: [String: PackageDump] = [:]+            while let result = await group.nextResult() {+                switch result {+                case .success((let dependency, let dump)):+                    packages[dependency.identity] = dump+                case .failure(_ as CancellationError):+                    // continue loop+                    break+                case .failure(let error):+                    group.cancelAll()+                    throw error+                }+            }++            return packages+        }++        var packagesByProductName: [String: String] = [:]+        for (packageID, package) in packages {+            for product in package.products ?? [] {+                packagesByProductName[product.name] = packageID+            }+        }++        let rootPackage = packages[dependencyRoot.identity]!+        let deploymentTarget = rootPackage.platforms?.first { $0.name == "ios" }?.version ?? "13.0"++        let libraries = rootPackage.products?.filter { $0.type == .autoLibrary } ?? []++        let library = try selectLibrary(+            from: libraries,+            matching: schema.base.product+        )++        var resources: [Resource] = []+        var visited: Set<String> = []+        var targets = library.targets.map { (rootPackage, $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)'")+            }+            guard visited.insert(targetName).inserted else { continue }+            if target.moduleType == "BinaryTarget" {+                resources.append(.binaryTarget(name: targetName))+            }+            if target.resources?.isEmpty == false {+                resources.append(.bundle(package: targetPackage.name, target: targetName))+            }+            for targetName in (target.targetDependencies ?? []) {+                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)'")+                }+                if product.type == .dynamicLibrary {+                    resources.append(.library(name: productName))+                }+                targets.append(contentsOf: product.targets.map { (package, $0) })+            }+        }++        let bundleID = schema.idSpecifier.formBundleID(product: library.name)++        let infoPlist: [String: Sendable]+        if let plist = self.schema.base.infoPath {+            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] {+                infoPlist = info+            } else {+                throw StringError("Info.plist has invalid format: expected a dictionary.")+            }+        } else {+            infoPlist = [+                "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)",+            ]+        }++        return Plan(+            product: library.name,+            deploymentTarget: deploymentTarget,+            bundleID: bundleID,+            infoPlist: infoPlist,+            resources: resources+        )+    }++    private func dumpPackage(at path: String) async throws -> PackageDump {+        let data = try await _dumpAction(arguments: ["describe", "--type", "json"], path: path)+        try Task.checkCancellation()+        return try Self.decoder.decode(PackageDump.self, from: data)+    }++    private func _dumpAction(arguments: [String], path: String) async throws -> Data {+        let dump = try await buildSettings.swiftPMInvocation(+            forTool: "package",+            arguments: arguments,+            packagePathOverride: path+        )+        let pipe = Pipe()+        dump.standardOutput = pipe+        async let task = Data(reading: pipe.fileHandleForReading)+        try await dump.runUntilExit()+        return try await task+    }++    private func selectLibrary(+        from products: [PackageDump.Product],+        matching name: String?+    ) throws -> PackageDump.Product {+        switch products.count {+        case 0:+            throw StringError("No library products were found in the package")+        case 1:+            let product = products[0]+            if let name, product.name != name {+                throw StringError("""+                Product name ('\(product.name)') does not match the 'product' value in the schema ('\(name)')+                """)+            }+            return product+        default:+            guard let name else {+                throw StringError("""+                Multiple library products were found (\(products.map(\.name))). Please either:+                1) Expose exactly one library product, or+                2) Specify the product you want via the 'product' key in supersign.yml.+                """)+            }+            guard let product = products.first(where: { $0.name == name }) else {+                throw StringError("""+                Schema declares a 'product' name of '\(name)' but no matching product was found.+                Found: \(products.map(\.name)).+                """)+            }+            return product+        }+    }+}++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 enum Resource: Codable, Sendable {+    case bundle(package: String, target: String)+    case binaryTarget(name: String)+    case library(name: String)+}++private struct PackageDependency: Decodable {+    let identity: String+    let name: String+    let path: String // on disk+    let dependencies: [PackageDependency]+}++private struct PackageDump: Decodable {+    enum ProductType: Decodable {+        case executable+        case dynamicLibrary+        case staticLibrary+        case autoLibrary+        case other++        private enum CodingKeys: String, CodingKey {+            case executable+            case library+        }++        init(from decoder: Decoder) throws {+            let container = try decoder.container(keyedBy: CodingKeys.self)+            if container.contains(.executable) {+                self = .executable+            } else if let library = try container.decodeIfPresent([String].self, forKey: .library) {+                if library.count == 1 {+                    switch library[0] {+                    case "dynamic":+                        self = .dynamicLibrary+                    case "static":+                        self = .staticLibrary+                    case "automatic":+                        self = .autoLibrary+                    default:+                        self = .other+                    }+                } else {+                    self = .other+                }+            } else {+                self = .other+            }+        }+    }++    struct Product: Decodable {+        let name: String+        let targets: [String]+        let type: ProductType+    }++    struct Target: Decodable {+        let name: String+        let moduleType: String+        let productDependencies: [String]?+        let targetDependencies: [String]?+        let resources: [Resource]?+    }++    struct Resource: Decodable {+        let path: String+    }++    struct Platform: Decodable {+        let name: String+        let version: String+    }++    let name: String+    let products: [Product]?+    let targets: [Target]?+    let platforms: [Platform]?+}
Sources/PackLib/Process+Helpers.swift
diff --git a/Sources/PackLib/Process+Helpers.swift b/Sources/PackLib/Process+Helpers.swiftnew file mode 100644index 0000000..3b47bcb--- /dev/null+++ b/Sources/PackLib/Process+Helpers.swift@@ -0,0 +1,63 @@+import Foundation++extension Process {+    /// Launches the process and suspends until the receiver is finished.+    ///+    /// - Parameter onCancel: The action to take if the current+    /// task is cancelled.+    public func runUntilExit(onCancel: TaskCancelAction = .interrupt) async throws {+        try Task.checkCancellation()++        let (terminationStream, terminationContinuation) = AsyncStream<Never>.makeStream()+        terminationHandler = { _ in+            terminationContinuation.finish()+        }++        do {+            try run()+        } catch {+            terminationContinuation.finish()+            throw error+        }++        await withTaskCancellationHandler {+            for await _ in terminationStream {}+        } onCancel: {+            switch onCancel {+            case .interrupt:+                interrupt()+            case .terminate:+                terminate()+            case .ignore:+                break+            }+        }++        try Task.checkCancellation()++        switch terminationReason {+        case .exit where terminationStatus == 0:+            break+        case .exit:+            throw Failure.exit(terminationStatus)+        case .uncaughtSignal:+            throw Failure.uncaughtSignal(terminationStatus)+        @unknown default:+            break+        }+    }++    public enum Failure: Error {+        case exit(CInt)+        case uncaughtSignal(CInt)+    }++    public enum TaskCancelAction: Sendable {+        /// Sends `SIGINT` to the process.+        case interrupt+        /// Sends `SIGTERM` to the process.+        case terminate+        /// Don't participate in cooperative cancellation.+        case ignore+    }+}
Sources/PackLib/Stdlib+Utils.swift
diff --git a/Sources/PackLib/Stdlib+Utils.swift b/Sources/PackLib/Stdlib+Utils.swiftnew file mode 100644index 0000000..bc643b7--- /dev/null+++ b/Sources/PackLib/Stdlib+Utils.swift@@ -0,0 +1,6 @@+package struct StringError: Error, CustomStringConvertible {+    package var description: String+    package init(_ description: String) {+        self.description = description+    }+}
Sources/PackLib/ToolRegistry.swift
diff --git a/Sources/SupersignCLISupport/ToolRegistry.swift b/Sources/PackLib/ToolRegistry.swiftsimilarity index 64%rename from Sources/SupersignCLISupport/ToolRegistry.swiftrename to Sources/PackLib/ToolRegistry.swiftindex 8fd87c1..0d82e28 100644--- a/Sources/SupersignCLISupport/ToolRegistry.swift+++ b/Sources/PackLib/ToolRegistry.swift@@ -1,10 +1,10 @@ import Foundation -enum ToolRegistry {-    enum Errors: Error, CustomStringConvertible {+package enum ToolRegistry {+    package enum Errors: Error, CustomStringConvertible {         case toolNotFound(String) -        var description: String {+        package var description: String {             switch self {             case .toolNotFound(let tool):                 "Could not find executable '\(tool)' in PATH"@@ -14,7 +14,15 @@ enum ToolRegistry {      private static let cache = Cache() -    static func locate(_ tool: StaticString) async throws -> URL {+    /// Obtain the full path to a tool in the user's `PATH`.+    ///+    /// This effectively invokes `/bin/sh -c "command -v '$tool'"`.+    ///+    /// - Warning: Make sure you trust/sanitize the `tool` parameter. If it+    /// contains a single quote, it can be used in a shell escape.+    ///+    /// - Throws: `Errors.toolNotFound` if the tool could not be located.+    package static func locate(_ tool: String) async throws -> URL {         try await cache.locate(tool: tool)     } @@ -28,9 +36,9 @@ enum ToolRegistry {             proc.arguments = ["-c", "command -v '\(tool)'"]             proc.standardOutput = pipe             async let bytes = pipe.fileHandleForReading.readToEnd()-            try proc.run()-            await proc.waitForExit()-            guard proc.terminationStatus == 0 else {+            do {+                try await proc.runUntilExit()+            } catch is Process.Failure {                 throw Errors.toolNotFound(tool)             }             let path = String(decoding: try await bytes ?? Data(), as: UTF8.self)@@ -38,9 +46,7 @@ enum ToolRegistry {             return URL(fileURLWithPath: path)         } -        func locate(tool: StaticString) async throws -> URL {-            let tool = "\(tool)"-+        func locate(tool: String) async throws -> URL {             let task: Task<URL, Error>             if let cached = cache[tool] {                 task = cached
Sources/PackLib/XcodePacker.swift
diff --git a/Sources/PackLib/XcodePacker.swift b/Sources/PackLib/XcodePacker.swiftnew file mode 100644index 0000000..54f871e--- /dev/null+++ b/Sources/PackLib/XcodePacker.swift@@ -0,0 +1,140 @@+#if os(macOS)+import Foundation+import PathKit+import Version+import ProjectSpec+import XcodeGenKit+import XcodeProj++public struct XcodePacker {+    public var plan: Plan++    public init(plan: Plan) {+        self.plan = plan+    }++    public func createProject() async throws -> URL {+        let targetName = "\(plan.product)-App"++        let supersignDir: Path = "supersign"++        let projectDir: Path = supersignDir + ".supersign-tmp"+        try? supersignDir.delete()+        try projectDir.mkpath()++        let infoPath = projectDir + "Info.plist"++        var plist = plan.infoPlist+        let families = (plist.removeValue(forKey: "UIDeviceFamily") as? [Int]) ?? [1, 2]+        plist["CFBundleExecutable"] = targetName+        plist["CFBundleName"] = targetName+        plist["CFBundleDisplayName"] = plan.product++        let encodedPlist = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)+        try infoPath.write(encodedPlist)++        let emptyFile = projectDir + "empty.c"+        try emptyFile.write(Data("// leave this file empty".utf8))++        let fromProjectToRoot = try Path(".").relativePath(from: projectDir)++        guard let deploymentTarget = Version(tolerant: plan.deploymentTarget) else {+            throw StringError("Could not parse deployment target '\(plan.deploymentTarget)'")+        }++        let project = Project(+            name: plan.product,+            targets: [+                Target(+                    name: targetName,+                    type: .application,+                    platform: .iOS,+                    deploymentTarget: deploymentTarget,+                    settings: Settings(buildSettings: [+                        "PRODUCT_BUNDLE_IDENTIFIER": plan.bundleID,+                        "TARGETED_DEVICE_FAMILY": families.map { "\($0)" }.joined(separator: ","),+                    ]),+                    sources: [+                        TargetSource(path: (fromProjectToRoot + emptyFile).string),+                    ],+                    dependencies: [+                        Dependency(+                            type: .package(products: [plan.product]),+                            reference: "RootPackage"+                        ),+                    ],+                    info: Plist(+                        path: (fromProjectToRoot + infoPath).string,+                        attributes: [:]+                    )+                )+            ],+            packages: [+                "RootPackage": .local(+                    path: fromProjectToRoot.string,+                    group: nil+                ),+            ],+            options: SpecOptions(+                localPackagesGroup: ""+            )+        )+        let generator = ProjectGenerator(project: project)+        let xcodeproj = projectDir + "\(plan.product).xcodeproj"+        let xcworkspace = supersignDir + "\(plan.product).xcworkspace"+        do {+            let current = Path.current+            Path.current = xcodeproj.parent()+            defer { Path.current = current }+            let xcodeProject = try generator.generateXcodeProject(userName: NSUserName())+            if let packageRef = xcodeProject.pbxproj.fileReferences.first(where: { $0.name == ".." }) {+                for group in xcodeProject.pbxproj.groups {+                    group.children.removeAll(where: { $0.uuid == packageRef.uuid })+                }+                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))+        }++        do {+            let current = Path.current+            Path.current = xcworkspace.parent()+            defer { Path.current = current }++            let xcworkspaceDirectory = xcworkspace.parent()+            let fromWorkspaceToSelf = try Path(".").relativePath(from: xcworkspaceDirectory).withName()+            let fromWorkspaceToProject = try xcodeproj.relativePath(from: xcworkspaceDirectory).withName()+            let workspace = XCWorkspace(data: .init(children: [+                .file(.init(location: .container(fromWorkspaceToSelf.string))),+                .file(.init(location: .group(fromWorkspaceToProject.string))),+            ]))+            try workspace.write(path: Path(xcworkspace.lastComponent))+        }++        return xcworkspace.url+    }+}++extension Path {+    fileprivate func withName() -> Path {+        // eg if curr dir is Foo, this converts "." to "../Foo"+        // which includes the name in the path, and therefore+        // in the Xcode navigator+        self.parent() + self.absolute().lastComponent+    }+}++#endif
Sources/SupersignCLISupport/DevCommands/DevCommand.swift
diff --git a/Sources/SupersignCLISupport/DevCommands/DevCommand.swift b/Sources/SupersignCLISupport/DevCommands/DevCommand.swiftindex 4a51f3a..659bd11 100644--- a/Sources/SupersignCLISupport/DevCommands/DevCommand.swift+++ b/Sources/SupersignCLISupport/DevCommands/DevCommand.swift@@ -21,21 +21,22 @@ struct DevSetupCommand: AsyncParsableCommand { }  struct PackOperation {-    struct Options: ParsableArguments {+    struct BuildOptions: ParsableArguments {         @Option(             name: .shortAndLong,             help: "Build with configuration"         ) var configuration: BuildConfiguration = .debug     } -    var options: Options+    var buildOptions = BuildOptions()+    var xcode = false      @discardableResult     func run() async throws -> URL {         print("Planning...")          let schema: PackSchema-        let configPath = URL(fileURLWithPath: "swiftpack.yml")+        let configPath = URL(fileURLWithPath: "supersign.yml")         if FileManager.default.fileExists(atPath: configPath.path) {             schema = try await PackSchema(url: configPath)         } else {@@ -47,7 +48,7 @@ struct PackOperation {         }          let buildSettings = try await BuildSettings(-            configuration: options.configuration,+            configuration: buildOptions.configuration,             options: []         ) @@ -57,6 +58,12 @@ struct PackOperation {         )         let plan = try await planner.createPlan() +        #if os(macOS)+        if xcode {+            return try await XcodePacker(plan: plan).createProject()+        }+        #endif+         let packer = Packer(             buildSettings: buildSettings,             plan: plan@@ -65,20 +72,32 @@ struct PackOperation {     } } +struct DevXcodeCommand: AsyncParsableCommand {+    static let configuration = CommandConfiguration(+        commandName: "generate-xcode-project",+        abstract: "Generate Xcode project",+        discussion: "This option does nothing on Linux"+    )++    func run() async throws {+        try await PackOperation(xcode: true).run()+    }+}++ struct DevBuildCommand: AsyncParsableCommand {     static let configuration = CommandConfiguration(         commandName: "build",         abstract: "Build app with SwiftPM",         discussion: """-        This command builds the SwiftPM-based iOS app in the current directory \-        using https://github.com/kabiroberai/swiftpack+        This command builds the SwiftPM-based iOS app in the current directory         """     ) -    @OptionGroup var packOptions: PackOperation.Options+    @OptionGroup var packOptions: PackOperation.BuildOptions      func run() async throws {-        try await PackOperation(options: packOptions).run()+        try await PackOperation(buildOptions: packOptions).run()     } } @@ -87,17 +106,16 @@ struct DevRunCommand: AsyncParsableCommand {         commandName: "run",         abstract: "Build and run app with SwiftPM",         discussion: """-        This command deploys the SwiftPM-based iOS app in the current directory \-        using https://github.com/kabiroberai/swiftpack+        This command deploys the SwiftPM-based iOS app in the current directory         """     ) -    @OptionGroup var packOptions: PackOperation.Options+    @OptionGroup var packOptions: PackOperation.BuildOptions      @OptionGroup var connectionOptions: ConnectionOptions      func run() async throws {-        let output = try await PackOperation(options: packOptions).run()+        let output = try await PackOperation(buildOptions: packOptions).run()          let token = try AuthToken.saved() @@ -127,6 +145,7 @@ struct DevCommand: AsyncParsableCommand {             DevSetupCommand.self,             DevNewCommand.self,             DevSDKCommand.self,+            DevXcodeCommand.self,             DevBuildCommand.self,             DevRunCommand.self,         ],@@ -134,4 +153,4 @@ struct DevCommand: AsyncParsableCommand {     ) } -extension BuildConfiguration: @retroactive ExpressibleByArgument {}+extension BuildConfiguration: ExpressibleByArgument {}
Sources/SupersignCLISupport/DevCommands/DevNewCommand.swift
diff --git a/Sources/SupersignCLISupport/DevCommands/DevNewCommand.swift b/Sources/SupersignCLISupport/DevCommands/DevNewCommand.swiftindex da8189e..7aeb32e 100644--- a/Sources/SupersignCLISupport/DevCommands/DevNewCommand.swift+++ b/Sources/SupersignCLISupport/DevCommands/DevNewCommand.swift@@ -1,5 +1,6 @@ import ArgumentParser import Foundation+import PackLib  struct DevNewCommand: AsyncParsableCommand {     static let configuration = CommandConfiguration(@@ -62,7 +63,7 @@ struct DevNewCommand: AsyncParsableCommand {                         .macOS(.v14),                     ],                     products: [-                        // A Swiftpack project should contain exactly one library target,+                        // A Supersign project should contain exactly one library target,                         // representing the main app.                         .library(                             name: "\(moduleName)",@@ -79,7 +80,7 @@ struct DevNewCommand: AsyncParsableCommand {             ),              (-                "swiftpack.yml",+                "supersign.yml",                 """                 version: 1                 bundleID: com.example.\(name)@@ -98,7 +99,7 @@ struct DevNewCommand: AsyncParsableCommand {                 .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata                 .netrc                 -                /swiftpack+                /supersign                 /.sourcekit-lsp                 """             ),@@ -164,8 +165,7 @@ struct DevNewCommand: AsyncParsableCommand {         gitInit.executableURL = try await ToolRegistry.locate("git")         gitInit.arguments = ["init"]         gitInit.currentDirectoryURL = baseURL-        try gitInit.run()-        await gitInit.waitForExit()+        try await gitInit.runUntilExit()          print("\nFinished generating project \(name). Next steps:")         print("- Enter the directory with `cd \(name)`")
Sources/SupersignCLISupport/DevCommands/DevSDKCommand.swift
diff --git a/Sources/SupersignCLISupport/DevCommands/DevSDKCommand.swift b/Sources/SupersignCLISupport/DevCommands/DevSDKCommand.swiftindex 38c4c99..78a51d3 100644--- a/Sources/SupersignCLISupport/DevCommands/DevSDKCommand.swift+++ b/Sources/SupersignCLISupport/DevCommands/DevSDKCommand.swift@@ -3,6 +3,7 @@ import Supersign import Version import ArgumentParser import Dependencies+import PackLib  struct DevSDKCommand: AsyncParsableCommand {     static let configuration = CommandConfiguration(@@ -153,10 +154,10 @@ extension SwiftVersion {         swift.arguments = ["--version"]         swift.standardOutput = outPipe         swift.standardError = errPipe-        try swift.run()         async let outputTask = outPipe.fileHandleForReading.readToEnd()-        await swift.waitForExit()-        guard swift.terminationStatus == 0 else {+        do {+            try await swift.runUntilExit()+        } catch is Process.Failure {             throw Console.Error("Failed to obtain Swift version")         }         let outputData = try await outputTask@@ -226,9 +227,9 @@ struct InstallSDKOperation {             """,             "--checksum", item.checksum(for: arch)         ]-        try install.run()-        await install.waitForExit()-        guard install.terminationStatus == 0 else {+        do {+            try await install.runUntilExit()+        } catch is Process.Failure {             throw Console.Error("Failed to install SDK")         }         #endif
Sources/SupersignCLISupport/ProcessZIPCompressor.swift
diff --git a/Sources/SupersignCLISupport/ProcessZIPCompressor.swift b/Sources/SupersignCLISupport/ProcessZIPCompressor.swiftindex e63f984..b57a5b4 100644--- a/Sources/SupersignCLISupport/ProcessZIPCompressor.swift+++ b/Sources/SupersignCLISupport/ProcessZIPCompressor.swift@@ -1,13 +1,7 @@-//-//  File.swift-//  Supersign-//-//  Created by Kabir Oberai on 23/12/24.-//- import Foundation import Supersign import Dependencies+import PackLib  extension ZIPCompressor: DependencyKey {     // TODO: Use `powershell Compress-Archive` and `powershell Expand-Archive` on Windows@@ -22,11 +16,7 @@ extension ZIPCompressor: DependencyKey {             zip.executableURL = try await ToolRegistry.locate("zip")             zip.currentDirectoryURL = dir.deletingLastPathComponent()             zip.arguments = ["-yqru0", dest.path, "Payload"]-            try zip.run()-            await zip.waitForExit()-            guard zip.terminationStatus == 0 else {-                throw ZIPCompressorError.compressionFailed-            }+            try await zip.runUntilExit()              return dest         },@@ -35,16 +25,7 @@ extension ZIPCompressor: DependencyKey {             let unzip = Process()             unzip.executableURL = try await ToolRegistry.locate("unzip")             unzip.arguments = ["-q", ipa.path, "-d", directory.path]-            try unzip.run()-            await unzip.waitForExit()-            guard unzip.terminationStatus == 0 else {-                throw ZIPCompressorError.decompressionFailed-            }+            try await unzip.runUntilExit()         }     ) }--enum ZIPCompressorError: Error {-    case compressionFailed-    case decompressionFailed-}