Rust CLI: Add CLI docs to your README.md
Generate CLI docs in your README for a Clap-based Rust CLI.

So you've written a Rust CLI with Clap and you want to update your README.md with details on how to use it. Well, ConnorGray has written a library that does just that:
GitHub - ConnorGray/clap-markdown: Autogenerate Markdown documentation for clap command-line tools
Autogenerate Markdown documentation for clap command-line tools - ConnorGray/clap-markdown
Problem: clap-markdown generates markdown just fine, but we want to add the output to our README.md without overwriting the entire contents of the file..
Solution: use hidden comments in the README as a placemarker.
1. Add something like the following to your README.md file:
<!-- start: CLI USAGE -->
<!-- end: CLI USAGE -->
- Add a hidden command to your CLI as suggested by clap-markdown here, which should call a function that looks something like:
pub fn add_cli_cmd_to_readme() -> Result<()> {
let md = clap_markdown::help_markdown::<Cli>();
// Read the README.md file
let mut content = std::fs::read_to_string("README.md")?;
// Find the start and end markers
let start = "<!-- start: CLI USAGE -->";
let end = "<!-- end: CLI USAGE -->";
// Replace content between markers
let start_idx = content
.find(start)
.ok_or_else(|| anyhow::anyhow!("Could not find start marker"))?;
let end_idx = content
.find(end)
.ok_or_else(|| anyhow::anyhow!("Could not find end marker"))?;
content.replace_range((start_idx + start.len())..end_idx, &format!("\n\n{}\n", md));
// Write back to README.md
std::fs::write("README.md", content)?;
println!("Markdown help written to README.md");
Ok(())
}
This function will add the output of clap_markdown
your between the place markers in your README.md.
Example
Here's a repo of mine using it: https://github.com/nbw/foto
I run cargo run – cli-readme
to generate a new README.md with updated docs.
