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

lnvxswe2  于 2022-10-23  发布在  Swift
关注(0)|答案(1)|浏览(174)

bounty 5天后到期。这个问题的答案有资格获得+150的声誉赏金。Sunkas希望引起更多关注这个问题:我需要一个适用于Xcode项目的答案,而不是一个SWIFT包。

我正在将一个项目从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来说是不够的
我正在考虑创建一个构建阶段脚本,以便根据环境变量条件手动将框架作为目标成员包括在内。
寻找可行的解决方案。

laik7k3q

laik7k3q1#

“Package.swft”是一个常规的快速文件,您可以为其中的逻辑和条件编写任何代码。例如,您可以使用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来实现领域依赖关系:

$ 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)

相关问题