返回 Skills 目录
firebase/agent-skills已通过检查

SKILL DETAIL

xcode-project-setup

firebase/agent-skills/xcode-project-setup

此技能用于安全地修改 Xcode 项目(.pbxproj)以添加 Swift 包并链接文件。当 iOS 项目需要安装依赖(如 Firebase、Alamofire)时,应使用此技能。 该技能提供了一种原生 Swift 脚本(xcode_spm_setup),可自动处理添加包依赖和链接产品模块的步骤。它遵循现代 Xcode 文件夹同步规则,避免手动修改 .pbxproj 文件。使用前需验证 Swift 工具链可用,并确保项目已存在。对于 Firebase 等依赖,脚本会自动注入 -ObjC 链接器标志以防止运行时崩溃。

安装量 · 674查看来源

Installation

npx skills add https://github.com/firebase/agent-skills --skill xcode-project-setup

技能文件

SKILL.md

最近同步 · 2026年8月29日

scripts/xcode_spm_setup/.gitignore
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/configuration/project.xcworkspace/
.swiftpm/xcode/
.swiftpm/xcode/xcuserdata/
scripts/xcode_spm_setup/Package.resolved
{
  "pins" : [
    {
      "identity" : "aexml",
      "kind" : "remoteSourceControl",
      "location" : "https://github.com/tadija/AEXML.git",
      "state" : {
        "revision" : "db806756c989760b35108146381535aec231092b",
        "version" : "4.7.0"
      }
    },
    {
      "identity" : "pathkit",
      "kind" : "remoteSourceControl",
      "location" : "https://github.com/kylef/PathKit.git",
      "state" : {
        "revision" : "3bfd2737b700b9a36565a8c94f4ad2b050a5e574",
        "version" : "1.0.1"
      }
    },
    {
      "identity" : "spectre",
      "kind" : "remoteSourceControl",
      "location" : "https://github.com/kylef/Spectre.git",
      "state" : {
        "revision" : "26cc5e9ae0947092c7139ef7ba612e34646086c7",
        "version" : "0.10.1"
      }
    },
    {
      "identity" : "xcodeproj",
      "kind" : "remoteSourceControl",
      "location" : "https://github.com/tuist/XcodeProj.git",
      "state" : {
        "revision" : "b1caa062d4aaab3e3d2bed5fe0ac5f8ce9bf84f4",
        "version" : "8.27.7"
      }
    }
  ],
  "version" : 2
}
scripts/xcode_spm_setup/Package.swift
// swift-tools-version: 5.9
import PackageDescription

let package = Package(
    name: "xcode_spm_setup",
    platforms: [.macOS(.v13)],
    dependencies: [
        .package(url: "https://github.com/tuist/XcodeProj.git", .upToNextMajor(from: "8.27.7")),
    ],
    targets: [
        .executableTarget(
            name: "xcode_spm_setup",
            dependencies: ["XcodeProj"],
            path: "Sources"
        )
    ]
)
scripts/xcode_spm_setup/Sources/main.swift
import Foundation
import XcodeProj
import PathKit

func isUserScriptSandboxingEnabled(project: PBXProj) -> Bool {
    guard let target = project.projects.first else {
        print("Error: No project targets found")
        return false
    }

    for configuration in target.buildConfigurationList?.buildConfigurations ?? [] {
        if let userSandbox = configuration.buildSettings["ENABLE_USER_SCRIPT_SANDBOXING"] as? String {
            return userSandbox.uppercased() == "YES"
        }
    }

    // If the value is absent, assume it is the default "YES"
    return true
}

func hasCrashlyticsRunScriptBuildPhase(project: PBXProj) -> Bool {
    guard let nativeTargets = project.nativeTargets.first else {
        return false
    }

    for phase in nativeTargets.buildPhases {
        if phase.buildPhase == BuildPhase.runScript, let scriptPhase = phase as? PBXShellScriptBuildPhase {
            if let script = scriptPhase.shellScript, script.contains("Crashlytics") {
                return true
            }
        }
    }

    return false
}

