cobra

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: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Preflight = complete.Preflight

Preflight scans os.Args for completion flags, allowing completion to be handled before the CLI parser. This is useful for subcommand-based CLIs where the parser requires a subcommand but completion flags are standalone.

Returns a populated CompletionFlags, any positional args found after "--", and true if a completion flag was found. When ok is false, the caller should proceed with normal CLI parsing.

Functions

func CompletionCommand

func CompletionCommand(
	parent *cobralib.Command,
	genFunc func() *complete.Generator,
) *cobralib.Command

CompletionCommand returns a cobra subcommand that replaces cobra's built-in "completion" command with one powered by clib. It disables cobra's default completion subcommand on parent and generates scripts via complete.Generator.

The genFunc is called at run time to build the generator, so the full command tree is available.

Usage:

cmd.AddCommand(clib.CompletionCommand(cmd, func() *complete.Generator {
    gen := complete.NewGenerator("myapp").FromFlags(clib.FlagMeta(cmd))
    gen.Subs = clib.Subcommands(cmd)
    return gen
}))

func Extend

func Extend(flag *pflag.Flag, extra FlagExtra)

Extend attaches clib metadata to a pflag.Flag.

cobracli.Extend(f.Lookup("repo"), cobracli.FlagExtra{
	Group:       "Filters",
	Placeholder: "repo",
	Complete:    "predictor=repo",
})

func ExtendCommand added in v0.7.4

func ExtendCommand(cmd *cobralib.Command, extra CommandExtra)

ExtendCommand attaches clib metadata to a cobra command.

func FlagMeta

func FlagMeta(cmd *cobralib.Command) []complete.FlagMeta

FlagMeta extracts completion metadata from a cobra command's flags. It reads pflag properties and clib extras from all flags on the command.

func HelpFunc

func HelpFunc(
	r *help.Renderer,
	sections func(cmd *cobralib.Command) []help.Section,
	opts ...help.Option,
) func(*cobralib.Command, []string)

HelpFunc returns a cobra-compatible help function that renders themed help. The sections callback receives the command and returns sections to render. By default, the description blurb and examples are hidden on -h and shown on --help (examples last); pass help.WithAlwaysShowDescription and/or help.WithAlwaysShowExamples to disable this.

func Sections

func Sections(cmd *cobralib.Command) []help.Section

Sections builds standard help sections from a cobra command. Extracts: Usage, Aliases, Examples, grouped Subcommands, Flags, Inherited Flags.

When any flag carries a clib "group" extra, flags are organized into one section per group (alphabetical), with ungrouped local flags under "Flags" and ungrouped inherited flags under "Inherited Flags".

func SectionsWithOptions

func SectionsWithOptions(opts ...SectionsOption) func(*cobralib.Command) []help.Section

SectionsWithOptions builds standard help sections from a cobra command using configurable flag-section behavior.

func Subcommands

func Subcommands(cmd *cobralib.Command) []complete.SubSpec

Subcommands extracts subcommand completion specs from a cobra command tree. Each visible subcommand produces a SubSpec with its local flags (excluding the built-in --help flag).

Types

type CSVFlag

type CSVFlag struct {
	Values []string
}

CSVFlag implements pflag.Value for comma-separated values.

func (*CSVFlag) Set

func (c *CSVFlag) Set(val string) error

Set appends comma-separated values, filtering empty entries.

func (*CSVFlag) String

func (c *CSVFlag) String() string

String returns the comma-separated string representation.

func (*CSVFlag) Type

func (c *CSVFlag) Type() string

Type returns the pflag type name.

type CommandExtra added in v0.7.4

type CommandExtra struct {
	Alias string `json:"alias"` // command invoked by this alias command
}

CommandExtra holds clib-specific metadata for a cobra command.

type Completion

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

Completion manages hidden completion flags on a cobra command.

func NewCompletion

func NewCompletion(cmd *cobralib.Command) *Completion

NewCompletion adds hidden persistent flags to cmd and returns a Completion. Flags added: --@complete, --@shell, --install-completion, --uninstall-completion, --print-completion. It also hides cobra's built-in "completion" subcommand.

func (*Completion) Handle

func (c *Completion) Handle(
	gen *complete.Generator,
	handler complete.Handler,
	opts ...Option,
) (bool, error)

Handle checks whether a completion action was requested and executes it. Returns true if a completion action was handled (caller should exit). The handler callback is invoked for --@complete=<type> requests; it receives the completion type and resolved shell name.

type CompletionFlags

type CompletionFlags = complete.CompletionFlags

CompletionFlags is an alias for complete.CompletionFlags. See Preflight for pre-parse usage.

type FlagExtra

type FlagExtra struct {
	Aliases        []string       `json:"aliases"`        // additional long-flag aliases
	Complete       string         `json:"complete"`       // completion directive (e.g. "predictor=repo")
	CompleteHidden bool           `json:"completeHidden"` // still offer this flag in completions even when hidden from help
	Enum           []string       `json:"enum"`           // enum values
	EnumDefault    string         `json:"enumDefault"`    // default enum value (highlighted by EnumStyleHighlightDefault)
	EnumHighlight  []string       `json:"enumHighlight"`  // highlight hints for enum values
	EnumTerse      []string       `json:"enumTerse"`      // short descriptions for enum values (parallel to Enum)
	Extension      string         `json:"extension"`      // file extension filter for completion (e.g. "yaml" or "yaml,yml")
	Group          string         `json:"group"`          // help section group
	HideLong       bool           `json:"hideLong"`       // hide the long flag from help output
	HideShort      bool           `json:"hideShort"`      // hide the short flag from help output
	Hint           string         `json:"hint"`           // value type hint for completion (file, dir, command, user, host, url, email)
	NoIndent       bool           `json:"noIndent"`       // suppress short-flag alignment indent in help
	Negatable      bool           `json:"negatable"`      // supports --no- prefix
	NegativeDesc   string         `json:"negativeDesc"`   // description for --no- variant (negatable flags)
	NegativeOnly   bool           `json:"negativeOnly"`   // advertise only the --no- variant in help (negatable flags)
	Order          complete.Order `json:"order"`          // completion ordering mode
	Placeholder    string         `json:"placeholder"`    // value placeholder (e.g. "repo")
	PositiveDesc   string         `json:"positiveDesc"`   // description for positive variant (negatable flags)
	PositiveOnly   bool           `json:"positiveOnly"`   // advertise only the positive variant in help (negatable flags)
	Terse          string         `json:"terse"`          // very short description for completions
}

FlagExtra holds clib-specific metadata for a pflag.Flag.

type Option

type Option func(*config)

Option configures Handle behavior.

func WithArgs

func WithArgs(args []string) Option

WithArgs passes preceding positional args to the completion handler.

func WithQuiet

func WithQuiet(quiet bool) Option

WithQuiet suppresses output during install/uninstall.

type SectionsOption

type SectionsOption func(*sectionsConfig)

SectionsOption configures cobra help-section generation.

func WithGlobalOptionsTitle added in v0.6.12

func WithGlobalOptionsTitle(title string) SectionsOption

WithGlobalOptionsTitle separates inherited flags under the given section title instead of the default merged-options layout.

func WithHideCommandAliases added in v0.7.6

func WithHideCommandAliases() SectionsOption

WithHideCommandAliases omits command aliases from help output.

func WithHideInheritedFlags

func WithHideInheritedFlags() SectionsOption

WithHideInheritedFlags omits inherited/global flags from help output.

func WithHideInheritedFlagsOnSubcommands

func WithHideInheritedFlagsOnSubcommands() SectionsOption

WithHideInheritedFlagsOnSubcommands omits inherited/global flags from subcommand help output while leaving root-command help unchanged. This is the default.

func WithInlineCommandAliases added in v0.7.6

func WithInlineCommandAliases() SectionsOption

WithInlineCommandAliases keeps alias commands in the Commands section instead of placing them in a separate Aliases section.

func WithKeepGroupOrder

func WithKeepGroupOrder() SectionsOption

WithKeepGroupOrder preserves first-seen order of grouped flag sections instead of sorting them alphabetically. This is the default.

func WithOptionsTitle added in v0.6.12

func WithOptionsTitle(title string) SectionsOption

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

func WithPreservePlaceholders

func WithPreservePlaceholders() SectionsOption

WithPreservePlaceholders keeps placeholders exactly as provided by clib metadata or pflag usage annotations. By default, explicit Cobra flag placeholders are lowercased for consistency with clib's help style.

func WithRawUsage

func WithRawUsage() SectionsOption

WithRawUsage passes cmd.Use through to the usage line verbatim instead of parsing it into structured Args. Use this for cobra commands whose Use: strings contain shell metacharacters (pipes, parens, ellipses) that clib's arg grammar would otherwise mangle.

func WithShowInheritedFlagsOnSubcommands

func WithShowInheritedFlagsOnSubcommands() SectionsOption

WithShowInheritedFlagsOnSubcommands keeps inherited/global flags visible in subcommand help output.

func WithSortedGroupOrder

func WithSortedGroupOrder() SectionsOption

WithSortedGroupOrder sorts grouped flag sections alphabetically.

func WithSubcommandOptional

func WithSubcommandOptional() SectionsOption

WithSubcommandOptional marks the auto-appended subcommand placeholder as optional ([<command>] instead of <command>). Use this when the root command is genuinely runnable without a subcommand.

Jump to

Keyboard shortcuts

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