用于条件 SPM 依赖项的 Xcode 构建脚本

Pet*_*vay 7 dependency-management ios cocoapods swift swift-package-manager

我正在将一个项目从 Cocoapods 迁移到 SPM,但我遇到了一个问题,即我们只需要在有条件的情况下使用某些依赖项。

Cocoapods 有一个简单的解决方案:

if ENV['enabled'].to_i == 1
 pod 'Google'
end 
Run Code Online (Sandbox Code Playgroud)

据我所知,SPM 仅部分支持条件依赖项,这不足以解决我的问题: https://github.com/apple/swift-evolution/blob/main/proposals/0273-swiftpm-conditional-目标依赖项.md

我正在考虑创建一个构建阶段脚本,以根据环境变量条件手动将框架包含为目标成员。

寻找可行的解决方案。

iUr*_*rii 0

“Package.swift”是一个常规的 swift 文件,您可以在其中编写适合您的逻辑和条件的任何代码。例如,您可以检查环境变量并ProcessInfo组装所需的依赖项数组:

import PackageDescription
import Foundation

let useRealm = ProcessInfo.processInfo.environment["realm"] == "1"

let packageDependencies: [Package.Dependency] = useRealm
    ? [.package(url: "https://github.com/realm/realm-cocoa.git", from: "10.15.1")]
    : []

let targetDependencies: [Target.Dependency] = useRealm
    ? [.product(name: "Realm", package: "realm-cocoa")]
    : []

let package = Package(
    name: "MyPackage",
    platforms: [
        .iOS(.v12),
        .macOS(.v10_14)
    ],
    products: [
        .library(name: "MyPackage", targets: ["MyPackage"]),
    ],
    dependencies: packageDependencies,
    targets: [
        .target(name: "MyPackage", dependencies: targetDependencies),
        .testTarget(name: "MyPackageTests", dependencies: ["MyPackage"]),
    ]
)
Run Code Online (Sandbox Code Playgroud)

现在您可以构建没有依赖项的包:

$ xcrun --sdk macosx swift build
Building for debugging...
[2/2] Emitting module MyPackage
Build complete! (0.77s)
Run Code Online (Sandbox Code Playgroud)

并通过realm=1在环境变量中设置 Realm 依赖项:

$ export realm=1
$ xcrun --sdk macosx swift build
Fetching https://github.com/realm/realm-cocoa.git from cache
Fetched https://github.com/realm/realm-cocoa.git (2.12s)
Computing version for https://github.com/realm/realm-cocoa.git
Computed https://github.com/realm/realm-cocoa.git at 10.32.0 (0.02s)
Fetching https://github.com/realm/realm-core from cache
Fetched https://github.com/realm/realm-core (1.37s)
Computing version for https://github.com/realm/realm-core
Computed https://github.com/realm/realm-core at 12.9.0 (0.02s)
Creating working copy for https://github.com/realm/realm-cocoa.git
Working copy of https://github.com/realm/realm-cocoa.git resolved at 10.32.0
Creating working copy for https://github.com/realm/realm-core
Working copy of https://github.com/realm/realm-core resolved at 12.9.0
Building for debugging...
[63/63] Compiling MyPackage MyPackage.swift
Build complete! (41.64s)
Run Code Online (Sandbox Code Playgroud)

  • @JIEWANG使用本地swift包的方法不适用于管理与环境变量等的包依赖关系,因为XCode在构建之前在单独的进程中运行Package.swift代码(解析包图)并且不共享任何Swift Active Compilation Flags或环境来自项目设置的变量。 (4认同)
  • 感谢 iUrii 的回答,不幸的是我没有 package.swift 文件,因为我将它用于 XCode 项目而不是 swift 包。 (2认同)