Ivan Dubrov
Ivan Dubrov

Reputation: 4788

Is there a way to enable a Cargo feature only when rustdoc verifies examples?

I have the following piece in the crate documentation:

//! # Examples
//! ```rust,no_run
//! extern crate stm32f103xx;
//! // ...
//! ```

The problem is that the dependency on stm32f103xx crate is optional. Everything works fine if I enable feature stm32f103xx by default, but I don't want to make it default. Is there any way to enable that feature only when rustdoc verifies examples?

Upvotes: 3

Views: 1426

Answers (2)

Shepmaster
Shepmaster

Reputation: 430544

No. Features are chosen by the end user of the crate, and you aren't the only person who chooses to run the tests. If you could do what you are asking, you'd actually force anyone who wanted to run the tests to download and compile the "optional" dependency, making it not very optional.


What you can do instead is only include that piece of the documentation when the feature is enabled. It's not obvious, but documentation comments are transformed into the attribute syntax (#[doc = "..."]). Combined with cfg_attr, you can conditionally include documentation, thus conditionally compile and run an example:

#![cfg_attr(feature = "alpha", doc = "
# Examples
```rust
fn alpha() {}
```
")]

Likewise, you can have the opposite case for a bit of documentation that says "check out this awesome feature!".

See also:

Upvotes: 4

E_net4
E_net4

Reputation: 29972

In order to always have a dependency when compiling any parts of the project (including tests such as that one), Development Dependencies are a good fit.

[dev-dependencies]
stm32f103xx = "0.7.5"

As you mention that the crate is also optional as a main dependency, you can keep it as so in your manifest.

[dependencies]
stm32f103xx = { version = "0.7.5", optional = true }

Upvotes: 1

Related Questions