### Read an Xcode Project Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/getting-started.md Loads an existing Xcode project file into memory using the XcodeProj class. It takes the path to the .xcodeproj file as input and parses its structure into Swift objects for manipulation. ```swift import Foundation import PathKit import XcodeProj let path = Path("/path/to/my/Project.xcodeproj") // Your project path do { let xcodeproj = try XcodeProj(path: path) } catch { print(error) } ``` -------------------------------- ### Output Project Targets Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/getting-started.md Retrieves and prints the names of all native targets within an Xcode project. It accesses the PBXProj object from the XcodeProj instance and iterates through its native targets. ```swift let pbxproj = xcodeproj.pbxproj // Returns a PBXProj pbxproj.nativeTargets.forEach { target in print(target.name) } ``` -------------------------------- ### Use xcodeproj with swift-sh Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/getting-started.md Enables using xcodeproj as a third-party dependency in standalone Swift scripts using swift-sh. It automatically fetches the dependency when the script is executed. ```swift #!/usr/bin/swift sh import Foundation import XcodeProj // @tuist import PathKit ``` -------------------------------- ### Accessing Public Helpers in xcodeproj 6 Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/migration-guides.md Illustrates how to access public helper methods on the PBXProj class in xcodeproj version 6. These methods replace the functionality previously available through the internal PBXObjects class for adding, removing, and getting objects. ```swift // Example usage of public helpers on PBXProj class // let proj = PBXProj() // proj.add(object: myObject) // proj.get(object: objectId) // proj.remove(object: objectId) ``` -------------------------------- ### Write Xcode Project Changes to Disk Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/getting-started.md Persists any modifications made to an Xcode project back to its file on disk. The write function is available on both XcodeProj and PBXProj objects and will throw an error if the writing process fails. ```swift try xcodeproj.write(path: path) ``` -------------------------------- ### Add xcodeproj Dependency with Swift Package Manager Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/getting-started.md Integrates the xcodeproj library into your Swift Package Manager project by adding its URL and version to your Package.swift file. This allows you to use xcodeproj functionalities in your package. ```swift .package(url: "https://github.com/tuist/xcodeproj.git", .upToNextMajor(from: "6.6.0")), ``` -------------------------------- ### Adding Build Configuration in xcodeproj 6 Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/migration-guides.md Demonstrates how to add a new build configuration to an XCConfigurationList in xcodeproj version 6. This method simplifies adding configurations by directly appending to the `buildConfigurations` attribute, abstracting away object reference management. ```swift list.buildConfigurations.append(config) ``` -------------------------------- ### Create a New Root Group in Xcode Project Source: https://github.com/tuist/xcodeproj/blob/main/Documentation/getting-started.md Adds a new group to the root of an Xcode project. It first retrieves the project's main group and then uses the addGroup method to create the new group. Note that the corresponding folder must exist on disk. ```swift let project = pbxproj.projects.first! // Returns a PBXProject let mainGroup = project.mainGroup mainGroup.addGroup(named: "MyGroup") ``` -------------------------------- ### Swift Package Manager Installation for XcodeProj Source: https://github.com/tuist/xcodeproj/blob/main/README.md This code snippet demonstrates how to add the XcodeProj library as a dependency to your Swift project using Swift Package Manager. It specifies the repository URL and the version constraint for the dependency. ```swift let package = Package( name: "myproject", dependencies: [ .package(url: "https://github.com/tuist/XcodeProj.git", .upToNextMajor(from: "8.12.0")), ], targets: [ .target( name: "myproject", dependencies: ["XcodeProj"]) ] ) ``` -------------------------------- ### Scripting Xcode Project Version Updates with XcodeProj and swift-sh Source: https://github.com/tuist/xcodeproj/blob/main/README.md This script uses XcodeProj and swift-sh to update the 'CURRENT_PROJECT_VERSION' build setting in an Xcode project file. It takes the project path and the new version as command-line arguments, modifies the project, and saves the changes. Ensure swift-sh is installed and the XcodeProj dependency is correctly referenced. ```swift #!/usr/bin/swift sh import Foundation import XcodeProj // @tuist ~> 8.8.0 import PathKit guard CommandLine.arguments.count == 3 else { let arg0 = Path(CommandLine.arguments[0]).lastComponent fputs("usage: \(arg0) \n", stderr) exit(1) } let projectPath = Path(CommandLine.arguments[1]) let newVersion = CommandLine.arguments[2] let xcodeproj = try XcodeProj(path: projectPath) let key = "CURRENT_PROJECT_VERSION" for conf in xcodeproj.pbxproj.buildConfigurations where conf.buildSettings[key] != nil { conf.buildSettings[key] = newVersion } try xcodeproj.write(path: projectPath) ``` -------------------------------- ### Read and Write Xcode Projects with XcodeProj Source: https://context7.com/tuist/xcodeproj/llms.txt Demonstrates how to load an existing Xcode project, access its components like pbxproj, workspace, and shared data, make modifications, and save changes back to disk. Requires the PathKit library for path manipulation. ```swift import XcodeProj import PathKit // Read an existing Xcode project let projectPath = Path("/path/to/MyApp.xcodeproj") do { let xcodeproj = try XcodeProj(path: projectPath) // Access the pbxproj (main project definition) let pbxproj = xcodeproj.pbxproj // Access the internal workspace let workspace = xcodeproj.workspace // Access shared data (schemes, breakpoints) if let sharedData = xcodeproj.sharedData { print("Shared schemes: \(sharedData.schemes.map { $0.name })") } // Make modifications... // Write changes back to disk try xcodeproj.write(path: projectPath) } catch { print("Error: \(error)") } ``` -------------------------------- ### Bash Script for Executing Xcode Project Version Update Source: https://github.com/tuist/xcodeproj/blob/main/README.md This bash script demonstrates how to execute the Swift script for updating the Xcode project version. It shows the command-line usage for setting the project version and committing the changes to Git, including tagging the new version. ```bash $ scripts/set-project-version ./App.xcodeproj 1.2.3 $ git add App.xcodeproj $ git commit -m "Bump version" $ git tag 1.2.3 ``` -------------------------------- ### Manage Xcode Schemes Programmatically Source: https://context7.com/tuist/xcodeproj/llms.txt Shows how to read existing Xcode schemes and create new ones programmatically using the `XCScheme` class from the XcodeProj library. It covers accessing build, test, and launch actions, and writing schemes to disk. Requires the XcodeProj and PathKit libraries. ```swift import XcodeProj import PathKit let projectPath = Path("/path/to/MyApp.xcodeproj") let xcodeproj = try XcodeProj(path: projectPath) // Read existing schemes from shared data if let sharedData = xcodeproj.sharedData { for scheme in sharedData.schemes { print("Scheme: \(scheme.name)") // Access build action if let buildAction = scheme.buildAction { print(" Build entries:") for entry in buildAction.buildActionEntries { print(" - \(entry.buildableReference.blueprintName)") } } // Access test action if let testAction = scheme.testAction { print(" Test configuration: \(testAction.buildConfiguration)") } // Access launch action if let launchAction = scheme.launchAction { print(" Launch configuration: \(launchAction.buildConfiguration)") } } } // Create a new scheme let buildableReference = XCScheme.BuildableReference( referencedContainer: "container:MyApp.xcodeproj", blueprint: xcodeproj.pbxproj.nativeTargets.first!, buildableName: "MyApp.app", blueprintName: "MyApp" ) let buildAction = XCScheme.BuildAction( buildActionEntries: [ XCScheme.BuildAction.Entry( buildableReference: buildableReference, buildFor: [.running, .testing, .profiling, .archiving, .analyzing] ) ] ) let newScheme = XCScheme( name: "MyApp-Debug", lastUpgradeVersion: "1500", version: "1.3", buildAction: buildAction, testAction: XCScheme.TestAction( buildConfiguration: "Debug", macroExpansion: buildableReference ), launchAction: XCScheme.LaunchAction( runnable: XCScheme.BuildableProductRunnable(buildableReference: buildableReference), buildConfiguration: "Debug" ) ) // Write scheme to disk let schemesPath = projectPath + "xcshareddata/xcschemes" try schemesPath.mkpath() try newScheme.write(path: schemesPath + "\(newScheme.name).xcscheme", override: true) ``` -------------------------------- ### Work with Xcode Workspaces Source: https://context7.com/tuist/xcodeproj/llms.txt Illustrates how to read and create Xcode Workspaces programmatically using the `XCWorkspace` class from the XcodeProj library. It covers accessing workspace contents and defining new workspace structures. Requires the XcodeProj and PathKit libraries. ```swift import XcodeProj import PathKit // Read an existing workspace let workspacePath = Path("/path/to/MyApp.xcworkspace") let workspace = try XCWorkspace(path: workspacePath) // Access workspace data (file references) print("Workspace contents:") for child in workspace.data.children { switch child { case .file(let fileRef): print(" File: \(fileRef.location)") case .group(let group): print(" Group: \(group.name ?? "unnamed")") for groupChild in group.children { if case .file(let ref) = groupChild { print(" - \(ref.location)") } } } } // Create a new workspace let newWorkspaceData = XCWorkspaceData(children: [ .file(.init(location: .group("MyApp.xcodeproj"))), .file(.init(location: .group("MyFramework.xcodeproj"))), ]) let newWorkspace = XCWorkspace(data: newWorkspaceData) // Write workspace try newWorkspace.write(path: Path("/path/to/NewWorkspace.xcworkspace")) ``` -------------------------------- ### Access Project Targets with XcodeProj Source: https://context7.com/tuist/xcodeproj/llms.txt Shows how to access and iterate over different types of targets (native, aggregate) within an Xcode project using the PBXProj class. It also demonstrates how to find targets by name and inspect their properties like build phases and dependencies. Requires the PathKit library. ```swift import XcodeProj import PathKit let xcodeproj = try XcodeProj(path: Path("/path/to/MyApp.xcodeproj")) let pbxproj = xcodeproj.pbxproj // Access all native targets (apps, frameworks, extensions) for target in pbxproj.nativeTargets { print("Target: \(target.name)") print(" Product Name: \(target.productName ?? "N/A")") print(" Product Type: \(target.productType?.rawValue ?? "N/A")") // Get build phases for phase in target.buildPhases { print(" Build Phase: \(phase.buildPhase)") } // Get dependencies for dependency in target.dependencies { print(" Depends on: \(dependency.name ?? "unknown")") } } // Find targets by name let appTargets = pbxproj.targets(named: "MyApp") // Access aggregate targets (for running scripts) for target in pbxproj.aggregateTargets { print("Aggregate Target: \(target.name)") } ``` -------------------------------- ### Parse and Modify xcconfig Files with Swift Source: https://context7.com/tuist/xcodeproj/llms.txt Demonstrates how to read, access build settings and includes, flatten settings, create, and write `.xcconfig` files using the XcodeProj library in Swift. It requires the XcodeProj and PathKit libraries. ```swift import XcodeProj import PathKit // Read an xcconfig file let configPath = Path("/path/to/Config.xcconfig") let config = try XCConfig(path: configPath) // Access build settings print("Build settings:") for (key, value) in config.buildSettings { print(" \(key) = \(value)") } // Access includes (referenced xcconfig files) print("Includes:") for include in config.includes { print(" #include \"\(include.include)\" ") } // Get flattened build settings (resolves all includes) let flatSettings = config.flattenedBuildSettings() print("Flattened settings count: \(flatSettings.count)") // Create a new xcconfig let newConfig = XCConfig( includes: [], buildSettings: [ "PRODUCT_NAME": .string("$(TARGET_NAME)"), "SWIFT_VERSION": .string("5.0"), "IPHONEOS_DEPLOYMENT_TARGET": .string("15.0"), "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"]), ] ) // Write xcconfig try newConfig.write(path: Path("/path/to/NewConfig.xcconfig"), override: true) ``` -------------------------------- ### Efficiently Add Multiple Files to Xcode Projects with Swift Source: https://context7.com/tuist/xcodeproj/llms.txt Shows how to use the batch update functionality in XcodeProj for efficiently adding multiple files to a target's sources build phase in Swift. This method optimizes operations for large projects by minimizing repeated project lookups. It requires XcodeProj and PathKit. ```swift import XcodeProj import PathKit let projectPath = Path("/path/to/MyApp.xcodeproj") let xcodeproj = try XcodeProj(path: projectPath) let pbxproj = xcodeproj.pbxproj let sourceRoot = projectPath.parent() // Use batch updater for adding many files efficiently try pbxproj.batchUpdate(sourceRoot: sourceRoot) { updater in // Add multiple files in a single batch operation // This is more efficient than calling addFile repeatedly // Get the target's sources build phase guard let target = pbxproj.nativeTargets.first(where: { $0.name == "MyApp" }), let sourcesPhase = try target.sourcesBuildPhase() else { return } // Add files to the batch let files = [ "NewFile1.swift", "NewFile2.swift", "NewFile3.swift" ] for fileName in files { let filePath = sourceRoot + "MyApp/\(fileName)" // Batch operations are handled internally print("Would add: \(filePath)") } } try xcodeproj.write(path: projectPath) ``` -------------------------------- ### Add Target Dependencies in Xcode Projects with Swift Source: https://context7.com/tuist/xcodeproj/llms.txt Illustrates how to add dependencies between native targets in an Xcode project using Swift. This involves loading the project, finding targets, adding a dependency, listing existing dependencies, and accessing the frameworks build phase. It requires XcodeProj and PathKit. ```swift import XcodeProj import PathKit let xcodeproj = try XcodeProj(path: Path("/path/to/MyApp.xcodeproj")) let pbxproj = xcodeproj.pbxproj // Find the app target and framework target guard let appTarget = pbxproj.nativeTargets.first(where: { $0.name == "MyApp" }), let frameworkTarget = pbxproj.nativeTargets.first(where: { $0.name == "MyFramework" }) else { fatalError("Targets not found") } // Add dependency: MyApp depends on MyFramework if let dependency = try appTarget.addDependency(target: frameworkTarget) { print("Added dependency: \(appTarget.name) -> \(dependency.name ?? frameworkTarget.name)") } // List all dependencies for a target print("Dependencies for \(appTarget.name):") for dep in appTarget.dependencies { print(" - \(dep.name ?? "unknown")") } // Access frameworks build phase to link the framework if let frameworksPhase = try appTarget.frameworksBuildPhase() { print("Frameworks build phase files: \(frameworksPhase.files?.count ?? 0)") } try xcodeproj.write(path: Path("/path/to/MyApp.xcodeproj")) ``` -------------------------------- ### Manage File References and Groups in Xcode Projects (Swift) Source: https://context7.com/tuist/xcodeproj/llms.txt Demonstrates how to use XcodeProj to manage file references and groups within an Xcode project. This includes finding existing groups, creating new ones, adding files to groups, and creating variant groups for localization. It requires the XcodeProj and PathKit libraries. ```swift import XcodeProj import PathKit let projectPath = Path("/path/to/MyApp.xcodeproj") let xcodeproj = try XcodeProj(path: projectPath) let pbxproj = xcodeproj.pbxproj // Get the project's main group (root of the file tree) guard let project = pbxproj.rootProject(), let mainGroup = project.mainGroup else { fatalError("Could not get main group") } // Find a group by name if let sourcesGroup = mainGroup.group(named: "Sources") { print("Found Sources group") // List children for child in sourcesGroup.children { print(" - (child.path ?? child.name ?? "unknown")") } } // Create a new group let sourceRoot = projectPath.parent() let newGroups = try mainGroup.addGroup(named: "NewFeature") let newGroup = newGroups.first! // Add a file to the group let filePath = sourceRoot + "NewFeature/NewFile.swift" let fileReference = try newGroup.addFile( at: filePath, sourceTree: .group, sourceRoot: sourceRoot ) print("Added file: (fileReference.path ?? "unknown")") // Create a variant group (for localized files) let variantGroups = try mainGroup.addVariantGroup(named: "Localizable.strings") try xcodeproj.write(path: projectPath) ``` -------------------------------- ### Add Files to Build Phases in Xcode Projects (Swift) Source: https://context7.com/tuist/xcodeproj/llms.txt Illustrates how to add file references to specific build phases (sources, resources) for an Xcode target using XcodeProj. This is essential for ensuring files are compiled or included in the build. It requires the XcodeProj and PathKit libraries. ```swift import XcodeProj import PathKit let projectPath = Path("/path/to/MyApp.xcodeproj") let xcodeproj = try XcodeProj(path: projectPath) let pbxproj = xcodeproj.pbxproj guard let target = pbxproj.nativeTargets.first(where: { $0.name == "MyApp" }), let project = pbxproj.rootProject(), let mainGroup = project.mainGroup else { fatalError("Setup failed") } let sourceRoot = projectPath.parent() // Add a Swift file to Sources group and build phase let sourcesGroup = mainGroup.group(named: "MyApp") ?? mainGroup let swiftFile = try sourcesGroup.addFile( at: sourceRoot + "MyApp/NewClass.swift", sourceTree: .group, sourceRoot: sourceRoot ) // Get the sources build phase and add the file if let sourcesBuildPhase = try target.sourcesBuildPhase() { let buildFile = PBXBuildFile(file: swiftFile) pbxproj.add(object: buildFile) sourcesBuildPhase.files?.append(buildFile) } // Add a resource file (image, asset, etc.) let resourceFile = try sourcesGroup.addFile( at: sourceRoot + "MyApp/Resources/config.json", sourceTree: .group, sourceRoot: sourceRoot ) if let resourcesBuildPhase = try target.resourcesBuildPhase() { let buildFile = PBXBuildFile(file: resourceFile) pbxproj.add(object: buildFile) resourcesBuildPhase.files?.append(buildFile) } try xcodeproj.write(path: projectPath) ``` -------------------------------- ### Modify Build Settings in Xcode Projects with XcodeProj Source: https://context7.com/tuist/xcodeproj/llms.txt Illustrates how to read and modify build settings for both project-level and target-level configurations within an Xcode project. It covers accessing build configurations, reading existing settings, setting new values, and appending to existing settings like OTHER_SWIFT_FLAGS. Requires the PathKit library. ```swift import XcodeProj import PathKit let xcodeproj = try XcodeProj(path: Path("/path/to/MyApp.xcodeproj")) let pbxproj = xcodeproj.pbxproj // Modify build settings for all configurations for config in pbxproj.buildConfigurations { print("Configuration: \(config.name)") // Read existing settings if let version = config.buildSettings["CURRENT_PROJECT_VERSION"] { print(" Current version: \(version)") } // Set build settings config.buildSettings["CURRENT_PROJECT_VERSION"] = "2.0.0" config.buildSettings["MARKETING_VERSION"] = "2.0" config.buildSettings["SWIFT_VERSION"] = "5.0" // Append to existing settings (preserves $(inherited)) config.append(setting: "OTHER_SWIFT_FLAGS", value: "-DDEBUG") } // Modify settings for a specific target if let appTarget = pbxproj.nativeTargets.first(where: { $0.name == "MyApp" }), let configList = appTarget.buildConfigurationList { for config in configList.buildConfigurations { config.buildSettings["INFOPLIST_FILE"] = "MyApp/Info.plist" config.buildSettings["CODE_SIGN_STYLE"] = "Automatic" } } try xcodeproj.write(path: Path("/path/to/MyApp.xcodeproj")) ``` -------------------------------- ### Add Shell Script Build Phases to Xcode Projects (Swift) Source: https://context7.com/tuist/xcodeproj/llms.txt Explains how to add custom shell script build phases to an Xcode target using XcodeProj. This allows for executing custom scripts during the build process, such as for code generation or linting. It requires the XcodeProj and PathKit libraries. ```swift import XcodeProj import PathKit let xcodeproj = try XcodeProj(path: Path("/path/to/MyApp.xcodeproj")) let pbxproj = xcodeproj.pbxproj guard let target = pbxproj.nativeTargets.first(where: { $0.name == "MyApp" }) else { fatalError("Target not found") } // Create a new shell script build phase let scriptPhase = PBXShellScriptBuildPhase( name: "SwiftLint", inputPaths: [], outputPaths: [], shellPath: "/bin/sh", shellScript: """ if which swiftlint > /dev/null; then swiftlint else echo \"warning: SwiftLint not installed\" fi """, showEnvVarsInLog: false, alwaysOutOfDate: true // Run on every build ) // Add to project and target pbxproj.add(object: scriptPhase) target.buildPhases.append(scriptPhase) // Get existing run script phases let existingScripts = target.runScriptBuildPhases() for script in existingScripts { print("Script: (script.name ?? \"Unnamed\")") print(" Shell: (script.shellPath ?? \"/bin/sh\")") } try xcodeproj.write(path: Path("/path/to/MyApp.xcodeproj")) ``` -------------------------------- ### Add Swift Package Dependencies to Xcode Project Source: https://context7.com/tuist/xcodeproj/llms.txt Demonstrates how to add both remote and local Swift Package Manager dependencies to an Xcode project using the XcodeProj library. It covers creating package references, linking them to targets, and listing existing packages. Requires the XcodeProj and PathKit libraries. ```swift import XcodeProj import PathKit let projectPath = Path("/path/to/MyApp.xcodeproj") let xcodeproj = try XcodeProj(path: projectPath) let pbxproj = xcodeproj.pbxproj guard let project = pbxproj.rootProject() else { fatalError("Could not get project") } // Add a remote Swift package (from GitHub) let packageRef = try project.addSwiftPackage( repositoryURL: "https://github.com/Alamofire/Alamofire.git", productName: "Alamofire", versionRequirement: .upToNextMajorVersion("5.0.0"), targetName: "MyApp" ) print("Added package: \(packageRef.repositoryURL ?? "")") // Add a local Swift package let localPackage = try project.addLocalSwiftPackage( path: Path("../MyLocalPackage"), // Must be relative path productName: "MyLocalPackage", targetName: "MyApp", addFileReference: true ) print("Added local package: \(localPackage.productName)") // List existing packages print("Remote packages:") for package in project.remotePackages { print(" - \(package.repositoryURL ?? "unknown")") } print("Local packages:") for package in project.localPackages { print(" - \(package.relativePath ?? "unknown")") } try xcodeproj.write(path: projectPath) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.