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

23

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

enter image description here

我也想为我的包启用这个功能,应该如何操作?

2个回答

32

坏消息是:目前这只是夜间版本的功能。

好消息是:docs.rs默认使用夜间版本。


为使其生效,您需要启用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() {}

13
本地测试请使用以下命令:RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features - Niklas

10
在最新的夜版(可能从版本1.57开始),你可以使用功能doc_auto_cfg(合并在PR#90502中),无需手动标记doc的特性,只需像以前一样编写cfg即可。
#![feature(doc_auto_cfg)]

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

要在本地检查它,请运行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() {}

更新: 上述方法仍需要运行每夜版的 doc-tests,并且它还需要依赖项的 doc 命令在每夜版下运行。一种解决方法是我们可以仅在每夜版下启用 doc_auto_cfg 功能。

Cargo.toml 文件中添加:

[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默认使用夜间版,因此那里的文档将会按照您的期望显示。


这在稳定版的文档测试中会失败,我猜想是因为启用了 doc 功能。我还尝试过 #![cfg_attr(all(doc, not(test)), feature(doc_auto_cfg))]#![cfg_attr(all(doc, not(doctest)), feature(doc_auto_cfg))],但没有成功。 - FujiApple
1
@FujiApple 我已经更新了答案,请检查是否适用 :) - Sprite
这是否需要在Cargo.toml中设置,以便crates.io显示所有功能的文档?[package.metadata.docs.rs] all-features = true - extremeandy
@extremeandy 我认为是的。如果一个模块被 cfg 禁用,Rustc 将无法看到它。 - Sprite

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接