help

package
v0.0.0-...-48904eb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 14, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package help provides configurable help format renderers for the cli package.

Each renderer implements cli.HelpRenderer and can be used with cli.WithHelpRenderer:

cli.Execute(ctx, root, args, cli.WithHelpRenderer(help.Compact()))

Renderers accept options for customization:

help.Default(help.WithColor(true), help.WithSorted())

Available renderers:

  • Default — matches the built-in cli help output
  • Compact — dense, minimal whitespace
  • Tree — ASCII command hierarchy
  • Man — man page style with CAPS sections
  • JSON — machine-readable JSON
  • Markdown — Markdown format for documentation
  • Template — custom Go text/template

Custom Templates

The Template renderer allows complete control over help output using Go's text/template syntax. Templates receive a Data struct with all command metadata:

tmpl := `{{.Name}} - {{.Description}}
{{range .Flags}}- --{{.Name}}: {{.Help}}
{{end}}`
renderer, _ := help.Template(tmpl)

Use BuildData to access the structured help data programmatically.

Index

Constants

View Source
const (
	Reset      = "\033[0m"
	Bold       = "\033[1m"
	Dim        = "\033[2m"
	Italic     = "\033[3m"
	Underline  = "\033[4m"
	Cyan       = "\033[36m"
	Green      = "\033[32m"
	Yellow     = "\033[33m"
	Blue       = "\033[34m"
	Magenta    = "\033[35m"
	Red        = "\033[31m"
	White      = "\033[37m"
	BoldCyan   = "\033[1;36m"
	BoldGreen  = "\033[1;32m"
	BoldYellow = "\033[1;33m"
)

ANSI color codes.

Variables

This section is empty.

Functions

func BuildArgUsage

func BuildArgUsage(args []cli.ArgDef) string

BuildArgUsage builds the argument usage string (e.g., "<required> [optional...]").

func CommandPath

func CommandPath(chain []cli.Commander) string

CommandPath builds the full command path from a chain (e.g., "app sub1 sub2").

func Compact

func Compact(opts ...Option) cli.HelpRenderer

Compact returns a help renderer that produces dense, minimal output.

Example output:

myapp serve - Start the HTTP server
Usage: myapp serve [flags]
Commands: start, stop, status
Flags:
  -p, --port int     Port (default: 8080)
  -v, --verbose      Enable verbose output

func Default

func Default(opts ...Option) cli.HelpRenderer

Default returns a help renderer that matches the built-in cli help output. It supports optional color output, sorting, and width configuration.

func FlagLeft

func FlagLeft(f *cli.FlagDef) string

FlagLeft builds the left column for a flag (e.g., "-v, --verbose").

func FlagRight

func FlagRight(f *cli.FlagDef) string

FlagRight builds the right column for a flag (description, default, etc.).

func HasVisibleFlags

func HasVisibleFlags(flags []cli.FlagDef) bool

HasVisibleFlags returns true if any flag is not hidden.

func InterpolateHelp

func InterpolateHelp(help, def, mask, enum, env string) string

InterpolateHelp replaces ${default}, ${enum}, and ${env} placeholders in help text.

func JSON

func JSON(opts ...Option) cli.HelpRenderer

JSON returns a help renderer that produces machine-readable JSON output. This is useful for programmatic consumption, documentation generation, or integration with other tools.

func Man

func Man(opts ...Option) cli.HelpRenderer

Man returns a help renderer that produces man page style output.

Example output:

NAME
    myapp serve - Start the HTTP server

SYNOPSIS
    myapp serve [flags]

DESCRIPTION
    Extended description here.

OPTIONS
    -p, --port int
        Port to listen on. Default: 8080

func Markdown

func Markdown(opts ...Option) cli.HelpRenderer

Markdown returns a help renderer that produces Markdown format output. This is useful for generating documentation or rendering help in Markdown-aware environments.

Example output:

# myapp serve

Start the HTTP server.

## Usage

    myapp serve [flags]

## Flags

| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-p, --port` | int | 8080 | Port to listen on |

func MaxCommandWidth

func MaxCommandWidth(subs []cli.Commander) int

MaxCommandWidth calculates the maximum name width across commands.

func MaxFlagWidth

func MaxFlagWidth(flags []cli.FlagDef) int

MaxFlagWidth calculates the maximum left column width across flags.

func MustTemplate

func MustTemplate(tmplStr string, opts ...Option) cli.HelpRenderer

MustTemplate is like Template but panics if the template cannot be parsed. Use this for templates that are compile-time constants where parse errors indicate programmer error. For templates loaded at runtime, use Template and handle the error explicitly.

func MustTemplateFile

func MustTemplateFile(path string, opts ...Option) cli.HelpRenderer

MustTemplateFile is like TemplateFile but panics if the file cannot be read or the template cannot be parsed. Use this for templates that are bundled with your application where errors indicate programmer error. For user-provided template files, use TemplateFile and handle errors.

func ResolveWidth

func ResolveWidth(opts *Options) int

ResolveWidth returns the configured width or auto-detects.

func Template

func Template(tmplStr string, opts ...Option) (cli.HelpRenderer, error)

Template returns a help renderer using a Go text/template string. The template receives a Data struct as its data context.

Available template functions:

  • join: strings.Join
  • upper: strings.ToUpper
  • lower: strings.ToLower
  • title: strings.Title (deprecated but commonly expected)
  • indent: indents each line by n spaces
  • wrap: wraps text to n columns
  • default: returns fallback if value is empty
  • repeat: repeats a string n times
  • trimPrefix: strings.TrimPrefix
  • trimSuffix: strings.TrimSuffix
  • contains: strings.Contains
  • hasPrefix: strings.HasPrefix
  • hasSuffix: strings.HasSuffix
  • replace: strings.ReplaceAll

func TemplateFile

func TemplateFile(path string, opts ...Option) (cli.HelpRenderer, error)

TemplateFile returns a help renderer using a template file. The template receives a Data struct as its data context.

func Tree

func Tree(opts ...Option) cli.HelpRenderer

Tree returns a help renderer that displays command hierarchy as an ASCII tree.

Example output:

myapp
├── serve       Start the server
│   ├── --port int     Port (default: 8080)
│   └── --verbose      Enable verbose output
├── deploy      Deploy the application
│   ├── prod    Deploy to production
│   └── staging Deploy to staging
└── status      Show status

func VisibleFlags

func VisibleFlags(flags []cli.FlagDef) []cli.FlagDef

VisibleFlags filters out hidden flags.

func VisibleSubcommands

func VisibleSubcommands(subs []cli.Commander) []cli.Commander

VisibleSubcommands filters out hidden subcommands.

func Wrap

func Wrap(text string, width int) string

Wrap wraps text to the specified width.

Types

type ArgData

type ArgData struct {
	Name     string `json:"name"`
	Help     string `json:"help,omitempty"`
	Default  string `json:"default,omitempty"`
	Env      string `json:"env,omitempty"`
	Enum     string `json:"enum,omitempty"`
	Type     string `json:"type"`
	Required bool   `json:"required,omitempty"`
	IsSlice  bool   `json:"isSlice,omitempty"`
}

ArgData is the structured representation of a positional argument.

type ColorScheme

type ColorScheme struct {
	Section  string // section headers (e.g., "Usage:", "Flags:")
	Flag     string // flag names
	Command  string // command names
	Default  string // default values
	Required string // required indicators
	Env      string // environment variables
	Example  string // example commands
	Reset    string
}

ColorScheme defines colors for different help elements.

func DefaultColorScheme

func DefaultColorScheme() ColorScheme

DefaultColorScheme returns the default color scheme.

func NoColorScheme

func NoColorScheme() ColorScheme

NoColorScheme returns a scheme with no colors.

type Colorizer

type Colorizer struct {
	// contains filtered or unexported fields
}

Colorizer applies color codes to text.

func NewColorizer

func NewColorizer(opts *Options) *Colorizer

NewColorizer creates a colorizer with the given options.

func (*Colorizer) Command

func (c *Colorizer) Command(text string) string

Command colors a command name.

func (*Colorizer) Default

func (c *Colorizer) Default(text string) string

Default colors a default value.

func (*Colorizer) Dim

func (c *Colorizer) Dim(text string) string

Dim applies dim styling to text.

func (*Colorizer) Enabled

func (c *Colorizer) Enabled() bool

Enabled returns whether color output is enabled.

func (*Colorizer) Env

func (c *Colorizer) Env(text string) string

Env colors an environment variable.

func (*Colorizer) Example

func (c *Colorizer) Example(text string) string

Example colors an example command.

func (*Colorizer) Flag

func (c *Colorizer) Flag(text string) string

Flag colors a flag name.

func (*Colorizer) Required

func (c *Colorizer) Required(text string) string

Required colors a required indicator.

func (*Colorizer) Section

func (c *Colorizer) Section(text string) string

Section colors a section header.

type CommandData

type CommandData struct {
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Aliases     []string `json:"aliases,omitempty"`
	Category    string   `json:"category,omitempty"`
	Hidden      bool     `json:"hidden,omitempty"`
}

CommandData is the structured representation of a subcommand.

type CommandInfo

type CommandInfo struct {
	Name            string
	Description     string
	LongDescription string
	Aliases         []string
	Hidden          bool
	Examples        []cli.Example
	Category        string
}

CommandInfo holds resolved command metadata.

func ResolveInfo

func ResolveInfo(cmd cli.Commander) CommandInfo

ResolveInfo extracts metadata from a command via optional interfaces.

type Data

type Data struct {
	Name            string        `json:"name"`
	Description     string        `json:"description,omitempty"`
	LongDescription string        `json:"longDescription,omitempty"`
	Aliases         []string      `json:"aliases,omitempty"`
	Usage           []string      `json:"usage"`
	Commands        []CommandData `json:"commands,omitempty"`
	Flags           []FlagData    `json:"flags,omitempty"`
	Arguments       []ArgData     `json:"arguments,omitempty"`
	GlobalFlags     []FlagData    `json:"globalFlags,omitempty"`
	Examples        []ExampleData `json:"examples,omitempty"`
}

Data is the structured representation of command help. It is used by both the JSON renderer and the Template renderer.

func BuildData

func BuildData(cmd cli.Commander, chain []cli.Commander, flags []cli.FlagDef, args []cli.ArgDef, globalFlags []cli.FlagDef, sorted bool) Data

BuildData constructs a Data struct from command metadata. This is useful for custom template rendering or programmatic access.

type ExampleData

type ExampleData struct {
	Description string `json:"description,omitempty"`
	Command     string `json:"command"`
}

ExampleData is the structured representation of an example.

type FlagData

type FlagData struct {
	Name        string   `json:"name"`
	Short       string   `json:"short,omitempty"`
	Alt         []string `json:"alt,omitempty"`
	Help        string   `json:"help,omitempty"`
	Default     string   `json:"default,omitempty"`
	Env         string   `json:"env,omitempty"`
	Enum        string   `json:"enum,omitempty"`
	Type        string   `json:"type"`
	Required    bool     `json:"required,omitempty"`
	Hidden      bool     `json:"hidden,omitempty"`
	Deprecated  string   `json:"deprecated,omitempty"`
	Category    string   `json:"category,omitempty"`
	IsBool      bool     `json:"isBool,omitempty"`
	IsCounter   bool     `json:"isCounter,omitempty"`
	Negate      bool     `json:"negate,omitempty"`
	Sep         string   `json:"sep,omitempty"`
	Placeholder string   `json:"placeholder,omitempty"`
}

FlagData is the structured representation of a flag.

type GroupedCommands

type GroupedCommands struct {
	Uncategorized []cli.Commander
	Categories    []string
	ByCategory    map[string][]cli.Commander
}

GroupedCommands groups commands by category.

func GroupCommandsByCategory

func GroupCommandsByCategory(subs []cli.Commander) GroupedCommands

GroupCommandsByCategory groups commands by their Category field.

type GroupedFlags

type GroupedFlags struct {
	Uncategorized []cli.FlagDef
	Categories    []string
	ByCategory    map[string][]cli.FlagDef
}

GroupedFlags groups flags by category.

func GroupFlagsByCategory

func GroupFlagsByCategory(flags []cli.FlagDef) GroupedFlags

GroupFlagsByCategory groups flags by their Category field.

type Option

type Option func(*Options)

Option configures a help renderer.

func WithColor

func WithColor(enabled bool) Option

WithColor enables ANSI color output.

func WithColorAuto

func WithColorAuto() Option

WithColorAuto enables automatic color detection based on terminal capabilities, NO_COLOR environment variable, and TERM value.

func WithSorted

func WithSorted() Option

WithSorted sorts flags and subcommands alphabetically.

func WithWidth

func WithWidth(w int) Option

WithWidth sets the terminal width for text wrapping. A value of 0 enables auto-detection using the COLUMNS environment variable or terminal ioctl.

type Options

type Options struct {
	Width     int  // terminal width (0 = auto-detect)
	Color     bool // force color output
	ColorAuto bool // auto-detect color support
	Sorted    bool // sort flags/subcommands alphabetically
}

Options configures help renderer behavior.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL