beardc
beardc

Reputation: 21063

Re-export optional cargo feature that can be turned off

With the following directory structure:

tree hello_dep
.
├── Cargo.lock
├── Cargo.toml
├── dep_a
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── dep_b
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── src
    └── main.rs

And the following dependency chain: hello_dep -> dep_a -> dep_b -> (optional feature) rustc-serialize, I would like to create a feature in dep_a that re-exports the optional rustc-serialize feature in dep_b.

At the bottom, I have dep_b, which has rustc-serialize as an optional default feature:

# dep_b/Cargo.toml
[package]
name = "dep_b"
version = "0.1.0"

[dependencies]
rustc-serialize = { version = "0.3.19", optional = true }

[features]
default = ["rustc-serialize"]

I would like to create a feature in dep_a to optionally reexport "rustc-serialize". Here is the attempt:

# dep_a/Cargo.toml
[package]
name = "dep_a"
version = "0.1.0"

[dependencies]
dep_b = { version = "0.1.0", path = "../dep_b" }

[features]
rustc-serialize = ["dep_b/rustc-serialize"]
default = ["rustc-serialize"]

However, when I try to add this as a dependency with the default off using the following Cargo.toml:

# hello_dep/Cargo.toml
[package]
name = "hello_dep"
version = "0.1.0"

[dependencies]
dep_a = { version = "0.1.0", path = "dep_a", default-features = false, optional = true }

cargo build still yields rustc-serialize in Cargo.lock. But directly depending on dep_b correctly avoids pulling in rustc-serialize with the following line

dep_b = { version = "0.1.0", path = "dep_b", default-features = false }

Is this a bug in Cargo, or am I doing something wrong? Here is a related question

Upvotes: 1

Views: 544

Answers (1)

Francis Gagné
Francis Gagné

Reputation: 65692

In dep_a/Cargo.toml, you did not specify default-features = false on the dep_b dependency. Therefore, the rustc-serialize feature in dep_b is enabled by default. The fact that you included a feature in dep_a to enable dep_b's rustc-serialize doesn't change the fact that it's still enabled when dep_a's feature is not enabled.

Thus, in dep_a/Cargo.toml, you should have:

[dependencies]
dep_b = { version = "0.1.0", path = "../dep_b", default-features = false }

Upvotes: 4

Related Questions