// build.rs
fn main(){
if std::env::var("DOCS_RS").is_ok(){
panic!("{}",std::env::var("DOCS_RS").is_ok());
}/*else{
panic!("aaa");
}*/
}
In PowerShell, $env:DOCS_RS="1"; cargo build
can be successfully compiled, which is not expected. However, if you uncomment the comment
--- stderr
thread 'main' panicked at build.rs:3:9:
true
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The expected error will be printed out. What's the reason here? It's confusing.
maybe the build script is not run at all. try add:
println!("cargo::rerun-if-env-changed=DOCS_RS");
However, if the else
branch is supplied, the build.rs
do work.
if you modified build.rs
, cargo will automatically (rebuild and) re-run the build script. but if you only change the environment variable without changing the build script (or any ./src/*
files), cargo build
will not re-run the build script (unless it's a clean build).
Okay. I still found a confusion part. If I manually set $env:RUSTFLAGS="--cfg docsrs"; cargo doc --open
, then I can still see the item in the generated documentation, where the item in the source code is written as:
// lib.rs
#[cfg(not(docsrs))]
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
However, if I used the build.rs, for example,
fn main(){
println!("cargo:rustc-cfg=docsrs");
}
Then, the generated documentation won't include the add
item? Shouldn't rustc-cfg
equal RUSTFLAGS="--cfg docsrs"
?
PS: If I want to manually set docsrs
, I need to set RUSTDOCFLAGS="--cfg docsrs"
. Why does rustc-cfg
in build.rs
affect RUSTDOCFLAGS
?
this, I don't really know, presumably cargo is hanlding the environment variables before invoking rustdoc
.
I wonder does it behave differently between cargo doc
and cargo rustdoc
? I vaguely remember there's different hanlding for the flags between cargo build
and cargo rustc
, maybe it's similar for the case of documentation?