Detecting `cargo doc` invocation from build scripts

My crate builds C++ with cmake inside of build scripts.
But for building documentation (with cargo doc) I would want to skip the C++ part: as required libraries are not available in the pipeline at that point.
I can do this with a feature flag and build docs like cargo doc --features build-docs, but this seems redundant.

Maybe cargo doc already sets some envars I can reliably check against?

I haven't tried this in a build script before, but rustdoc sets --cfg doc for conditional compilation, allowing you to use #[cfg(doc)] in your code. I assume this can be used in your build script, e.g. by guarding the part that builds the CPP dependencies behind a #[cfg(not(doc))].

Thanks!

fn main() {
    #[cfg(doc)]
    {
        return;
    }
    panic!("Feature not enabled");
}

Results in:

$ cargo doc
...
  thread 'main' panicked at crates\test_crate\build.rs:8:5:
  Feature not enabled

It does work, however, when I build documentation for the test_crate directly:

$ cargo doc -p test_crate
...
Finished `dev` profile [unoptimized + debuginfo] target(s) in 7.56s

UPDATE:
Actually, no, cargo doc -p doesn't run build.rs at all.

Looks like I was wrong and --cfg doc is not passed to the build script:

1 Like

Builds on docs.rs set DOCS_RS env var.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.