Skip to content

Supply a Cobra command tree

docscheck takes a docscheck.Command tree and imports no CLI framework of its own — a constraint the module enforces on itself in TestDependencyFootprint. Converting from Cobra is a few lines.

The conversion

func tree(c *cobra.Command) docscheck.Command {
    n := docscheck.Command{Name: c.Name()}
    for _, sub := range c.Commands() {
        n.Sub = append(n.Sub, tree(sub))
    }

    return n
}

c.Commands() returns the child commands, so this walks the whole tree. Call it on your root:

root, _ := root.NewCmdRoot(version.Info{})
checker, err := docscheck.New(tree(root.Command))

Get the root's name right

The root's Name is what a reader types, and docscheck looks for exactly that word in your documentation. Cobra derives Name() from the first word of Use, so a root with Use: "krites" gives krites — but a root that never set Use gives you the binary name Cobra guessed, which may not be what your docs say. Check it:

if root.Name() != "krites" {
    t.Fatalf("unexpected root name %q", root.Name())
}

Hidden and generated commands

Cobra's Commands() includes hidden commands and the ones Cobra adds itself (help, completion). Include them: your documentation may legitimately mention completion, and a command being hidden does not stop someone documenting it. Excluding them can only produce false positives.

Other frameworks

Nothing here is Cobra-specific. Any framework that can enumerate a command and its children converts the same way — build docscheck.Command values and hand the root to New.