or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

command-basics.mdcompletions.mddoc-generation.mdflags.mdindex.md
tile.json

doc-generation.mddocs/

Documentation Generation

The github.com/spf13/cobra/doc package provides functions to automatically generate documentation for Cobra commands in multiple formats: man pages, Markdown, reStructuredText, and YAML.

Import

import "github.com/spf13/cobra/doc"

Man Page Generation

type GenManHeader struct {
    Title   string
    Section string
    Date    *time.Time
    Source  string
    Manual  string
}

func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error
func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error
func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error

Generate Unix man pages for your command:

package main

import (
    "github.com/spf13/cobra"
    "github.com/spf13/cobra/doc"
    "time"
)

func main() {
    cmd := &cobra.Command{
        Use:   "myapp",
        Short: "My application",
    }

    // Add subcommands...

    header := &doc.GenManHeader{
        Title:   "MYAPP",
        Section: "1",
        Date:    &time.Time{}, // or nil for current time
        Source:  "MyApp 1.0",
        Manual:  "MyApp Manual",
    }

    // Generate single man page
    doc.GenMan(cmd, header, os.Stdout)

    // Generate man pages for entire command tree
    doc.GenManTree(cmd, header, "/usr/local/share/man/man1")
}

GenManHeader

Header information for man page generation:

  • Title: Man page title (typically uppercase command name)
  • Section: Man page section (usually "1" for commands)
  • Date: Document date (uses current time if nil)
  • Source: Source attribution (defaults to "Auto generated by spf13/cobra")
  • Manual: Manual name

Man Page Functions

  • GenMan: Generate a single man page for the command
  • GenManTree: Generate man pages for command and all descendants
  • GenManTreeFromOpts: Generate man pages with additional options

Man Tree Options

type GenManTreeOptions struct {
    Header           *GenManHeader
    Path             string
    CommandSeparator string
}

Advanced options for man page generation:

opts := doc.GenManTreeOptions{
    Header: &doc.GenManHeader{
        Title:   "MYAPP",
        Section: "1",
    },
    Path:             "/usr/local/share/man/man1",
    CommandSeparator: "_", // Use underscore instead of dash in filenames
}

doc.GenManTreeFromOpts(cmd, opts)
  • Header: Man page header information
  • Path: Output directory for man pages
  • CommandSeparator: Separator for command names in filenames

Markdown Generation

func GenMarkdown(cmd *cobra.Command, w io.Writer) error
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error
func GenMarkdownTree(cmd *cobra.Command, dir string) error
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error

Generate Markdown documentation:

package main

import (
    "github.com/spf13/cobra"
    "github.com/spf13/cobra/doc"
    "os"
)

func main() {
    cmd := &cobra.Command{
        Use:   "myapp",
        Short: "My application",
    }

    // Add subcommands...

    // Generate single markdown file
    doc.GenMarkdown(cmd, os.Stdout)

    // Generate markdown tree
    doc.GenMarkdownTree(cmd, "./docs")

    // Generate with custom link handler
    doc.GenMarkdownCustom(cmd, os.Stdout, func(name string) string {
        return "https://example.com/docs/" + name + ".md"
    })

    // Generate tree with prepender and link handler
    doc.GenMarkdownTreeCustom(cmd, "./docs",
        func(filename string) string {
            return "---\ntitle: Documentation\n---\n\n"
        },
        func(name string) string {
            return "/docs/" + name + ".md"
        })
}
  • GenMarkdown: Generate markdown for a single command
  • GenMarkdownCustom: Generate markdown with custom link handler
  • GenMarkdownTree: Generate markdown files for entire command tree
  • GenMarkdownTreeCustom: Generate markdown tree with custom prepender and link handler

The linkHandler function transforms command names into documentation links.

The filePrepender function adds content at the beginning of each generated file (e.g., front matter for static site generators).

reStructuredText Generation

func GenReST(cmd *cobra.Command, w io.Writer) error
func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error
func GenReSTTree(cmd *cobra.Command, dir string) error
func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error

Generate reStructuredText documentation:

package main

import (
    "github.com/spf13/cobra"
    "github.com/spf13/cobra/doc"
    "os"
)

func main() {
    cmd := &cobra.Command{
        Use:   "myapp",
        Short: "My application",
    }

    // Add subcommands...

    // Generate single ReST file
    doc.GenReST(cmd, os.Stdout)

    // Generate ReST tree
    doc.GenReSTTree(cmd, "./docs")

    // Generate with custom link handler
    doc.GenReSTCustom(cmd, os.Stdout, func(filename, name string) string {
        return ":doc:`" + name + " <" + filename + ">`"
    })

    // Generate tree with prepender and link handler
    doc.GenReSTTreeCustom(cmd, "./docs",
        func(filename string) string {
            return ".. Documentation for " + filename + "\n\n"
        },
        func(filename, name string) string {
            return ":doc:`" + name + " <" + filename + ">`"
        })
}
  • GenReST: Generate ReST for a single command
  • GenReSTCustom: Generate ReST with custom link handler
  • GenReSTTree: Generate ReST files for entire command tree
  • GenReSTTreeCustom: Generate ReST tree with custom prepender and link handler

