如何在`cargo doc`生成的文档中获取功能需求标签?

问题描述 投票:0回答:2

如果您查看 docs.rs 上的 Tokio 文档,有一个蓝色标签表示必须激活某个功能才能访问此 API:

enter image description here

我也想为我的板条箱启用此功能,该怎么做?

rust rustdoc
2个回答
36
投票

坏消息是:目前仅提供夜间功能。

好消息是:docs.rs 默认使用 nightly。


要使其发挥作用,您所需要做的就是启用

doc_cfg
功能 并将
#doc(cfg)
应用于正在记录的项目

#![feature(doc_cfg)]

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

因为这是仅限夜间使用的功能,您可能不想一直启用它。

tokio
在其
Cargo.toml
中定义了以下内容,仅在 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"]

然后他们使用

// 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() {}

11
投票

在最新的 nightly 中(可能从 v1.57 开始),您可以使用功能

doc_auto_cfg
(合并在 PR#90502 中),并且您不再需要手动标记
doc
的功能,只需像以前一样编写
cfg
:

#![feature(doc_auto_cfg)]

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

要在本地检查,请运行

cargo +nightly doc --all-features

如果您想继续使用 stable 来执行除

cargo doc
以外的命令,您可以:

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

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

更新:上述方法仍然需要

doc-tests
每晚运行,并且还需要依赖者的
doc
命令每晚运行。解决方法是我们只能在夜间启用
doc_auto_cfg
功能。

Cargo.toml
中,添加:

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

[build-dependencies]
rustc_version = "0.4.0"

创建一个包含以下内容的

build.rs
文件:

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

然后我们可以这样启用该功能

doc_auto_cfg

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

由于

docs.rs
默认使用 nightly,那里的文档将按照您的预期显示。

© www.soinside.com 2019 - 2024. All rights reserved.