Taking more control over your Cobra CLI documentation

Prompted by some discussions I've had recently around documenting Cobra CLIs, I realised that in November 2023 I wrote a library, cobra-doc-template and somehow I ended up not writing a blog post about it (how?? π ) - so here it is!
Inbuilt to Cobra is functionality to generate documentation from your CLI, which is a really great starting point for getting some out-of-the-box rendered documentation for your CLI, in a way that avoids having to hand-roll it.
For a couple of CLIs I work on building - an internal CLI tool at Elastic, and the other for dependency-management-data - I've found that the generated docs don't quite work for exactly what I wanted.
For instance, there may be custom docs-specific metadata you need to use for your docs platform (i.e. <Link ...>
) or it may be that deprecated commands are not currently rendered by Cobra, which is a bit of a pain.
So I set about creating a hacky solution to see if it would work, and raised an upstream feature request.
Over the last ~18 months it's been very useful, and so today I thought I'd finalise the repository, add some tests and documentation.
Usage
The intent is that you can take cobra-doc-template and provide it a text/template
, and it'll write out the generated documentation.
My use-cases have been for Markdown-shaped content (either .md
or .mdx
) but it should be possible to use it for any other purpose.
For instance, we can see the following snippet:
## {{ .Command.CommandPath }}
{{ if .Command.Deprecated -}}
> [!WARNING]
> Note that the <code>{{ .Command.CommandPath }}</code> command is deprecated:
>
> {{ .Command.Deprecated }}
{{ else -}}
```console
{{ .Command.Use }}
```
{{ end }}
This will then render a GitHub-flavoured Markdown warning if the command is deprecated, otherwise indicate how to use it (with syntax highlighting!)
Full usage can be seen either in the package's testable examples or in its tests, or how dependency-management-data is using it.
You can see the input data to the templates gives you full access to the underlying cobra.Command
, as well as some helpers that make it easier to access things that can be a little awkward to do within a template.
Example
The dependency-management-data docs are currently using it, for instance the dmd import bulk
command.
You can also see an example of what a deprecated command looks like.
Hope it's as useful as it has been for me!