Xcode针对有条件的SPM依赖项的构建脚本。

7

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

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


(未提供需要翻译的内容,请提供完整信息)
if ENV['enabled'].to_i == 1
 pod 'Google'
end 

据我所知,SPM只部分支持条件依赖关系,这对我的问题来说不够: https://github.com/apple/swift-evolution/blob/main/proposals/0273-swiftpm-conditional-target-dependencies.md 我正在考虑创建一个生成阶段脚本,根据环境变量条件手动包含框架作为目标成员。
正在寻找可行的解决方案。
1个回答

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"]),
    ]
)

现在您可以构建不依赖于其他包的软件包:

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

通过在环境变量中设置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)

做得好,iUrii!但是要使用这个技能,我们需要通过命令行进行构建,对吗? - kakaiikaka
2
谢谢回答iUrii,不幸的是,我没有package.swift文件,因为我正在将其用于XCode项目而不是Swift软件包。 - Peter Lendvay
我也很好奇。已经开始了悬赏。这个答案似乎不适用于Xcode项目。 - Sunkas
@PeterLendvay 你可以创建一个本地的 Swift 包来包装 "Google" 包,然后将这个本地包包含到 Xcode 中,https://developer.apple.com/documentation/xcode/organizing-your-code-with-local-packages - JIE WANG
4
@JIEWANG 本地 Swift 包的方法不适用于使用环境变量等方式管理包依赖,因为 XCode 在构建之前在单独的进程中运行 Package.swift 代码(解决包图),不会共享来自项目设置的任何 Swift Active Compilation Flags 或环境变量。 - iUrii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接