Skip to content

include target in build when trait is active #9340

@JaapWijnen

Description

@JaapWijnen

Description

I have the following case for which I’m trying to use package traits.
I have a library of which some part of the implementation is platform specific. I've moved that part separate targets (A and B). Both of those implementations provide a single public function with the same signature. So that if either trait A is active or trait B is active SomeLibrary will be able to compile.

Now the below setup works perfectly if I just instruct swift build to build the SomeLibrary target by using:
swift build --target SomeLibrary --traits PlatformA
But fails when I simply try to build the full package using:
swift build --traits PlatformA
since this will still try to build PlatformBImplementation (which fails on my current platform)

Is there any way to only add this target when a certain trait is active?

A different solution would be wrapping everything in PlatformBImplementation in #if PlatformB but that seems to kind of defeat the purpose.
Another solution would be to have both implementations live in a separate package. But it seems kind of overkill in my situation.

I'd really like to be an able to do this using traits. Or understand why (if true) this is not possible.

Any help is greatly appreciated!

let package = Package(
name: “some-package”,
products: [.library(name: “SomeLibrary”, targets: [“SomeLibrary”])],
traits: [
“PlatformA”,
“PlatformB”,
],
targets: [
.target(
name: “SomeLibrary”,
dependencies: [
.target(name: "PlatformAImplementation", condition: .when(traits: ["PlatformA"])),
.target(name: "PlatformBImplementation", condition: .when(traits: ["PlatformB"])),
]
),
.target(name: “PlatformAImplementation”),
.target(name: “PlatformBImplementation”),
]
)

Expected behavior

No response

Actual behavior

No response

Steps to reproduce

No response

Swift Package Manager version/commit hash

No response

Swift & OS version (output of swift --version && uname -a)

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions