Documentation
¶
Overview ¶
Package cli provides a cobra-infused CLI starter kit with custom help rendering inspired by Rust's clap. It also provides type-safe enum flag support via Enum with optional help text for each value.
Shell completion is powered by carapace, providing enhanced completions for 11 shells beyond Cobra's standard offering. Use Completer types like Files, Directories, and Values to define completions declaratively.
Index ¶
- func BindEnv(flag *pflag.Flag, envVar string)
- func Execute(cmd *cobra.Command, opts ...Option) error
- func FlagGroup(cmd *cobra.Command, group string, flags ...string)
- func GetEnvVar(flag *pflag.Flag) string
- type Completer
- type CompletionOption
- func CompleteFlag(flag string, completer Completer) CompletionOption
- func CompletePositional(position int, completer Completer) CompletionOption
- func CompletePositionalAny(completer Completer) CompletionOption
- func CompleteSubcommand(name string, opts ...CompletionOption) CompletionOption
- func WithExtraShells(shells ...Shell) CompletionOption
- func WithShells(shells ...Shell) CompletionOption
- type EnumHelper
- type EnumOption
- type EnumValue
- func (e *EnumValue[T]) BaseType() string
- func (e *EnumValue[T]) Get() T
- func (e *EnumValue[T]) HasHelp() bool
- func (e *EnumValue[T]) HelpEntries() []EnumOption
- func (e *EnumValue[T]) Set(s string) error
- func (e *EnumValue[T]) String() string
- func (e *EnumValue[T]) Type() string
- func (e *EnumValue[T]) WithHelp(help ...string) *EnumValue[T]
- type Enumerable
- type Option
- func WithCompletionCommand(opts ...CompletionOption) Option
- func WithContext(ctx context.Context) Option
- func WithStderr(w io.Writer) Option
- func WithStdout(w io.Writer) Option
- func WithTheme(t Theme) Option
- func WithVersionCommand(info VersionInfo) Option
- func WithVersionFlag(info VersionInfo) Option
- func WithWidth(w int) Option
- func WithoutManpage() Option
- type Shell
- type Theme
- type VersionInfo
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindEnv ¶ added in v0.5.0
BindEnv associates an environment variable with a flag. If the environment variable is set and the flag has not been explicitly provided, the environment variable value is used as the flag's value during command execution.
Precedence (highest to lowest):
- Explicit flag value on command line
- Environment variable
- Flag default value
If flag is nil, BindEnv silently returns without effect (no-op).
cmd.Flags().StringVarP(&key, "key", "k", "", "GPG private key")
cli.BindEnv(cmd.Flags().Lookup("key"), "GPG_PRIVATE_KEY")
func Execute ¶
Execute runs the provided cobra command with custom help rendering and sensible defaults. Options can be provided to customise behavior.
Basic usage:
root := &cobra.Command{
Use: "myapp",
Short: "A brief description",
Long: `
A longer description that spans multiple lines.
Indentation is automatically removed.
`,
}
if err := cli.Execute(root); err != nil {
os.Exit(1)
}
Functional options allow customisation:
cli.Execute(root,
cli.WithContext(ctx),
cli.WithStdout(os.Stdout),
cli.WithStderr(os.Stderr),
)
func FlagGroup ¶ added in v0.4.0
FlagGroup assigns flags to a named group for organized help output. Grouped flags are rendered under their group header instead of the default FLAGS section. Groups appear in the order they are defined.
cli.FlagGroup(cmd, "Authentication", "token", "api-key") cli.FlagGroup(cmd, "Output Options", "format", "output")
Types ¶
type Completer ¶ added in v0.6.0
type Completer interface {
// contains filtered or unexported methods
}
Completer defines a completion source that can be converted to a carapace Action.
func ActionFunc ¶ added in v0.6.0
ActionFunc returns a Completer from a function that produces a carapace.Action. This is the escape hatch for advanced carapace usage.
cli.CompleteFlag("branch", cli.ActionFunc(func() carapace.Action {
return carapace.ActionExecCommand("git", "branch", "--format=%(refname:short)")(
func(output []byte) carapace.Action {
branches := strings.Split(strings.TrimSpace(string(output)), "\n")
return carapace.ActionValues(branches...)
},
)
}))
func Directories ¶ added in v0.6.0
func Directories() Completer
Directories returns a Completer for directory paths.
cli.CompletePositional(0, cli.Directories())
func Executables ¶ added in v0.6.0
func Executables() Completer
Executables returns a Completer for executable names from PATH.
cli.CompleteFlag("editor", cli.Executables())
func Files ¶ added in v0.6.0
Files returns a Completer for file paths, optionally filtered by extension.
cli.CompleteFlag("config", cli.Files(".yaml", ".yml", ".json"))
func None ¶ added in v0.6.0
func None() Completer
None returns a Completer that disables file completion fallback.
cli.CompleteFlag("password", cli.None())
func Values ¶ added in v0.6.0
Values returns a Completer for a fixed list of values.
cli.CompleteFlag("format", cli.Values("json", "text", "yaml"))
func ValuesDescribed ¶ added in v0.6.0
ValuesDescribed returns a Completer for values with descriptions. Arguments are provided as pairs: value1, description1, value2, description2, ...
cli.CompleteFlag("format", cli.ValuesDescribed(
"json", "JSON format",
"yaml", "YAML format",
))
type CompletionOption ¶ added in v0.6.0
type CompletionOption func(*completionOptions)
CompletionOption configures shell completion behavior.
func CompleteFlag ¶ added in v0.6.0
func CompleteFlag(flag string, completer Completer) CompletionOption
CompleteFlag defines completion for a flag.
cli.WithCompletionCommand(
cli.CompleteFlag("config", cli.Files(".yaml", ".json")),
cli.CompleteFlag("format", cli.Values("json", "text")),
)
func CompletePositional ¶ added in v0.6.0
func CompletePositional(position int, completer Completer) CompletionOption
CompletePositional defines completion for a positional argument (0-indexed).
cli.WithCompletionCommand(
cli.CompletePositional(0, cli.Directories()),
)
func CompletePositionalAny ¶ added in v0.6.0
func CompletePositionalAny(completer Completer) CompletionOption
CompletePositionalAny defines completion for remaining positional arguments.
cli.WithCompletionCommand(
cli.CompletePositionalAny(cli.Files()),
)
func CompleteSubcommand ¶ added in v0.6.0
func CompleteSubcommand(name string, opts ...CompletionOption) CompletionOption
CompleteSubcommand defines completions for a specific subcommand.
cli.WithCompletionCommand(
cli.CompleteSubcommand("deploy",
cli.CompleteFlag("environment", cli.Values("dev", "staging", "prod")),
cli.CompletePositional(0, cli.Directories()),
),
)
func WithExtraShells ¶ added in v0.6.0
func WithExtraShells(shells ...Shell) CompletionOption
WithExtraShells adds shells to the default set (bash, zsh, fish).
cli.WithCompletionCommand(
cli.WithExtraShells(cli.ShellPowerShell, cli.ShellNushell),
)
func WithShells ¶ added in v0.6.0
func WithShells(shells ...Shell) CompletionOption
WithShells sets the supported shells, replacing the defaults. The help output and completion command will only show these shells.
cli.WithCompletionCommand(
cli.WithShells(cli.ShellBash, cli.ShellZsh, cli.ShellPowerShell),
)
type EnumHelper ¶ added in v0.4.0
type EnumHelper interface {
HasHelp() bool
HelpEntries() []EnumOption
BaseType() string
}
EnumHelper is implemented by enum values that have help text for their options.
type EnumOption ¶ added in v0.4.0
EnumOption represents an enum value with an optional help description.
type EnumValue ¶ added in v0.4.0
type EnumValue[T Enumerable] struct { // contains filtered or unexported fields }
EnumValue implements pflag.Value for type-safe enumeration flags.
func Enum ¶ added in v0.4.0
func Enum[T Enumerable](def T, allowed ...T) *EnumValue[T]
Enum creates a new type-safe enum flag. The first argument is the default value, followed by all allowed values. For string-based enums, the string value is used as the display name. For integer-based enums, the numeric value is used as the display name.
String enum example:
type Format string
const (
FormatJSON Format = "json"
FormatYAML Format = "yaml"
FormatTOML Format = "toml"
)
format := cli.Enum(FormatJSON, FormatJSON, FormatYAML, FormatTOML)
cmd.Flags().VarP(format, "format", "f", "output format")
Integer enum example:
type TrustLevel int
const (
TrustUnknown TrustLevel = iota + 1 // 1
TrustNever // 2
TrustMarginal // 3
)
trust := cli.Enum(TrustUnknown, TrustUnknown, TrustNever, TrustMarginal)
cmd.Flags().Var(trust, "trust-level", "GPG trust level")
func (*EnumValue[T]) BaseType ¶ added in v0.4.0
BaseType returns the underlying type name ("string" or "int").
func (*EnumValue[T]) Get ¶ added in v0.4.0
func (e *EnumValue[T]) Get() T
Get returns the current typed enum value.
func (*EnumValue[T]) HasHelp ¶ added in v0.4.0
HasHelp returns true if this enum has help text for its values.
func (*EnumValue[T]) HelpEntries ¶ added in v0.4.0
func (e *EnumValue[T]) HelpEntries() []EnumOption
HelpEntries returns the enum values with their help text in display order.
func (*EnumValue[T]) String ¶ added in v0.4.0
String returns the string representation of the current value.
func (*EnumValue[T]) Type ¶ added in v0.4.0
Type returns the type name for help output, showing all allowed values.
func (*EnumValue[T]) WithHelp ¶ added in v0.4.0
WithHelp adds help text for each enum value in order. The help strings correspond to the enum values in the order they were defined.
format := cli.Enum(FormatJSON, FormatJSON, FormatYAML, FormatTOML).
WithHelp(
"JavaScript Object Notation",
"YAML Ain't Markup Language",
"Tom's Obvious Minimal Language",
)
type Enumerable ¶ added in v0.4.0
type Enumerable interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~string
}
Enumerable defines the constraint for enum types.
type Option ¶
type Option func(*options)
Option is a functional option for configuring the CLI.
func WithCompletionCommand ¶ added in v0.6.0
func WithCompletionCommand(opts ...CompletionOption) Option
WithCompletionCommand adds a "completion" subcommand that generates shell completion scripts. By default, it supports bash, zsh, and fish shells.
Basic usage:
cli.Execute(root, cli.WithCompletionCommand())
With custom completions:
cli.Execute(root,
cli.WithCompletionCommand(
cli.CompleteFlag("config", cli.Files(".yaml", ".json")),
cli.CompleteFlag("format", cli.Values("json", "text")),
),
)
With additional shells:
cli.Execute(root,
cli.WithCompletionCommand(
cli.WithExtraShells(cli.ShellPowerShell, cli.ShellNushell),
),
)
func WithContext ¶
WithContext sets the context for the CLI, enabling cancellation and passing request-scoped values.
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() cli.Execute(root, cli.WithContext(ctx))
func WithStderr ¶
WithStderr sets the standard error writer for the CLI.
var buf strings.Builder cli.Execute(root, cli.WithStderr(&buf)) fmt.Print(buf.String())
func WithStdout ¶
WithStdout sets the standard output writer for the CLI.
var buf strings.Builder cli.Execute(root, cli.WithStdout(&buf)) fmt.Print(buf.String())
func WithTheme ¶ added in v0.2.0
WithTheme sets the theme for styling the CLI help output.
theme := cli.DefaultTheme()
theme.Header = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("141"))
cli.Execute(root, cli.WithTheme(theme))
func WithVersionCommand ¶ added in v0.5.0
func WithVersionCommand(info VersionInfo) Option
WithVersionCommand adds a "version" subcommand to the root command that displays build information. The subcommand supports additional flags for different output formats.
Flags:
--short: Display only the version number
--json: Display version information as JSON
cli.Execute(root, cli.WithVersionCommand(cli.VersionInfo{ Version: "0.5.0", GitCommit: "abc1234", GitBranch: "main", BuildDate: "2024-01-15T10:30:00Z", GoVersion: runtime.Version(), }), )
func WithVersionFlag ¶ added in v0.5.0
func WithVersionFlag(info VersionInfo) Option
WithVersionFlag adds a --version / -V flag to the root command that displays build information. The output is styled according to the configured theme.
cli.Execute(root,
cli.WithVersionFlag(cli.VersionInfo{
Version: "0.5.0",
GitCommit: "abc1234",
GitBranch: "main",
BuildDate: "2024-01-15T10:30:00Z",
GoVersion: runtime.Version(),
}),
)
func WithWidth ¶ added in v0.3.0
WithWidth sets the maximum width for word wrapping CLI help output. Text will wrap at word boundaries to fit within the specified width. The default width is 80 characters. Set to 0 to disable wrapping.
cli.Execute(root, cli.WithWidth(100))
func WithoutManpage ¶ added in v0.4.0
func WithoutManpage() Option
WithoutManpage disables the hidden "man" command that generates a manpage. By default, a hidden "man" command is available that outputs a roff-formatted manpage which can be installed by piping to a file in your manpath.
type Shell ¶ added in v0.6.0
type Shell string
Shell represents a supported shell for completion.
const ( // ShellBash represents the Bourne Again Shell. ShellBash Shell = "bash" // ShellZsh represents the Z Shell. ShellZsh Shell = "zsh" // ShellFish represents the Friendly Interactive Shell. ShellFish Shell = "fish" // ShellPowerShell represents PowerShell. ShellPowerShell Shell = "powershell" // ShellElvish represents the Elvish shell. ShellElvish Shell = "elvish" // ShellNushell represents Nushell. ShellNushell Shell = "nushell" // ShellIon represents the Ion shell. ShellIon Shell = "ion" // ShellOil represents the Oil shell. ShellOil Shell = "oil" // ShellTcsh represents the TENEX C Shell. ShellTcsh Shell = "tcsh" // ShellXonsh represents Xonsh. ShellXonsh Shell = "xonsh" // ShellCmd represents Windows Command Prompt. ShellCmd Shell = "cmd" )
func DefaultShells ¶ added in v0.6.0
func DefaultShells() []Shell
DefaultShells returns the default set of supported shells.
type Theme ¶ added in v0.2.0
type Theme struct {
// Command styles command and subcommand names in the COMMANDS section.
Command lipgloss.Style
// Comment styles comment lines within the EXAMPLES section.
Comment lipgloss.Style
// Description styles the help text that describes commands and flags.
Description lipgloss.Style
// EnvVar styles the environment variable name in the env binding hint
// (e.g., GPG_PRIVATE_KEY in [env: GPG_PRIVATE_KEY]).
EnvVar lipgloss.Style
// EnvVarValue styles the environment variable value in the env binding hint
// (e.g., my-key in [env: GPG_PRIVATE_KEY=my-key]).
EnvVarValue lipgloss.Style
// Flag styles flag names including short and long forms
// (e.g., -v, --verbose).
Flag lipgloss.Style
// FlagDefault styles the default value indicator shown beneath flags
// (e.g., [default: 8080]).
FlagDefault lipgloss.Style
// FlagType styles the type hint for flags that accept values
// (e.g., <string> in --config <string>).
FlagType lipgloss.Style
// Header styles section headings such as USAGE, COMMANDS, FLAGS,
// GLOBAL FLAGS, and EXAMPLES.
Header lipgloss.Style
// Operator styles shell operators in the EXAMPLES section
// (e.g., |, >, >>, <, &&, ||, ;).
Operator lipgloss.Style
}
Theme defines the styles used for rendering CLI help output. Each field controls the appearance of a specific element.
func DefaultTheme ¶ added in v0.2.0
func DefaultTheme() Theme
DefaultTheme returns a theme with no styling applied.
type VersionInfo ¶ added in v0.5.0
type VersionInfo struct {
// Version is the semantic version of the application.
Version string `json:"version,omitempty"`
// GitCommit is the git commit hash of the build.
GitCommit string `json:"git_commit,omitempty"`
// GitBranch is the git branch of the build.
GitBranch string `json:"git_branch,omitempty"`
// BuildDate is the date/time the binary was built.
BuildDate string `json:"build_date,omitempty"`
// GoVersion is the Go version used to build the binary.
GoVersion string `json:"go_version,omitempty"`
// Platform is the OS/architecture the binary was built for.
Platform string `json:"platform,omitempty"`
}
VersionInfo contains build-time version information for the CLI.