How to turn off cargo doc test and compile for a specific module in Rust

1.2k Views Asked by At

I have some generated .rs code (from grpc proto files) and they are checked in with my normal Rust code under src but in some sub modules. The issue is that when doing cargo test the doc test will run and some of the generated .rs have comments with indentations (code blocks) and cargo doc test will try to compile them and fail.

For example cargo test will try to compile (and perhaps run these lines) show here.

Is there a way to exclude or ignore those generated .rs for doc test (without manually changing them)?

1

There are 1 best solutions below

4
On

Updated answer:

I have hacked together a crate tonic-disable-doctest for disabling doctests, it may be used as such:

use tonic_disable_doctest::BuilderEx;

fn main() {
    tonic_build::configure()
        .disable_doctests_for_types([".google.api.HttpRule"])
        .compile(
            &["proto/api/google/api/http.proto"],
            &["proto/"],
        )
        .unwrap();
}

Old answer

My solution

I've resolved this by injecting code that separates the offending comment and the structure underneath:

fn main() {
    tonic_build::configure()
        .type_attribute(
            ".google.api.HttpRule",
            "#[cfg(not(doctest))]\n\
             #[allow(dead_code)]\n\
             pub struct HttpRuleComment{}\n\
             /// HACK: see docs in [`HttpRuleComment`] ignored in doctest pass",
        )
        .compile(
            &["proto/api/google/api/http.proto"],
            &["proto/"],
        )
        .unwrap();
}
Explanation:
  1. tonic_build allows adding attributes to specific protobuf paths, but it does not discern between attributes or any other strings.
  2. #[cfg(not(doctest))] excludes the comment's offending code from doc tests, because it excludes the structure it's added to, this trick is taken from discussion on Rust user forum.
  3. #[allow(dead_code)] silences warnings about injected structure not being used (as it shouldn't be used).
  4. pub struct HttpRuleComment{} creates a public structure that can be referenced in the docstring for the original struct.
  5. /// ...[HttpRuleComment]... is a docstring referencing injected struct, so that the original documentation can still be accessed.
Notes:

I'm not sure if your case is the same, but I found myself on this SO page a lot while searching for an answer and decided to share the results.

In my case, the only offending comment was in HttpRule, you may need to write a macro or do lots of copy-paste if you happen to have multiple offending comments.