func addCrashlyticsRunScriptBuildPhase(project: PBXProj) {
    guard let nativeTarget = project.nativeTargets.first else {
        print("Error: couldn't add the Crashlytics Run Script Build phase automatically, please add it manually")
        return
    }

    var inputPaths = [
        "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}",
        "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${PRODUCT_NAME}",
        "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Info.plist",
        "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/GoogleService-Info.plist",
        "$(TARGET_BUILD_DIR)/$(EXECUTABLE_PATH)"
    ]

    if isUserScriptSandboxingEnabled(project: project) {
        inputPaths.append("${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${PRODUCT_NAME}.debug.dylib")
    }

    let phase = PBXShellScriptBuildPhase(
        files: [],
        inputPaths: inputPaths,
        outputPaths: [],
        shellPath: "/bin/sh",
        shellScript: "\"${BUILD_DIR%/Build/*}/SourcePackages/checkouts/firebase-ios-sdk/Crashlytics/run\"\n",
        runOnlyForDeploymentPostprocessing: false
    )

    project.add(object: phase)
    nativeTarget.buildPhases.append(phase)
}

func setDwarfWithDsymDebugInformationFormat(project: PBXProj) {
    guard let target = project.projects.first else {
        print("Error: No project targets found")
        return
    }

    for configuration in target.buildConfigurationList?.buildConfigurations ?? [] {
        // Set debug format for all configs
        configuration.buildSettings["DEBUG_INFORMATION_FORMAT"] = "dwarf-with-dsym"
    }
}

func main() {
    let args = CommandLine.arguments
    guard args.count >= 5 else {
        print("Usage: swift run --package-path <path> xcode_spm_setup <Path/To/Project.xcodeproj> <RepoURL> <VersionRequirement> [--plist <Path/To/Plist>] <Product1> [Product2 ...]")
        exit(1)
    }

    var arguments = args
    _ = arguments.removeFirst() // executable name
    let projectPath = Path(arguments.removeFirst())
    let repoURL = arguments.removeFirst()
    let versionRequirementString = arguments.removeFirst()
    
    var plistPath: Path? = nil
    if let plistIndex = arguments.firstIndex(of: "--plist"), plistIndex + 1 < arguments.count {
        plistPath = Path(arguments[plistIndex + 1])
        arguments.remove(at: plistIndex + 1)
        arguments.remove(at: plistIndex)
    }

    let products = arguments

    guard !products.isEmpty else {
        print("Error: No products specified to link.")
        exit(1)
    }

    do {
        let xcodeproj = try XcodeProj(path: projectPath)
        let pbxproj = xcodeproj.pbxproj
        
        guard let rootObject = try pbxproj.rootProject() else {
            print("Error: Could not find root project")
            exit(1)
        }
        
        guard let target = pbxproj.nativeTargets.first else {
            print("Error: No native targets found")
            exit(1)
        }
        
        // 1. Add Plist to the project (Optional)
        if let plistPath = plistPath {
            print("Adding \(plistPath.lastComponent) to project...")
            let mainGroup = rootObject.mainGroup
            
            let appName = target.name
            let groupToAddTo = mainGroup?.children.first(where: { $0.path == appName }) as? PBXGroup ?? mainGroup
            
            // Only add if it doesn't already exist
            if groupToAddTo?.children.contains(where: { $0.path == plistPath.lastComponent || $0.name == plistPath.lastComponent }) == false {
                let fileRef = try groupToAddTo?.addFile(at: plistPath, sourceRoot: projectPath.parent())
                
                if let fileRef = fileRef, let buildPhase = target.buildPhases.first(where: { $0.buildPhase == .resources }) as? PBXResourcesBuildPhase {
                    _ = try buildPhase.add(file: fileRef)
                    print("Successfully added \(plistPath.lastComponent) to resources build phase.")
                }
            } else {
                print("\(plistPath.lastComponent) already exists in project.")
            }
        }
        
        // 2. Add Swift Package Dependency
        print("Adding Swift Package Dependency: \(repoURL)")
        
        // Check if package already exists
        let packageRef: XCRemoteSwiftPackageReference
        if let existingPkg = rootObject.remotePackages.first(where: { $0.repositoryURL == repoURL }) {
            packageRef = existingPkg
            print("Package already present.")
        } else {
            packageRef = try rootObject.addSwiftPackage(
                repositoryURL: repoURL, 
                productName: products.first!, 
                versionRequirement: .upToNextMajorVersion(versionRequirementString), 
                targetName: target.name
            )
        }
        
        // 3. Link requested products
        print("Linking products: \(products.joined(separator: ", "))")
        var frameworksBuildPhase = target.buildPhases.compactMap { $0 as? PBXFrameworksBuildPhase }.first
        if frameworksBuildPhase == nil {
            let newPhase = PBXFrameworksBuildPhase()
            pbxproj.add(object: newPhase)
            target.buildPhases.append(newPhase)
            frameworksBuildPhase = newPhase
        }
        
        for product in products {
            // Check if product is already linked
            if target.packageProductDependencies?.contains(where: { $0.productName == product }) == true {
                print("Product \(product) is already linked.")
                continue
            }
            
            let dependency = XCSwiftPackageProductDependency(productName: product, package: packageRef)
            pbxproj.add(object: dependency)
            
            if target.packageProductDependencies == nil { target.packageProductDependencies = [] }
            target.packageProductDependencies?.append(dependency)
            
            let buildFile = PBXBuildFile(product: dependency)
            pbxproj.add(object: buildFile)
            
            if frameworksBuildPhase?.files == nil { frameworksBuildPhase?.files = [] }
            frameworksBuildPhase?.files?.append(buildFile)
        }

        // 4. Add -ObjC linker flag if adding Firebase
        if products.contains(where: { $0.contains("Firebase") }) {
            print("Adding -ObjC to OTHER_LDFLAGS...")
            for configuration in target.buildConfigurationList?.buildConfigurations ?? [] {
                var otherLdFlags: [String] = []
                if let current = configuration.buildSettings["OTHER_LDFLAGS"] {
                    if let currentArray = current as? [String] {
                        otherLdFlags = currentArray
                    } else if let currentString = current as? String {
                        otherLdFlags = [currentString]
                    }
                }
                
                if !otherLdFlags.contains("-ObjC") {
                    otherLdFlags.append("-ObjC")
                    configuration.buildSettings["OTHER_LDFLAGS"] = otherLdFlags
                    print("Updated OTHER_LDFLAGS for configuration: \(configuration.name)")
                }
            }
        }

        if products.contains(where: { $0.contains("FirebaseCrashlytics")}) {
            print("Setting the debug format to DWARF with dSYMs")
            setDwarfWithDsymDebugInformationFormat(project: pbxproj)

            print("Adding the Crashlytics Run Script Build phase")
            if !hasCrashlyticsRunScriptBuildPhase(project: pbxproj) {
                addCrashlyticsRunScriptBuildPhase(project: pbxproj)
            } else {
                print("Crashlytics Run Script Build phase already exists")
            }
        }
        
        // Write changes
        try xcodeproj.write(path: projectPath)
        print("Successfully updated Xcode project!")
        
    } catch {
        print("Error: \(error)")
        exit(1)
    }
}

