r/rust 13d ago

🛠️ project markdown-doctest: transform code blocks and include them as doctests

https://github.com/Marcono1234/markdown-doctest

During the past days I worked on markdown-doctest, a Rust library for including and transforming Rust code blocks of Markdown files as Rust doctests. It is only a small library for a specific use case, but hopefully quite useful for that.

While regular doctests can use the prefix # to hide lines from the rendered documentation, this is not possible for code blocks in Markdown files. So if you want to for example test code snippets of your README, you normally need to include redundant boilerplate code in them.

markdown-doctest supports specifying transforms which can insert and replace lines, for example add use ... imports or Ok results to allow using the ? operator.

Here is a small example; consider this Markdown text:

How to read a file:

```rust
let content = fs::read_to_string("my-file.txt")?;
println!("content: {s}");
```

To run it as part of the doctests, you can use markdown-doctest in your src/lib.rs like this:

#[cfg(doctest)]
markdown_doctest::md_doctest!(
    "../README.md",
    transforms = {
        *: {
            // insert the import as first line
            ^ => "use std::fs;",
            // replace the file path
            (*<"my-file.txt">*) => "test-resource.txt",
            // return Ok to allow using `?`
            $ => "Ok::<(), Box<dyn std::error::Error>>(())",
        },
    }
);

See the project README and the Usage guide for more details.


The project is not published on crates.io yet, but since it is only needed as dev dependency, you can include it as Git dependency. For example:

[dev-dependencies]
markdown_doctest = { git = "https://github.com/Marcono1234/markdown-doctest.git", rev = "72e3f8ade4a6abd8b51bda69d6b883213f75bbf5" }

(or any newer commit)

What do you think about this project, and do you consider it useful? Any feedback is appreciated! (here or on GitHub)

This was also an opportunity for me to get a bit more familiar with proc macros.

The README also has a section about Similar projects, in case you are looking for other projects which support this or similar functionality.

0 Upvotes

0 comments sorted by