The linkHandler for ReST takes two parameters: filename and name.

YAML Generation

func GenYaml(cmd *cobra.Command, w io.Writer) error
func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error
func GenYamlTree(cmd *cobra.Command, dir string) error
func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error

Generate YAML documentation:

package main

import (
    "github.com/spf13/cobra"
    "github.com/spf13/cobra/doc"
    "os"
)

func main() {
    cmd := &cobra.Command{
        Use:   "myapp",
        Short: "My application",
    }

    // Add subcommands...

    // Generate single YAML file
    doc.GenYaml(cmd, os.Stdout)

    // Generate YAML tree
    doc.GenYamlTree(cmd, "./docs")

    // Generate with custom link handler
    doc.GenYamlCustom(cmd, os.Stdout, func(name string) string {
        return "docs/" + name + ".yaml"
    })

    // Generate tree with prepender and link handler
    doc.GenYamlTreeCustom(cmd, "./docs",
        func(filename string) string {
            return "# YAML documentation\n"
        },
        func(name string) string {
            return "docs/" + name + ".yaml"
        })
}
  • GenYaml: Generate YAML for a single command
  • GenYamlCustom: Generate YAML with custom link handler
  • GenYamlTree: Generate YAML files for entire command tree
  • GenYamlTreeCustom: Generate YAML tree with custom prepender and link handler

Complete Example

package main

import (
    "fmt"
    "github.com/spf13/cobra"
    "github.com/spf13/cobra/doc"
    "os"
    "time"
)

func main() {
    rootCmd := &cobra.Command{
        Use:   "myapp",
        Short: "My application",
        Long:  "A comprehensive CLI application",
    }

    serveCmd := &cobra.Command{
        Use:   "serve",
        Short: "Start the server",
    }

    fetchCmd := &cobra.Command{
        Use:   "fetch",
        Short: "Fetch resources",
    }

    rootCmd.AddCommand(serveCmd, fetchCmd)

    // Generate man pages
    manHeader := &doc.GenManHeader{
        Title:   "MYAPP",
        Section: "1",
        Date:    &time.Time{},
        Manual:  "MyApp Manual",
    }
    if err := doc.GenManTree(rootCmd, manHeader, "./man"); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    // Generate Markdown with front matter
    if err := doc.GenMarkdownTreeCustom(rootCmd, "./docs/markdown",
        func(filename string) string {
            return "---\nlayout: doc\n---\n\n"
        },
        func(name string) string {
            return "/docs/" + name + "/"
        }); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    // Generate ReST
    if err := doc.GenReSTTree(rootCmd, "./docs/rest"); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    // Generate YAML
    if err := doc.GenYamlTree(rootCmd, "./docs/yaml"); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    fmt.Println("Documentation generated successfully!")
}

Output Structure

When generating tree documentation, files are named based on the command path:

  • Root command: myapp.md
  • Subcommand: myapp_serve.md
  • Nested subcommand: myapp_serve_start.md

Commands with - in names may cause conflicts (e.g., myapp sub-third vs myapp sub third both generate myapp_sub-third.md).

DisableAutoGenTag

Control whether generated documentation includes the "Auto generated by spf13/cobra" tag:

cmd := &cobra.Command{
    Use:               "myapp",
    DisableAutoGenTag: true, // Omit auto-generated tag
}

Integration with Build Process

Integrate documentation generation into your build:

//go:build docgen
// +build docgen

package main

import (
    "github.com/spf13/cobra/doc"
    "log"
)

func main() {
    cmd := getRootCommand() // Your function

    if err := doc.GenMarkdownTree(cmd, "./docs"); err != nil {
        log.Fatal(err)
    }
}

Build with:

go run -tags docgen ./cmd/docgen

Customization Tips

  1. Front Matter: Use filePrepender to add YAML front matter for static site generators
  2. Links: Customize linkHandler to match your documentation structure
  3. Filtering: Modify command visibility with Hidden flag before generation
  4. Styling: Post-process generated files for specific formatting needs
  5. CI Integration: Generate docs in CI pipeline and commit to repository

Generated Content

Documentation includes:

  • Command description (Short and Long)
  • Usage synopsis
  • Available subcommands
  • Flags (local and inherited)
  • Examples
  • See Also (related commands)

The format varies by output type but covers the same information across all formats.