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.
great👍, thank you)