main()
SKILL.md
---
name: xcode-project-setup
description: Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).
compatibility: Requires Swift to be installed locally and macOS environment.
metadata:
  category: ApplicationDevelopment
---

# Xcode Project Setup

## ⛔️ CRITICAL RULES & ENVIRONMENT CHECKS

Before performing any Xcode setup or file manipulation, you **MUST** adhere to
the following rules. A hefty fee will be applied if you violate them.

### 1. The Anti-Ruby Mandate

You are **strictly forbidden** from using Ruby, Rails, or any Ruby gems
(including the `xcodeproj` gem). Under no circumstances may you write or execute
Ruby scripts.

### 2. Modern Xcode Folder Synchronization

Modern Xcode projects support folder synchronization. When adding new source
code (`.swift`) or resource files, simply write them to the correct directory on
disk. They will be automatically included in the Xcode project. **Never manually
modify the `.pbxproj` file to add files.**

### 3. Allowed Scripting Languages

If you absolutely must write a script to manipulate the project environment
(e.g., configuring SPM packages beyond what the provided `xcode_spm_setup`
script does), you **must use Swift**. Only as an absolute last resort, if Swift
is completely unviable, may you use Node.js or TypeScript.

### 4. Toolchain Verification

Because this skill relies entirely on a native Swift script, you must verify the
environment:

- Run `swift --version` before proceeding.
- If the Swift command is not found, you must stop and recommend the user
  install the Swift toolchain (e.g., via `xcode-select --install` on macOS), or
  ask if you can attempt to install it for them. Do not attempt to proceed
  without Swift.

