Modern Apps git

← xtool.git

packer: use XcodeProjectFormat for generate-xcode-project (#300)

Commit
8f0cc0adf1c4f01d875842040170221820c23a2d
Author
Kabir Oberai <[email protected]>
When
2026-10-06 22:19 UTC (2 months ago)
Parents
491fe2f
## What does this PR do?

Improves `xtool dev generate-xcode-project`. Instead of constructing an
XcodeGen project, we directly construct an xcodeproj (with the new
xcproj format) using
[apple/xcode-project-format](https://github.com/apple/xcode-project-format).
For now, we still rely on
[Tuist/XcodeProj](https://github.com/tuist/XcodeProj) to translate it
back into a pbxproj for maximal compatibility, but this is treated as an
implementation detail.

Also adds support for resources and icons in the generated Xcode project

## How was it tested?

- [x] Generated a simple project, opened it, and ran the app

## AI tool usage

How much of this PR was AI-assisted? (check one)

- [ ] **0** - No AI was used to write code
- [x] **1** - I was assisted by AI. I reviewed the finished result.
- [ ] **2** - I set the AI going and left it to it; nobody has read the
result - no review, or AI review only

<!-- If an AI agent is filling this in: declare the level honestly, and
open as a draft if it is #2. Do not lower the declared level to get the
PR reviewed. -->


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added support for creating and saving Xcode projects and workspaces in
`.pbxproj` and `.xcproj` formats.
* Added tools for opening, converting, and writing project and workspace
files, including workspace contents.
* Project generation can target a specified directory, and the command
reports where the project was created.
  * Project generation is available on non-macOS platforms.
* Generated projects include product settings and references for
packages, resources, icons, and app extensions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Diff

Package.resolved
diff --git a/Package.resolved b/Package.resolvedindex 10de66b..38d8f63 100644--- a/Package.resolved+++ b/Package.resolved@@ -1,5 +1,5 @@ {-  "originHash" : "23134cf3fab2ed308c844bd3240285be6a7e070b43a9e75366896971e0c380c1",+  "originHash" : "72833caa0d28404618b540ad08cbaa72d65446a56dc70dfd3ff2790a48c9fdda",   "pins" : [     {       "identity" : "aexml",@@ -37,15 +37,6 @@         "version" : "1.2.2"       }     },-    {-      "identity" : "jsonutilities",-      "kind" : "remoteSourceControl",-      "location" : "https://github.com/yonaskolb/JSONUtilities.git",-      "state" : {-        "revision" : "128d2ffc22467f69569ef8ff971683e2393191a0",-        "version" : "4.2.0"-      }-    },     {       "identity" : "openapikit",       "kind" : "remoteSourceControl",@@ -73,15 +64,6 @@         "version" : "1.0.1"       }     },-    {-      "identity" : "rainbow",-      "kind" : "remoteSourceControl",-      "location" : "https://github.com/onevcat/Rainbow.git",-      "state" : {-        "revision" : "711ca908ca19d16e577d575c8d0a48151a16bb1b",-        "version" : "4.2.2"-      }-    },     {       "identity" : "spectre",       "kind" : "remoteSourceControl",@@ -397,15 +379,6 @@         "version" : "1.8.1"       }     },-    {-      "identity" : "swiftcli",-      "kind" : "remoteSourceControl",-      "location" : "https://github.com/jakeheis/SwiftCLI.git",-      "state" : {-        "revision" : "2e949055d9797c1a6bddcda0e58dada16cc8e970",-        "version" : "6.0.3"-      }-    },     {       "identity" : "swiftymobiledevice",       "kind" : "remoteSourceControl",@@ -452,12 +425,12 @@       }     },     {-      "identity" : "xcodegen",+      "identity" : "xcode-project-format",       "kind" : "remoteSourceControl",-      "location" : "https://github.com/yonaskolb/XcodeGen",+      "location" : "https://github.com/apple/xcode-project-format.git",       "state" : {-        "revision" : "8445e778451c7e44237b90281bde622d764b0084",-        "version" : "2.46.0"+        "revision" : "c132630aabf40f6d6c3f7bb004595d2e5a28ea42",+        "version" : "0.1.0"       }     },     {@@ -465,8 +438,8 @@       "kind" : "remoteSourceControl",       "location" : "https://github.com/tuist/XcodeProj.git",       "state" : {-        "revision" : "eb001108f64467b0cc7e8cbf90b3b4aaa1822cbb",-        "version" : "9.14.0"+        "revision" : "aeea2e97376cd69fbdd1c7e68664b79a1a641dde",+        "version" : "9.17.5"       }     },     {
Package.swift
diff --git a/Package.swift b/Package.swiftindex ebb159b..132ddf5 100644--- a/Package.swift+++ b/Package.swift@@ -65,6 +65,7 @@ let package = Package(         // v1.7.0 has a crash on old OSes: https://github.com/apple/swift-collections/issues/733.         // pin 1.6.0 until 1.7.1 is released.         .package(url: "https://github.com/apple/swift-collections", exact: "1.6.0"),+        .package(url: "https://github.com/apple/xcode-project-format.git", .upToNextMinor(from: "0.1.0")),          .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"),         .package(url: "https://github.com/swiftlang/swift-subprocess", from: "1.0.0"),@@ -84,8 +85,8 @@ let package = Package(         .package(url: "https://github.com/jpsim/Yams", from: "5.1.3"),         .package(url: "https://github.com/saagarjha/unxip", from: "3.2.0"), -        // TODO: just depend on tuist/XcodeProj instead-        .package(url: "https://github.com/yonaskolb/XcodeGen", from: "2.45.4"),+        // NB: this should only be imported from XcodeProjects+        .package(url: "https://github.com/tuist/XcodeProj.git", from: "9.17.5"),     ],     targets: [         .target(@@ -165,6 +166,7 @@ let package = Package(             dependencies: [                 "XKit",                 "XToolSupport",+                "PackLib",             ],             swiftSettings: swiftSettings,         ),@@ -177,19 +179,27 @@ let package = Package(                 .product(name: "ArgumentParser", package: "swift-argument-parser"),                 .product(name: "SystemPackage", package: "swift-system"),                 .product(name: "NIOPosix", package: "swift-nio"),-                .product(name: "Version", package: "Version"),                 .product(name: "libunxip", package: "unxip"),             ],             cSettings: cSettings,             swiftSettings: swiftSettings,         ),+        .target(+            name: "XcodeProjects",+            dependencies: [+                .product(name: "XcodeProj", package: "XcodeProj"),+                .product(name: "XcodeProjectFormat", package: "xcode-project-format"),+            ],+        ),         .target(             name: "PackLib",             dependencies: [                 "XUtils",+                "XcodeProjects",                 .product(name: "Superutils", package: "xtool-core"),                 .product(name: "Yams", package: "Yams"),-                .product(name: "XcodeGenKit", package: "XcodeGen", condition: .when(platforms: [.macOS])),+                .product(name: "Version", package: "Version"),+                .product(name: "XcodeProjectFormat", package: "xcode-project-format"),             ],             swiftSettings: swiftSettings,         ),
Sources/PackLib/XcodePacker.swift
diff --git a/Sources/PackLib/XcodePacker.swift b/Sources/PackLib/XcodePacker.swiftindex 1126d58..d679ea7 100644--- a/Sources/PackLib/XcodePacker.swift+++ b/Sources/PackLib/XcodePacker.swift@@ -1,10 +1,5 @@-#if os(macOS) import Foundation-import PathKit-import Version-import ProjectSpec-import XcodeGenKit-import XcodeProj+import XcodeProjects  public struct XcodePacker {     public var plan: Plan@@ -14,151 +9,284 @@ public struct XcodePacker {     }      // swiftlint:disable:next function_body_length-    public func createProject() async throws -> URL {-        let xtoolDir: Path = "xtool"+    public func createProject(+        at root: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)+    ) async throws -> URL {+        let xtoolDir = root.appendingPathComponent("xtool", isDirectory: true)+        let projectDir = xtoolDir.appendingPathComponent(".xtool-tmp", isDirectory: true)+        try? FileManager.default.removeItem(at: projectDir)+        try FileManager.default.createDirectory(at: projectDir, withIntermediateDirectories: true) -        let projectDir: Path = xtoolDir + ".xtool-tmp"-        try? xtoolDir.delete()-        try projectDir.mkpath()+        let fromProjectToRoot = "../.." -        let fromProjectToRoot = try Path(".").relativePath(from: projectDir)--        guard let deploymentTarget = Version(tolerant: plan.app.deploymentTarget) else {-            throw StringError("Could not parse deployment target '\(plan.app.deploymentTarget)'")+        let emptyText = Data("// leave this file empty".utf8)+        let products = plan.allProducts+        let targetIDs = products.map {+            XCSchema.ObjectID("xtool:\($0.product)")         }+        let sourcePhase = XCSchema.BuildPhase.sources(.init(objectID: nil, name: nil))+        let frameworksPhase = XCSchema.BuildPhase.frameworks(.init(objectID: nil, name: nil)) -        let emptyText = Data("""-        // leave this file empty-        """.utf8)--        let targets = try plan.allProducts.map { product in-            let productDir = projectDir + product.product-            try productDir.mkpath()--            let emptyFile = productDir + "empty.c"-            try emptyFile.write(emptyText)+        var groups: [XCSchema.Reference] = []+        var productFiles: [XCSchema.Reference] = []+        var targets: [XCSchema.Target] = [] -            let infoPath = productDir + "Info.plist"+        for (index, product) in products.enumerated() {+            let productDir = projectDir.appendingPathComponent(product.product, isDirectory: true)+            try FileManager.default.createDirectory(at: productDir, withIntermediateDirectories: true)+            try emptyText.write(to: productDir.appendingPathComponent("empty.c"))              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 iconPath = product.iconPath {+                plist["CFBundleIconFile"] = URL(fileURLWithPath: iconPath).deletingPathExtension().lastPathComponent+            }             let encodedPlist = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)-            try infoPath.write(encodedPlist)+            try encodedPlist.write(to: productDir.appendingPathComponent("Info.plist")) -            var buildSettings: [String: BuildSetting] = [+            var buildSettings: [String: XCSchema.BuildSetting] = [                 "PRODUCT_BUNDLE_IDENTIFIER": .string(product.bundleID),-                "TARGETED_DEVICE_FAMILY": .string(families.map { "\($0)" }.joined(separator: ",")),+                "PRODUCT_NAME": .string(product.targetName),+                "TARGETED_DEVICE_FAMILY": .string(families.map(String.init).joined(separator: ",")),+                "IPHONEOS_DEPLOYMENT_TARGET": .string(product.deploymentTarget),+                "INFOPLIST_FILE": .string("\(product.product)/Info.plist"),+                "LD_RUNPATH_SEARCH_PATHS": .array(["$(inherited)", "@executable_path/Frameworks"]),             ]-             if product.type == .appExtension {-                buildSettings["APPLICATION_EXTENSION_API_ONLY"] = true+                buildSettings["APPLICATION_EXTENSION_API_ONLY"] = .string("YES")+                buildSettings["LD_RUNPATH_SEARCH_PATHS"] = .array([+                    "$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks",+                ])             }-             if let entitlementsPath = product.entitlementsPath {-                buildSettings["CODE_SIGN_ENTITLEMENTS"] = .string((fromProjectToRoot + Path(entitlementsPath)).string)+                let path = (entitlementsPath as NSString).isAbsolutePath+                    ? entitlementsPath+                    : (fromProjectToRoot as NSString).appendingPathComponent(entitlementsPath)+                buildSettings["CODE_SIGN_ENTITLEMENTS"] = .string(path)             } -            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+            let source = XCSchema.FileReference(+                objectID: nil,+                path: "empty.c",+                explicitFileType: nil,+                expectedSignature: nil,+                textEncoding: nil,+                lineEnding: nil,+                includeInIndex: nil,+                buildFiles: [.init(+                    objectID: nil,+                    buildPhase: .named(+                        target: .init(targetName: product.targetName),+                        kind: .sources,+                        name: nil                     ),-                ],-                dependencies: [-                    Dependency(-                        type: .package(products: [product.product]),-                        reference: "RootPackage"+                    properties: buildFileProperties(),+                )],+            )+            let info = XCSchema.FileReference(+                objectID: nil,+                path: "Info.plist",+                explicitFileType: nil,+                expectedSignature: nil,+                textEncoding: nil,+                lineEnding: nil,+                includeInIndex: nil,+                buildFiles: [],+            )+            let resources = try resourceReferences(for: product, at: root)+            groups.append(.group(.init(+                objectID: nil,+                name: product.product,+                path: try .init(base: .group, path: product.product),+                includeInIndex: nil,+                children: [.fileReference(source), .fileReference(info)] + resources,+            )))++            let productFilename = "\(product.targetName).\(product.type == .application ? "app" : "appex")"+            let productFile = XCSchema.FileReference(+                objectID: nil,+                path: try .init(base: .buildProducts, path: productFilename),+                explicitFileType: .init(fileTypeID: product.type == .application ? "wrapper.application" : "wrapper.app-extension"),+                expectedSignature: nil,+                textEncoding: nil,+                lineEnding: nil,+                includeInIndex: false,+                buildFiles: index == 0 ? [] : [.init(+                    objectID: nil,+                    buildPhase: .named(+                        target: .init(targetName: plan.app.targetName),+                        kind: .copy,+                        name: "Embed App Extensions",                     ),-                ] + additionalDependencies,-                info: Plist(-                    path: try infoPath.relativePath(from: projectDir).string,-                    attributes: [:]-                )+                    properties: buildFileProperties(removeHeadersOnCopy: true),+                )],             )-        }+            productFiles.append(.fileReference(productFile)) -        let project = Project(-            name: plan.app.targetName,-            targets: targets,-            packages: [-                "RootPackage": .local(-                    path: fromProjectToRoot.string,-                    group: nil,-                    excludeFromProject: false+            let packageProduct = XCSchema.SwiftPackageProductReference(+                objectID: nil,+                package: nil,+                productName: product.product,+                productType: .other,+            )+            let packageMember = XCSchema.SwiftPackageProductTargetMember(+                packageProduct: packageProduct,+                buildFile: .init(+                    objectID: nil,+                    buildPhase: .named(kind: .frameworks, name: nil),+                    properties: buildFileProperties(),                 ),-            ],-            options: SpecOptions(-                localPackagesGroup: ""             )+            var phases = [sourcePhase, frameworksPhase]+            if !resources.isEmpty {+                phases.append(.copy(.init(+                    objectID: nil,+                    name: "Copy Root Resources",+                    bundleBasePath: .resourcesDir,+                    relativePath: "",+                    scope: .always,+                )))+            }+            if index == 0 && !plan.extensions.isEmpty {+                phases.append(.copy(.init(+                    objectID: nil,+                    name: "Embed App Extensions",+                    bundleBasePath: .plugInsDir,+                    relativePath: "",+                    scope: .always,+                )))+            }+            let dependencies: [XCSchema.TargetDependency] = index == 0+                ? plan.extensions.map {+                    .localTarget(XCSchema.LocalTargetReference(targetName: $0.targetName), [])+                }+                : []+            targets.append(.native(XCSchema.CommonTargetProperties(+                name: product.targetName,+                objectID: targetIDs[index],+                configurationListDebugID: nil,+                dependencies: dependencies,+                buildPhases: phases,+                buildRules: [],+                specializedConfigurations: [],+                buildSettings: buildSettings,+                product: .namePath(.init(components: [.child("Products"), .child(productFilename)])),+                productTypeID: XCSchema.ProductTypeID(+                    abbreviatedRepresentation: product.type == .application+                    ? "application"+                    : "app-extension"+                ),+                testHostTarget: nil,+                legacyProvisioningStyle: nil,+                legacyTeamID: nil,+                lastSwiftUpdateCheck: nil,+                lastSwiftMigration: nil,+                packageProductTargetMembers: [packageMember],+            )))+        }++        let schema = XCSchema.Project(+            objectID: nil,+            rootGroupDebugID: nil,+            configurationListDebugID: nil,+            topLevelReferences: groups + [+                .group(XCSchema.Group(+                    objectID: nil,+                    name: "Products",+                    path: "",+                    includeInIndex: nil,+                    children: productFiles,+                ))+            ],+            packages: [.init(location: .local(.init(path: fromProjectToRoot)), traits: [])],+            configurations: ["Debug", "Release"].map {+                .init(name: .init(name: $0), file: nil, objectID: nil)+            },+            buildSettings: ["SDKROOT": .string("iphoneos")],+            defaultConfigurationName: .init(name: "Debug"),+            targets: targets,+            localizationInfo: .init(development: .init(languageID: "en"), supported: []),+            requiredCapabilities: [],+            buildIndependentTargetsInParallel: true,+            lastUpgradeCheck: nil,+            lastSwiftUpdateCheck: nil,+            lastSwiftMigration: nil,+            organizationName: nil,+            classPrefix: nil,+            productsGroup: .namePath(.init(components: [.child("Products")])),+            importedProducts: [],         ) -        // TODO: Handle plan.resources of type .root-        // TODO: Handle plan.iconPath--        let generator = ProjectGenerator(project: project)-        let xcodeproj = projectDir + "\(plan.app.product).xcodeproj"-        let xcworkspace = xtoolDir + "\(plan.app.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)-            }+        let project = XcodeProject(project: schema)+        let projectURL = projectDir.appending(path: "\(plan.app.product).xcodeproj")+        try project.write(to: projectURL) -            try xcodeProject.write(path: Path(xcodeproj.lastComponent))-        }+        let workspace = XcodeWorkspace(children: [+            .file(XcodeWorkspace.Location(base: .container, path: "..")),+            .file(XcodeWorkspace.Location(base: .group, path: ".xtool-tmp/\(projectURL.lastPathComponent)"))+        ])+        let workspaceURL = xtoolDir.appending(path: "\(plan.app.product).xcworkspace")+        try workspace.write(to: workspaceURL)+        return workspaceURL+    } -        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))+    private func resourceReferences(for product: Plan.Product, at root: URL) throws -> [XCSchema.Reference] {+        var paths = product.resources.compactMap { resource -> String? in+            guard case .root(let source) = resource else { return nil }+            return source+        }+        if let iconPath = product.iconPath {+            paths.append(iconPath)         } -        return xcworkspace.url+        var visited: Set<String> = []+        return try paths.compactMap { path in+            let url = URL(fileURLWithPath: path, relativeTo: root).standardizedFileURL+            guard visited.insert(url.path).inserted else { return nil }+            let isAbsolute = (path as NSString).isAbsolutePath+            let referencePath = isAbsolute ? path : ("../.." as NSString).appendingPathComponent(path)+            var isDirectory: ObjCBool = false+            _ = FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory)++            return .fileReference(.init(+                objectID: nil,+                path: try .init(base: isAbsolute ? .absolute : .project, path: referencePath),+                explicitFileType: isDirectory.boolValue ? .init(fileTypeID: "folder") : nil,+                expectedSignature: nil,+                textEncoding: nil,+                lineEnding: nil,+                includeInIndex: nil,+                buildFiles: [.init(+                    objectID: nil,+                    buildPhase: .named(+                        target: .init(targetName: product.targetName),+                        kind: .copy,+                        name: "Copy Root Resources",+                    ),+                    properties: buildFileProperties(),+                )],+            ))+        }     }-} -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+    private func buildFileProperties(removeHeadersOnCopy: Bool = false) -> XCSchema.BuildFileProperties {+        XCSchema.BuildFileProperties(+            platformFilters: [],+            additionalBuildFlags: nil,+            assetTags: [],+            attributes: XCSchema.BuildFileAttributes(+                headerRole: nil,+                machInterfaceGeneration: nil,+                isWeak: false,+                codeSignOnCopy: false,+                codeGeneration: .default,+                headerPreservation: removeHeadersOnCopy ? .removeOnCopy : .keep,+                decompress: false,+                codeGenerationVisibility: nil,+            ),+        )     } }--#endif
Sources/XToolSupport/DevCommand.swift
diff --git a/Sources/XToolSupport/DevCommand.swift b/Sources/XToolSupport/DevCommand.swiftindex 4e613bc..369bfa8 100644--- a/Sources/XToolSupport/DevCommand.swift+++ b/Sources/XToolSupport/DevCommand.swift@@ -66,11 +66,9 @@ 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,@@ -109,12 +107,12 @@ struct PackOperation { struct DevXcodeCommand: AsyncParsableCommand {     static let configuration = CommandConfiguration(         commandName: "generate-xcode-project",-        abstract: "Generate Xcode project",-        discussion: "This option does nothing on Linux"+        abstract: "Generate Xcode project"     )      func run() async throws {-        try await PackOperation(xcode: true).run()+        let result = try await PackOperation(xcode: true).run()+        print("Wrote to \(result.path)")     } } 
Sources/XToolSupport/SDKCommand.swift
diff --git a/Sources/XToolSupport/SDKCommand.swift b/Sources/XToolSupport/SDKCommand.swiftindex af04b62..39aea7a 100644--- a/Sources/XToolSupport/SDKCommand.swift+++ b/Sources/XToolSupport/SDKCommand.swift@@ -1,6 +1,5 @@ import Foundation import XKit-import Version import ArgumentParser import Dependencies import PackLib
Sources/XcodeProjects/XCSchema+PBXProj.swift
diff --git a/Sources/XcodeProjects/XCSchema+PBXProj.swift b/Sources/XcodeProjects/XCSchema+PBXProj.swiftnew file mode 100644index 0000000..5849060--- /dev/null+++ b/Sources/XcodeProjects/XCSchema+PBXProj.swift@@ -0,0 +1,17 @@+import Foundation+private import XcodeProj++extension XCSchema.Project {+    public func pbxprojRepresentation(name: String) throws -> Data {+        let xcprojData = try self.jsonRepresentation()+        let pbxproj = try PBXProj(xcprojData: xcprojData, projectName: name)+        // dataRepresentation should never return nil+        return try pbxproj.dataRepresentation() ?? Data()+    }++    public init(pbxprojRepresentation data: Data) throws {+        let pbxproj = try PBXProj(data: data)+        let xcprojData = try pbxproj.xcprojData()+        try self.init(jsonRepresentation: xcprojData)+    }+}
Sources/XcodeProjects/XcodeProject.swift
diff --git a/Sources/XcodeProjects/XcodeProject.swift b/Sources/XcodeProjects/XcodeProject.swiftnew file mode 100644index 0000000..99cb1df--- /dev/null+++ b/Sources/XcodeProjects/XcodeProject.swift@@ -0,0 +1,78 @@+import Foundation+@_exported import XcodeProjectFormat++// This library is a lightweight layer on top of the XcodeProjectFormat+// interface, providing other facilities for working with the Xcode+// project formats.+//+// We currently use XcodeProj under the hood for some functionality, but this+// should be considered an implementation detail.++public struct XcodeProject: Equatable, Sendable {+    public enum Format: Sendable {+        case pbxproj+        case xcproj+    }++    public var project: XCSchema.Project+    public var format: Format++    public init(+        project: XCSchema.Project,+        format: Format = .pbxproj,+    ) {+        self.project = project+        self.format = format+    }++    /// Reads the project from the given `.xcodeproj` path.+    public init(url: URL) throws {+        guard url.pathExtension == "xcodeproj" else {+            throw Errors.notAnXcodeproj(url.path)+        }+        let xcprojURL = url.appending(path: "project.xcproj")+        lazy var pbxprojURL = url.appending(path: "project.pbxproj")+        if FileManager.default.fileExists(atPath: xcprojURL.path) {+            let data = try Data(contentsOf: xcprojURL)+            self.project = try XCSchema.Project(jsonRepresentation: data)+            self.format = .xcproj+        } else if FileManager.default.fileExists(atPath: pbxprojURL.path) {+            let data = try Data(contentsOf: pbxprojURL)+            self.project = try XCSchema.Project(pbxprojRepresentation: data)+            self.format = .pbxproj+        } else {+            throw Errors.missingProjectFile(url.path)+        }+    }++    /// Sets the format in which the project should be serialized.+    public func withFormat(_ format: Format) -> XcodeProject {+        var copy = self+        copy.format = format+        return copy+    }++    /// Writes the project to the given `.xcodeproj` path.+    public func write(to url: URL) throws {+        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)++        switch format {+        case .pbxproj:+            try project+                .pbxprojRepresentation(name: url.deletingPathExtension().lastPathComponent)+                .write(to: url.appendingPathComponent("project.pbxproj"))+        case .xcproj:+            try project+                .jsonRepresentation()+                .write(to: url.appendingPathComponent("project.xcproj"))+        }++        try XcodeWorkspace(children: [.file(.current)])+            .write(to: url.appendingPathComponent("project.xcworkspace"))+    }++    public enum Errors: Error {+        case notAnXcodeproj(String)+        case missingProjectFile(String)+    }+}
Sources/XcodeProjects/XcodeWorkspace+XML.swift
diff --git a/Sources/XcodeProjects/XcodeWorkspace+XML.swift b/Sources/XcodeProjects/XcodeWorkspace+XML.swiftnew file mode 100644index 0000000..b390a95--- /dev/null+++ b/Sources/XcodeProjects/XcodeWorkspace+XML.swift@@ -0,0 +1,84 @@+import Foundation+private import XcodeProj++extension XcodeWorkspace {+    public init(url: URL) throws {+        let workspace = try XCWorkspace(pathString: url.path)+        self.init(workspace.data)+    }++    public func dataRepresentation() throws -> Data {+        try xcWorkspaceData.dataRepresentation() ?? Data()+    }++    public func write(to url: URL) throws {+        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+        try self.dataRepresentation()+            .write(to: url.appendingPathComponent("contents.xcworkspacedata"))+    }+}++// MARK: - Conversion++extension XcodeWorkspace {+    fileprivate init(_ xcWorkspaceData: XCWorkspaceData) {+        self.init(children: xcWorkspaceData.children.map { .init(from: $0) })+    }++    fileprivate var xcWorkspaceData: XCWorkspaceData {+        XCWorkspaceData(children: children.map(\.xcWorkspaceDataElement))+    }+}++extension XcodeWorkspace.Element {+    fileprivate init(from xcWorkspaceDataElement: XCWorkspaceDataElement) {+        switch xcWorkspaceDataElement {+        case .file(let file):+            self = .file(.init(file.location))+        case .group(let group):+            self = .group(.init(group))+        case .fileSystemSynchronizedGroup(let group):+            self = .fileSystemSynchronizedGroup(.init(group))+        }+    }++    fileprivate var xcWorkspaceDataElement: XCWorkspaceDataElement {+        switch self {+        case .file(let location):+            .file(.init(location: location.xcWorkspaceLocation))+        case .group(let group):+            .group(group.xcWorkspaceDataElement)+        case .fileSystemSynchronizedGroup(let group):+            .fileSystemSynchronizedGroup(group.xcWorkspaceDataElement)+        }+    }+}++extension XcodeWorkspace.Location {+    fileprivate init(_ xcWorkspaceDataElementLocation: XCWorkspaceDataElementLocationType) {+        self.base = .init(rawValue: xcWorkspaceDataElementLocation.schema)+        self.path = xcWorkspaceDataElementLocation.path+    }++    fileprivate var xcWorkspaceLocation: XCWorkspaceDataElementLocationType {+        .other(base.rawValue, path)+    }+}++extension XcodeWorkspace.Group {+    fileprivate init(_ xcWorkspaceDataGroup: XCWorkspaceDataGroup) {+        self.init(+            location: .init(xcWorkspaceDataGroup.location),+            name: xcWorkspaceDataGroup.name,+            children: xcWorkspaceDataGroup.children.map { .init(from: $0) }+        )+    }++    fileprivate var xcWorkspaceDataElement: XCWorkspaceDataGroup {+        .init(+            location: self.location.xcWorkspaceLocation,+            name: name,+            children: children.map(\.xcWorkspaceDataElement)+        )+    }+}
Sources/XcodeProjects/XcodeWorkspace.swift
diff --git a/Sources/XcodeProjects/XcodeWorkspace.swift b/Sources/XcodeProjects/XcodeWorkspace.swiftnew file mode 100644index 0000000..13b6258--- /dev/null+++ b/Sources/XcodeProjects/XcodeWorkspace.swift@@ -0,0 +1,103 @@+import Foundation++public struct XcodeWorkspace: Hashable, Sendable {+    public enum Element: Hashable, Sendable {+        case file(Location)+        case group(Group)+        case fileSystemSynchronizedGroup(Group)++        public var location: Location {+            get {+                switch self {+                case let .file(location):+                    location+                case let .group(group):+                    group.location+                case let .fileSystemSynchronizedGroup(group):+                    group.location+                }+            }+            set {+                switch self {+                case .file:+                    self = .file(newValue)+                case .group(var group):+                    group.location = newValue+                    self = .group(group)+                case .fileSystemSynchronizedGroup(var group):+                    group.location = newValue+                    self = .fileSystemSynchronizedGroup(group)+                }+            }+        }+    }++    public struct Group: Hashable, Sendable {+        public var location: Location+        public var name: String?+        public var children: [Element]++        public init(location: Location, name: String?, children: [Element]) {+            self.location = location+            self.name = name+            self.children = children+        }+    }++    public struct Location: Hashable, Sendable {+        public struct Base: Hashable, Sendable, RawRepresentable {+            public var rawValue: String++            public init(rawValue: String) {+                self.rawValue = rawValue+            }+        }++        public var base: Base+        public var path: String++        public init(base: Base, path: String) {+            self.base = base+            self.path = path+        }+    }++    public var children: [Element]++    public init(children: [Element]) {+        self.children = children+    }+}++extension XcodeWorkspace.Location.Base {+    /// Absolute path+    public static let absolute = Self(rawValue: "absolute")+    /// Relative to container+    public static let container = Self(rawValue: "container")+    /// Relative to Developer Directory+    public static let developer = Self(rawValue: "developer")+    /// Relative to group+    public static let group = Self(rawValue: "group")+    /// Single project workspace in xcodeproj directory+    public static let current = Self(rawValue: "self")+}++extension XcodeWorkspace.Location {+    public static var current: Self {+        Self(base: .current, path: "")+    }+}++extension XcodeWorkspace.Location: LosslessStringConvertible, CustomStringConvertible {+    public init?(_ string: String) {+        guard let colon = string.firstIndex(of: ":") else {+            return nil+        }+        self.base = Base(rawValue: String(string[..<colon]))+        self.path = String(string[colon...].dropFirst())+    }++    public var description: String {+        "\(base.rawValue):\(path)"+    }+}