Skip to content

Instantly share code, notes, and snippets.

@JakeHartnell
Last active March 19, 2024 16:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakeHartnell/2c1fa387f185f5dc46c9429470a2e2be to your computer and use it in GitHub Desktop.
Save JakeHartnell/2c1fa387f185f5dc46c9429470a2e2be to your computer and use it in GitHub Desktop.
Include README.md files in rust documentation generation

Include README.md in documentation generation and tests

Recentely, I was trying to make sure our README.md files for DAO DAO were included in the documentation generated by cargo doc or rustdoc. Moreover, I wanted code examples in our README.md files to be tested.

Here's a quick gist...

There is of course the doc attribute, and the rust book contains the following example which you are meant to include in your lib.rs or main.rs:

#[doc = include_str!("../../README.md")]

However, this doesn't always work! The include_str! macro doesn't correctly parse the file path for certain build targets like WASM. If you are like me, you keep your rust code in a src/ folder, with the README.md file in the parent directory. Googling did not yield a good way to solve this!

What to do?

The solution is simple: just use the env! and concat! macros along with the $CARGO_MANIFEST_DIR environment variable!

#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]

Now we just keep our README.md files up to date and they are included in cargo doc generation as well as tests.

Hope this helps someone.

@deveusss
Copy link

deveusss commented Nov 22, 2022

great👍, thank you)

@TrevorJTClarke
Copy link

This is rad!

@srackham
Copy link

Works, thanks!

@sammysheep
Copy link

Very cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment