-
Notifications
You must be signed in to change notification settings - Fork 313
Description
The current approach to writing examples is to write the code directly in the markdown files an then combine and use skeptic for testing.
The downside of this is that it's more difficult to edit the code using the standard rust tooling (rust-analyzer, rustfmt, clippy, etc.)
A better approach (@jamesgraves did this in https://github.com/jamesgraves/rust-cookbook/) is to move all the code into actual projects and then import from files into mdbook (see https://rust-lang.github.io/mdBook/format/mdbook.html#including-files)
Doing this means that in general you can write code, lint it and format it, and then view the code snippet in the book directly. It also means that each snippet can be supported by the relevant cargo manifest necessary just for that snippet rather than a manifest for the entire cookbook, and it makes it possible to run each example directly when you clone the repo.
Implementation
We use this approach successfully in the Ratatui website. This started as an mdbook site and then we moved to using Starlight (a doc site template for Astro). To do this we added the same idea of importing code from files to the stock code block element, and then went a little further to reduce the amount of // ANCHOR
comments needed for importing rust functions using tree sitter to parse out just functions of interest. This might be possible to backport into mdbook.
Minor side note (code organization)
I'm not 100% in agreement with the arrangement of where the rust projects end up in the tree in @jamesgraves version. They feel a bit jumbled together which is difficult to navigate. In Ratatui, we had a second root code
folder with just the crates / code. This observation is a minor one however, as I think it's much better to have this functionality than to bikeshed on exactly how it's organized. Perhaps there's some hybrid where each crate has a src
folder with a docs
folder alongside it. That would make it feel less jumbled (I'm not whether it's possible with mdbook to have the file location and url not fully aligned like this)