### 5. Mandatory Linker Flags for Static Frameworks (Firebase)

When setting up SPM dependencies that heavily rely on internal Objective-C
categories and `+load` methods (such as the Firebase iOS SDK suite), the Apple
linker will aggressively strip these methods out if they are linked statically.

This causes fatal runtime crashes (e.g.,
`FirebaseAuth/Auth.swift:167: Fatal error: Unexpectedly found nil`).

**The provided `xcode_spm_setup` Swift script automatically injects the `-ObjC`
flag to `OTHER_LDFLAGS` when adding Firebase products.** However, you should
still verify it is present in the build settings if you encounter issues.

- Failing to include this flag when adding Firebase dependencies is a critical
  error.

______________________________________________________________________

## Empty Directory Workflow

If you are asked to build an iOS app or configure Xcode dependencies but **no
`.xcodeproj` or `.xcworkspace` exists**, you MUST ask the user to create the
project first:

**"No Xcode project found in this directory. Please create an empty Xcode
project manually and let me know when you are ready to proceed."**

Wait for the user to confirm they have created the `.xcodeproj` via Xcode, then
proceed with the Standard Xcode Workflow below.

______________________________________________________________________

## Standard Xcode Workflow

Do not use raw text parsing, `sed`, or Ruby scripts to modify `.pbxproj` files
directly.

Instead, execute the Swift configuration package bundled with this skill
(`scripts/xcode_spm_setup`) to securely install SPM packages and link optional
config files (like `GoogleService-Info.plist`).

### **CRITICAL: Always Use Latest SDK Version**

To ensure access to the latest features and security fixes, always use the most
recent version of the Firebase iOS SDK. Check for the latest release version at
[https://github.com/firebase/firebase-ios-sdk/releases](https://github.com/firebase/firebase-ios-sdk/releases).

- Use the most recent version number (e.g., `11.x.y`) in your commands instead
  of hardcoded placeholders.

### Understanding the Script's Actions

When adding a Swift Package to an Xcode project, two distinct steps must occur:

1. Adding the package repository dependency (e.g.,
   `https://github.com/Alamofire/Alamofire`).
1. Selecting the target (e.g., `MyApp`), navigating to **General > Frameworks,
   Libraries, and Embedded Content**, and hitting the `+` button to explicitly
   link the specific product modules (e.g., `Alamofire`).

**The provided `xcode_spm_setup` Swift script automatically handles BOTH of
these steps for you.** By passing the list of modules as arguments, it safely
injects the package dependency and automatically wires those modules to the main
target's Frameworks build phase. You do not need to do any manual linking.

## Usage

1. **Locate the package path:** Find the absolute path to this skill's
   `scripts/xcode_spm_setup` directory on disk.
1. **Execute:** Run the native `swift run` command using the signature below:

```bash
swift run --package-path <PATH_TO_SKILL>/scripts/xcode_spm_setup xcode_spm_setup <ProjectPath.xcodeproj> <RepoURL> <VersionRequirement> [--plist <Optional/Path/To/Config.plist>] <Product1> [Product2 ...]
```

### Example 1: Generic Package (e.g., Alamofire)

Adding Alamofire to a standard Xcode project. Notice there is no `--plist` flag.

```bash
swift run --package-path /Users/foo/.agents/skills/xcode-project-setup/scripts/xcode_spm_setup xcode_spm_setup MyApp.xcodeproj https://github.com/Alamofire/Alamofire 5.8.1 Alamofire
```

### Example 2: Firebase (Requires Plist)

Adding Firebase and linking the `GoogleService-Info.plist` to the resources
build phase automatically. *Note: Replace `11.0.0` with the actual latest
version from
[the releases page](https://github.com/firebase/firebase-ios-sdk/releases).*

```bash
swift run --package-path /Users/foo/.agents/skills/xcode-project-setup/scripts/xcode_spm_setup xcode_spm_setup MyApp.xcodeproj https://github.com/firebase/firebase-ios-sdk 11.0.0 --plist MyApp/GoogleService-Info.plist FirebaseCore FirebaseAuth FirebaseFirestore
```

*Note: The script is idempotent. It will automatically skip linking files or
packages that are already present in the project.*