help

package
v0.7.17 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 15 Imported by: 2

Documentation

Index

Constants

View Source
const (
	EllipsisShort = "…"
	EllipsisLong  = "..."

	ArgOpen       = "<"
	ArgClose      = ">"
	OptOpen       = "["
	OptClose      = "]"
	ArgRepeatable = EllipsisShort
	NoteOpen      = "("
	NoteClose     = ")"
)

Docopt-style argument syntax tokens.

View Source
const GlobalSection = "@global"

GlobalSection is the title-agnostic group section for flags that belong in the inherited/global options section. It resolves to the configured global title when global options are separated, or the local options title when they are merged.

Variables

This section is empty.

Functions

func BracketArg

func BracketArg(a Arg) string

BracketArg returns the arg formatted in docopt style:

required:          <name>
required+repeated: <name>…
optional:          [<name>]
optional+repeated: [<name>…]

func IsLongHelp

func IsLongHelp(args []string) bool

IsLongHelp reports whether --help appears in args (before any "--" separator). args is expected to include the program name at index 0.

Types

type Alias added in v0.7.4

type Alias struct {
	Name   string // alias subcommand name
	Target string // command invoked by the alias
}

Alias describes a subcommand that delegates to another command.

type AliasGroup added in v0.7.4

type AliasGroup []Alias

AliasGroup is a group of subcommand alias entries.

type Aliases

type Aliases []string

Aliases is a list of alias names. Each name is styled with HelpAlias, falling back to HelpCommand when HelpAlias is unset. Separators (", ") between names are left unstyled.

type AlignMode

type AlignMode int

AlignMode controls whether alignment is computed per section or globally.

const (
	AlignModeSection AlignMode = iota // Align within each section independently (default).
	AlignModeGlobal                   // Align across all sections using a shared column.
)

type Alignment

type Alignment int

Alignment controls how names are aligned against the description column.

const (
	AlignLeft  Alignment = iota // Left-align names (default).
	AlignRight                  // Right-align names against the description column.
)

type Arg

type Arg struct {
	Name         string // "query"
	Default      string // default value, rendered as " (default: X)" suffix (auto-derived from tags)
	Desc         string
	Enum         []string // known values this arg accepts (e.g. provider names); used to style matching backtick tokens in descriptions
	HideDefault  bool     // true -> suppress the (default: X) annotation even when Default is set
	Required     bool     // true -> <query>, false -> [query]
	Repeatable   bool     // true -> appends "…" suffix
	IsSubcommand bool     // true -> this arg represents a subcommand placeholder
}

Arg describes a positional argument.

func ParseArg

func ParseArg(s string) Arg

ParseArg parses a docopt-style argument token into an Arg. It handles optional brackets ([...]), angle brackets (<...>), and ellipsis (...) for repeated arguments.

type Args

type Args []Arg

Args is a group of positional argument entries.

type BacktickStyle

type BacktickStyle int

BacktickStyle controls how backticked tokens in descriptions are styled.

const (
	// BacktickStyleSmart resolves each backticked token against the help's
	// own content (positional args, subcommands, binary-prefixed command
	// paths like "mycli sub cmd") and applies the matching section's style.
	// Tokens that don't resolve fall back to [theme.Theme.HelpDescBacktick].
	// This is the default.
	BacktickStyleSmart BacktickStyle = iota

	// BacktickStylePlain skips the contextual lookup entirely. Every
	// non-flag backticked token is styled with [theme.Theme.HelpDescBacktick],
	// regardless of whether it names something elsewhere in the help.
	// Flag-like tokens (--name, -x) are still detected.
	BacktickStylePlain

	// BacktickStyleNone disables backtick handling completely. Delimiters
	// are left intact in the output and no styling is applied.
	BacktickStyleNone
)

type ClassifiedFlag

