rust-lang / cargo

The Rust package manager
https://doc.rust-lang.org/cargo
Apache License 2.0
12.75k stars 2.42k forks source link

Document/standardize the `docsrs` "well-known" feature #13875

Open zvolin opened 6 months ago

zvolin commented 6 months ago

Problem

Recently standardized --check-cfg started triggering in my project. There is some common pattern in crates that want to use another nightly feature, doc_cfg, to do stuff like:

[package.metadata.docs.rs]
rustdoc-args = ["--cfg", "docs_rs"]
#![cfg_attr(docs_rs, feature(doc_cfg))]

#[cfg(feature = "foo")]
#[cfg_attr(docs_rs, doc(cfg(feature = "foo")))]
pub mod p2p;

The cfg attribute was used just to conditionally include the doc_cfg feature so that it is only present in docs.rs builds and not require nightly on a daily basis. When adding this I found no mention or whatever about any requirements for the name of the additional cfg flag used for this guard. It looked like docsrs is most widely used (eg. by tokio), however I opted in for docs_rs as I found it easier to read.

After standardizing of --check-cfg it turned out it's failing with the given message:

error: unexpected `cfg` condition name: `docs_rs`
  --> types/src/lib.rs:16:12
   |
16 | #[cfg_attr(docs_rs, doc(cfg(feature = "p2p")))]
   |            ^^^^^^^ help: there is a config with a similar name: `docsrs`
   |
   = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(docs_rs)");` to the top of the `build.rs`
   = note: see <https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#rustc-check-cfg> for more information about checking conditional configuration

Indeed, after switching to docsrs everything is fine. I found that it's explicitely included here because that's what docs.rs uses internally, however I couldn't find it in any documentation, nor in the "well-known" names.

Steps

No response

Possible Solution(s)

No response

Notes

No response

Version

❯ cargo +nightly --version
cargo 1.80.0-nightly (05364cb2f 2024-05-03)
zvolin commented 6 months ago

potentially affected crates can be searched with https://github.com/search?q=%2Frustdoc-args.*--cfg.*docs_rs%2F&type=code but that only includes the crates using the docs_rs attribute, github doesn't support look around regexes so I didn't find a way to search for ones which have 'not docsrs'

weihanglo commented 6 months ago

Indeed, after switching to docsrs everything is fine. I found that it's explicitely included here because that's what docs.rs uses internally, however I couldn't find it in any documentation, nor in the "well-known" names.

This is documented in https://docs.rs/about/builds#detecting-docsrs.

And yeah agree this is a bit hard to discover. The Cargo team has talked about documenting the interaction of --check-cfg between rustc, cargo and other systems. Currently we don't have a simple answer for that.

weihanglo commented 6 months ago

See also: