SBSTP
SBSTP

Reputation: 3639

How to get a feature requirement tag in the documentation generated by `cargo doc`?

If you look at the Tokio docs on docs.rs there's a blue tag indicating that a feature must be activated in order to access this API:

enter image description here

I would like to enable this for my crate as well, how can this be done?

Upvotes: 27

Views: 4233

Answers (2)

Sprite
Sprite

Reputation: 3763

In the latest nightly (since v1.57 maybe), you can use feature doc_auto_cfg (merged in PR#90502) and you no longer need to manually mark features for doc, just write cfg as before:

#![feature(doc_auto_cfg)]

#[cfg(feature = "macros")]
pub fn test() {}

To check it locally, run cargo +nightly doc --all-features.

If you want to continue using stable for commands other than cargo doc, you can:

#![cfg_attr(doc, feature(doc_auto_cfg))]

#[cfg(feature = "macros")]
pub fn test() {}

UPDATE: The above method still requires doc-tests to run nightly, and it also requires dependents' doc command to run nightly. A workaround is that we can enable the doc_auto_cfg feature only under nightly.

In Cargo.toml, adding:

[package.metadata.docs.rs]
all-features = true

[build-dependencies]
rustc_version = "0.4.0"

Create a build.rs file with the following contents:

use rustc_version::{version_meta, Channel};

fn main() {
    // Set cfg flags depending on release channel
    let channel = match version_meta().unwrap().channel {
        Channel::Stable => "CHANNEL_STABLE",
        Channel::Beta => "CHANNEL_BETA",
        Channel::Nightly => "CHANNEL_NIGHTLY",
        Channel::Dev => "CHANNEL_DEV",
    };
    println!("cargo:rustc-cfg={}", channel)
}

Then we can enable the feature doc_auto_cfg this way:

#![cfg_attr(all(doc, CHANNEL_NIGHTLY), feature(doc_auto_cfg))]

Since docs.rs uses nightly by default, the documentation on there will be shown as you expected.

Upvotes: 13

mcarton
mcarton

Reputation: 30001

The bad news is: It's a nightly-only feature for now.

The good news is: docs.rs uses nightly by default.


To get this to work all you need is to enable the doc_cfg feature and apply #doc(cfg) to the item being documented

#![feature(doc_cfg)]

#[doc(cfg(feature = "macros"))]
pub fn test() {}

Because this is a nightly-only feature, you probably don't want to enable it all the time. tokio defines the following in its Cargo.toml to only enable this feature on docs.rs:

# docs.rs-specific configuration
[package.metadata.docs.rs]
# document all features
all-features = true
# defines the configuration attribute `docsrs`
rustdoc-args = ["--cfg", "docsrs"]

and then they use

// only enables the `doc_cfg` feature when
// the `docsrs` configuration attribute is defined
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
pub fn test() {}

Upvotes: 41

Related Questions