type ClassifiedFlag struct {
	Flag  Flag
	Group string // group name ("" = ungrouped); may contain "/" for sub-groups or use GlobalSection
	// AncestorDepth is 0 for flags defined on the current command, 1 for the
	// immediate parent, 2 for the grandparent, and so on. The deepest depth
	// in a given set corresponds to the root command (or the ancestor closest
	// to it, from the caller's perspective). Ungrouped flags are split into
	// one sub-group per distinct depth within the "Options" section, rendered
	// with blank-line separators.
	AncestorDepth int
}

ClassifiedFlag pairs a help.Flag with its group name and ancestor depth.

type Command

type Command struct {
	Name string
	Desc string
}

Command describes a subcommand entry.

type CommandGroup

type CommandGroup []Command

CommandGroup is a group of subcommand entries.

type Content

type Content interface {
	// contains filtered or unexported methods
}

Content is anything that can appear inside a help section.

type Description

type Description string

Description is a long-form descriptive blurb (e.g. a command's detailed help from kong's HelpProvider interface). It renders one indent step deeper than other content so it visually nests under the preceding line (typically the Usage syntax) rather than aligning flush with section content.

type Example

type Example struct {
	Comment string
	Command string
}

Example describes a help example with a comment and command.

type Examples

type Examples []Example

Examples is a group of example entries.

type Flag

type Flag struct {
	Default            string // default value for non-enum flags, rendered as " (default: X)" suffix
	Desc               string
	Enum               []string // values to render as [v1, v2, ...]
	EnumDefault        string   // default value annotation appended after enum list
	EnumHighlight      []string // highlight substrings (parallel to Enum, used with EnumStyleHighlightPrefix)
	HideDefault        bool     // true -> suppress the (default: X) annotation even when Default is set
	Long               string   // "repo" -> rendered as --repo
	NoIndent           bool     // true -> suppress short-flag alignment indent for long-only flags
	Placeholder        string   // "repo" -> rendered as <repo>
	PlaceholderLiteral bool     // true -> renders placeholder without <...>
	Repeatable         bool     // true -> renders <placeholder>,…
	Short              string   // "R" -> rendered as -R
}

Flag describes a single flag entry. Short and Long should not include dashes - the renderer adds them. Placeholder is rendered as <placeholder> (angle brackets added by renderer). Set PlaceholderLiteral to true to render the placeholder as-is without <...>.

type FlagGroup

type FlagGroup []Flag

FlagGroup is a group of flag entries (blank line separates adjacent groups).

type FlagRefs added in v0.7.16

type FlagRefs []Flag

FlagRefs is non-rendering flag metadata used to resolve backticked flag references in descriptions when the corresponding flag group is intentionally omitted from visible help.

type FlagSectionsOption

type FlagSectionsOption func(*flagSectionsConfig)

FlagSectionsOption configures BuildFlagSections behavior.

func WithGlobalOptionsTitle added in v0.6.12

func WithGlobalOptionsTitle(title string) FlagSectionsOption

WithGlobalOptionsTitle separates inherited flags into their own section (like WithSeparateGlobalOptions) under a custom title instead of the default "Global Options".

func WithKeepGroupOrder

func WithKeepGroupOrder() FlagSectionsOption

WithKeepGroupOrder preserves first-seen order of groups instead of sorting them alphabetically. Use this when the caller controls insertion order and wants it preserved in the output.

func WithOptionsTitle added in v0.6.12

func WithOptionsTitle(title string) FlagSectionsOption

WithOptionsTitle sets the section title for local and merged flags instead of the default "Options".

func WithSeparateGlobalOptions

func WithSeparateGlobalOptions() FlagSectionsOption

WithSeparateGlobalOptions emits inherited flags under a dedicated "Global Options" section instead of the default behavior, which merges them into the "Options" section as a blank-line-separated sub-group.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option transforms help sections (composable post-processor). Use OptionFunc to create an Option from a plain function.

func WithAlwaysShowDescription added in v0.6.4

func WithAlwaysShowDescription() Option

