Rendering documentation for your CLI apps

Documentation for CLIs usually consists ofa —help section in the commandand a manual (man) page.

Both can be automatically generatedwhen using clap v3 (in unreleased alpha,at time of writing), via the man backend.

  1. #[derive(Clap)]
  2. pub struct Head {
  3. /// file to load
  4. #[clap(parse(from_os_str))]
  5. pub file: PathBuf,
  6. /// how many lines to print
  7. #[clap(short = "n", default_value = "5")]
  8. pub count: usize,
  9. }

Secondly, you need to use a build.rsto generate the manual file at compile timefrom the definition of your appin code.

There are a few things to keep in mind(such as how you want to package your binary)but for nowwe simply put the man filenext to our src folder.

  1. use clap::IntoApp;
  2. use clap_generate::gen_manuals;
  3. #[path="src/cli.rs"]
  4. mod cli;
  5. fn main() {
  6. let app = cli::Head::into_app();
  7. for man in gen_manuals(&app) {
  8. let name = "head.1";
  9. let mut out = fs::File::create("head.1").unwrap();
  10. use std::io::Write;
  11. out.write_all(man.render().as_bytes()).unwrap();
  12. }
  13. }

When you now compile your applicationthere will be a head.1 filein your project directory.

If you open that in manyou’ll be able to admire your free documentation.