WithAlwaysShowDescription disables the default WithDescriptionOnLongHelp behavior, making the description blurb visible on both -h and --help.

func WithAlwaysShowExamples

func WithAlwaysShowExamples() Option

WithAlwaysShowExamples disables the default WithExamplesOnLongHelp behavior, making examples visible on both -h and --help.

func WithDescriptionOnLongHelp added in v0.6.4

func WithDescriptionOnLongHelp(args []string) Option

WithDescriptionOnLongHelp hides Description content blocks on short help (-h) and keeps them on long help (--help). A description blurb (a command's Help()/Long/Description detail) is nested inside a section (typically Usage) rather than being a section of its own, so this strips the Description items in place. Sections left with no content are dropped.

func WithExamplesOnLongHelp

func WithExamplesOnLongHelp(args []string) Option

WithExamplesOnLongHelp hides the Examples section on short help (-h) and moves it to the end on long help (--help), ensuring it is always last regardless of option ordering.

func WithFlagDefault

func WithFlagDefault(flagLong, value string) Option

WithFlagDefault appends a "[default: value]" suffix to the description of the flag with the given Long name. No-op if value is empty or the flag is not found.

func WithHelpFlagSection

func WithHelpFlagSection(sectionTitle string) Option

WithHelpFlagSection moves existing help flags into the named section. It preserves their current rendering shape, whether combined or already split into separate -h and --help entries. If the section does not exist, it is created.

func WithHelpFlags

func WithHelpFlags(shortDesc, longDesc string) Option

WithHelpFlags replaces any combined help flag (Long=="help") with separate -h and --help entries. Appends as a new FlagGroup to the last section containing flag content. Removes empty FlagGroups/sections left behind.

func WithHelpFlagsInSection

func WithHelpFlagsInSection(sectionTitle, shortDesc, longDesc string) Option

WithHelpFlagsInSection replaces any combined help flag (Long=="help") with separate -h and --help entries, then appends them to the named section. When sectionTitle is empty, it uses the last section containing flag content and falls back to "Options" if no flag sections exist.

func WithLongHelp

func WithLongHelp(args []string, sections ...Section) Option

WithLongHelp appends sections only when args include --help (not -h).

func WithRenamedSection

func WithRenamedSection(from, to string) Option

WithRenamedSection renames any section whose title exactly matches from.

func WithoutSection

func WithoutSection(title string) Option

WithoutSection removes any section whose title exactly matches title.

type OptionFunc

type OptionFunc func([]Section) []Section

OptionFunc is a function that implements Option.

type Policy

type Policy struct {
	// AlwaysShowExamples disables the default [WithExamplesOnLongHelp] behavior,
	// making examples visible on both -h and --help.
	AlwaysShowExamples bool
	// AlwaysShowDescription disables the default [WithDescriptionOnLongHelp]
	// behavior, making the description blurb visible on both -h and --help.
	AlwaysShowDescription bool
}

Policy holds framework-level help configuration resolved from options.

func ResolvePolicy

func ResolvePolicy(opts ...Option) Policy

ResolvePolicy walks opts and builds a Policy from any options that implement the internal behaviorOption interface.

type Renderer

type Renderer struct {
	Theme *theme.Theme
	// contains filtered or unexported fields
}

Renderer renders styled help output.

func NewRenderer

func NewRenderer(th *theme.Theme, opts ...RendererOption) *Renderer

NewRenderer creates a Renderer.

func (*Renderer) Render

func (r *Renderer) Render(w io.Writer, sections []Section) error

Render writes help sections to w.

type RendererOption

type RendererOption func(*Renderer)

RendererOption configures a Renderer.

func WithArgumentPadding

func WithArgumentPadding(n int) RendererOption

WithArgumentPadding sets the padding (in spaces) between an argument and its description. Default is 2.

func WithBacktickStyle

func WithBacktickStyle(s BacktickStyle) RendererOption

WithBacktickStyle sets how backticked tokens in descriptions are styled. See BacktickStyle for the supported modes. The default is BacktickStyleSmart.

func WithCommandAlign

func WithCommandAlign(a Alignment) RendererOption

WithCommandAlign sets the alignment of command names in the Commands section.

func WithCommandAlignMode

func WithCommandAlignMode(m AlignMode) RendererOption

WithCommandAlignMode sets whether command names are aligned per section (default) or globally across all command sections.

func WithCommandPadding

func WithCommandPadding(n int) RendererOption

WithCommandPadding sets the padding (in spaces) between a command and its description. Default is 1.

func WithDescriptionIndent

func WithDescriptionIndent(n int) RendererOption

WithDescriptionIndent sets the extra indent (in columns) applied to Description content beyond the section's normal content indent. The default is 2, which nests a description visually under the preceding content (e.g. a Usage line) rather than aligning flush with it. Pass 0 to align descriptions with regular section content.

func WithDescriptionWidth

func WithDescriptionWidth(n int) RendererOption

WithDescriptionWidth sets a fixed wrap width for Description content (e.g. the long-form help surfaced by kong's HelpProvider interface). It overrides the default flexible WithDescriptionWidthRange, pinning descriptions to exactly n columns. Pass 0 to disable wrapping for descriptions specifically while keeping flag/arg wrapping intact.

func WithDescriptionWidthRange

func WithDescriptionWidthRange(minWidth, maxWidth int) RendererOption

WithDescriptionWidthRange sets a flexible wrap width for Description content. Instead of wrapping strictly at one column, the renderer tries every width from minWidth to maxWidth and keeps the one whose wrapped lines form the most even right edge - so a short word never pokes out past an otherwise clean margin just to satisfy an exact width. If multiple widths are equally good, the lower width wins. One width is chosen per Description block, so all its paragraphs share the same right edge. The upper bound is capped at WithMaxWidth when that is set.

A range of 70-100 is the default; call this to widen or narrow it, or call WithDescriptionWidth to pin descriptions to one fixed column instead.

func WithFlagAlign

func WithFlagAlign(a Alignment) RendererOption

WithFlagAlign sets the alignment of flag names in flag sections.

func WithFlagPadding

func WithFlagPadding(n int) RendererOption

WithFlagPadding sets the padding (in spaces) between a flag and its description. Default is 2.

func WithHideDefaults

func WithHideDefaults() RendererOption

WithHideDefaults suppresses the " (default: X)" annotation that the renderer would otherwise append to non-enum flag descriptions for any flag whose Flag.Default is set. Per-flag Flag.HideDefault is unaffected and always wins. Useful when the caller would rather surface defaults in their own description text, or in a separate footer.

func WithListIndent added in v0.6.0

func WithListIndent(n int) RendererOption

WithListIndent sets the leading indent (in columns) applied to list items auto-detected in Description content, relative to the description's base indent. Both unordered ("-", "*", "+") and ordered ("1.", "2)") markers are re-indented to this width regardless of how many spaces the author wrote, so list indentation stays uniform. The default is 2.

func WithMaxWidth

func WithMaxWidth(n int) RendererOption

WithMaxWidth sets the maximum output width. Descriptions that exceed this width are word-wrapped, with continuation lines indented according to the configured WrapStyle. A value of 0 disables wrapping; by default the renderer auto-detects width from the output writer when possible.

func WithWrapStyle

func WithWrapStyle(s WrapStyle) RendererOption

WithWrapStyle sets how wrapped description continuation lines are indented. The default is WrapBracketAlign, which aligns continuation lines to the content after an unclosed '[' on the first line (e.g. for enum value lists). Use WrapBracketBelow to break before the bracket, or WrapFlush for uniform indentation to the description column.

type Section

type Section struct {
	Title   string
	Content []Content
}

Section is a named section containing content blocks.

func Apply

func Apply(sections []Section, opts ...Option) []Section

Apply applies options to sections in order.

func BuildFlagSections

func BuildFlagSections(flags []ClassifiedFlag, opts ...FlagSectionsOption) []Section

BuildFlagSections assembles flag help sections from pre-classified flags.

By default, inherited flags are merged into the "Options" section as a blank-line-separated sub-group. Pass WithSeparateGlobalOptions() to emit them under a dedicated "Global Options" section instead.

When no flag carries a group name, a single flat "Options" section is produced (containing local flags and, appended as a sub-group, inherited flags). Under WithSeparateGlobalOptions(), "Options" and "Global Options" are emitted as separate sections, each omitted if empty.

When any flag has a group, flags are organized into one section per group (sorted alphabetically by default). Ungrouped local and inherited flags share the trailing "Options" section as sub-groups; pass WithSeparateGlobalOptions() to split inherited flags into "Global Options". Pass WithKeepGroupOrder() to preserve first-seen order instead of sorting.

Compound group names ("Section/SubGroup") split flags within the same section into separate FlagGroup content entries (rendered with a blank-line separator). Sub-groups appear in first-seen order within each section. The case-insensitive GlobalSection sentinel resolves to the configured global section title, or the local options title when global options are merged.

func MoveHelpFlagsToSection

func MoveHelpFlagsToSection(sections []Section, sectionTitle string) []Section

MoveHelpFlagsToSection moves existing help flags into sectionTitle. It preserves whether the help flags are combined or already split. When sectionTitle is empty, help flags are appended to the last section containing flag content and fall back to "Options" if no flag sections exist. Empty FlagGroups and sections are cleaned up.

func SplitHelpFlags

func SplitHelpFlags(sections []Section, shortDesc, longDesc string) []Section

SplitHelpFlags removes any Flag with Long=="help" from all sections, then appends separate -h and --help entries as a new FlagGroup to the last section containing flag content. Empty FlagGroups and sections are cleaned up.

func SplitHelpFlagsInSection

func SplitHelpFlagsInSection(
	sections []Section,
	sectionTitle, shortDesc, longDesc string,
) []Section

SplitHelpFlagsInSection removes any Flag with Long=="help" from all sections, then appends separate -h and --help entries as a new FlagGroup to sectionTitle. When sectionTitle is empty, the help group is appended to the last section containing flag content and falls back to "Options" if no flag sections exist. Empty FlagGroups and sections are cleaned up.

type Text

type Text string

Text is freeform text. Inline backticked tokens are highlighted like description backticks.

type Usage

type Usage struct {
	Command     string // "mycli" -> styled as HelpCommand
	ShowOptions bool   // true -> renders [options] in HelpFlag style
	Args        []Arg  // positional args with bracket style
	Raw         string // when set, rendered verbatim after Command (disables Args/ShowOptions)
}

Usage is an auto-styled usage line.

When Raw is non-empty, it is appended verbatim after the styled Command and the structured Args/ShowOptions fields are ignored. Use Raw to pass through a pre-formatted usage string (for example, cobra's cmd.Use) when its shape does not match clib's arg grammar.

type WrapStyle

type WrapStyle int

WrapStyle controls how wrapped description continuation lines are indented.

const (
	// WrapBracketAlign indents continuation lines to the content after an
	// unclosed '[' on the first line, keeping bracketed lists (like enum
	// values) visually cohesive. Falls back to WrapFlush when no unclosed
	// bracket is present.
	WrapBracketAlign WrapStyle = iota

	// WrapBracketBelow breaks before a trailing '[...]', placing the bracket
	// content on a new line at the description column. Continuation lines
	// within the bracket are indented one column further to align with the
	// content after '['. Falls back to WrapFlush when no trailing bracket
	// is present.
	WrapBracketBelow

	// WrapFlush indents all continuation lines to the description column.
	WrapFlush
)

Jump to

Keyboard shortcuts

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