Documentation
¶
Overview ¶
Package mamba provides a modern, drop-in replacement for Cobra with enhanced terminal features.
Mamba maintains 100% API compatibility with Cobra while adding beautiful colored output, interactive prompts, loading spinners, progress bars, and modern styled help messages.
Quick Start ¶
Create a simple command:
package main
import (
"github.com/base-go/mamba"
)
func main() {
rootCmd := &mamba.Command{
Use: "myapp",
Short: "My awesome CLI application",
Run: func(cmd *mamba.Command, args []string) {
cmd.PrintSuccess("Welcome to Mamba!")
},
}
rootCmd.Execute()
}
Modern Features ¶
Mamba adds several modern terminal features on top of Cobra's functionality:
Styled Output - Beautiful, pre-styled output methods:
cmd.PrintSuccess("Operation completed!")
cmd.PrintError("Something went wrong")
cmd.PrintWarning("Be careful")
cmd.PrintInfo("Here's some info")
cmd.PrintHeader("Section Title")
Interactive Prompts - User-friendly input with the interactive package:
import "github.com/base-go/mamba/pkg/interactive"
name, err := interactive.AskString("What's your name?", "Enter name")
confirmed, err := interactive.AskConfirm("Continue?", true)
Loading Spinners - Visual feedback for operations:
import "github.com/base-go/mamba/pkg/spinner"
spinner.WithSpinner("Processing...", func() error {
// Your operation here
return nil
})
Progress Bars - Track batch operations:
spinner.WithProgress("Loading...", total, func(update func()) {
for i := 0; i < total; i++ {
// Process item
update()
}
})
Migration from Cobra ¶
Migrating from Cobra is as simple as changing imports:
Before:
import "github.com/spf13/cobra"
After:
import "github.com/base-go/mamba"
All Cobra features continue to work:
- Command structure (Use, Short, Long, Example)
- Subcommands (AddCommand, RemoveCommand)
- Flags (local, persistent, shorthand)
- Lifecycle hooks (PreRun, PostRun, PersistentPreRun, etc.)
- Argument validators (NoArgs, ExactArgs, MinimumNArgs, etc.)
- Error handling (RunE, PreRunE, PostRunE)
- Context support
- Custom help and usage templates
Styling ¶
Use the style package for custom formatting:
import "github.com/base-go/mamba/pkg/style"
fmt.Println(style.Success("Success!"))
fmt.Println(style.Error("Error!"))
fmt.Println(style.Bold("Bold text"))
fmt.Println(style.Code("code snippet"))
fmt.Println(style.Box("Title", "Content"))
Disabling Modern Features ¶
If needed, modern styling can be disabled:
disableColors := false
cmd := &mamba.Command{
Use: "myapp",
EnableColors: &disableColors,
}
Architecture ¶
Mamba is built on proven libraries:
- spf13/pflag - POSIX-style flag parsing
- charmbracelet/lipgloss - Terminal styling
- charmbracelet/huh - Interactive forms
- charmbracelet/bubbles - TUI components
Index ¶
- Variables
- type Command
- func (c *Command) AddCommand(cmds ...*Command)
- func (c *Command) Commands() []*Command
- func (c *Command) Context() interface{}
- func (c *Command) ErrOrStderr() io.Writer
- func (c *Command) Execute() error
- func (c *Command) ExecuteContext(ctx interface{}) error
- func (c *Command) Find(args []string) (*Command, []string, error)
- func (c *Command) Flags() *pflag.FlagSet
- func (c *Command) HasAlias(s string) bool
- func (c *Command) HasParent() bool
- func (c *Command) HasSubCommands() bool
- func (c *Command) Help() error
- func (c *Command) InOrStdin() io.Reader
- func (c *Command) LocalFlags() *pflag.FlagSet
- func (c *Command) ModernHelp() string
- func (c *Command) Name() string
- func (c *Command) OutOrStdout() io.Writer
- func (c *Command) Parent() *Command
- func (c *Command) ParseFlags(args []string) error
- func (c *Command) PersistentFlags() *pflag.FlagSet
- func (c *Command) PrintBox(title, content string)
- func (c *Command) PrintBullet(msg string)
- func (c *Command) PrintCode(code string)
- func (c *Command) PrintError(msg string)
- func (c *Command) PrintHeader(msg string)
- func (c *Command) PrintInfo(msg string)
- func (c *Command) PrintSubHeader(msg string)
- func (c *Command) PrintSuccess(msg string)
- func (c *Command) PrintWarning(msg string)
- func (c *Command) RemoveCommand(cmds ...*Command)
- func (c *Command) Root() *Command
- func (c *Command) SetContext(ctx interface{})
- func (c *Command) SetErr(err io.Writer)
- func (c *Command) SetHelpCommand(cmd *Command)
- func (c *Command) SetHelpFunc(f func(*Command, []string))
- func (c *Command) SetIn(in io.Reader)
- func (c *Command) SetOutput(output io.Writer)
- func (c *Command) SetUsageFunc(f func(*Command) error)
- func (c *Command) SetUsageTemplate(s string)
- func (c *Command) SetVersionTemplate(s string)
- func (c *Command) Usage() error
- func (c *Command) UsageString() string
- func (c *Command) UseLine() string
- type PositionalArgs
Constants ¶
This section is empty.
Variables ¶
var ( // NoArgs returns an error if any args are provided NoArgs = func(cmd *Command, args []string) error { if len(args) > 0 { return fmt.Errorf("unknown command %q for %q", args[0], cmd.Use) } return nil } // ArbitraryArgs accepts any number of args (including zero) ArbitraryArgs = func(cmd *Command, args []string) error { return nil } // MinimumNArgs returns an error if there are not at least N args MinimumNArgs = func(n int) PositionalArgs { return func(cmd *Command, args []string) error { if len(args) < n { return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) } return nil } } // MaximumNArgs returns an error if there are more than N args MaximumNArgs = func(n int) PositionalArgs { return func(cmd *Command, args []string) error { if len(args) > n { return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) } return nil } } // ExactArgs returns an error if there are not exactly N args ExactArgs = func(n int) PositionalArgs { return func(cmd *Command, args []string) error { if len(args) != n { return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) } return nil } } // RangeArgs returns an error if the number of args is not within the range [min, max] RangeArgs = func(min, max int) PositionalArgs { return func(cmd *Command, args []string) error { if len(args) < min || len(args) > max { return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) } return nil } } )
Standard validators for positional arguments. These can be used in the Args field of a Command to validate argument counts.
Functions ¶
This section is empty.
Types ¶
type Command ¶
type Command struct {
// Use is the one-line usage message
Use string
// Aliases is an array of aliases that can be used instead of the first word in Use
Aliases []string
// Short is the short description shown in the 'help' output
Short string
// Long is the long message shown in the 'help <this-command>' output
Long string
// Example is examples of how to use the command
Example string
// Run is the function to call when this command is executed
// If both Run and RunE are defined, RunE takes precedence
Run func(cmd *Command, args []string)
// RunE is the function to call when this command is executed, with error handling
RunE func(cmd *Command, args []string) error
// PreRun is called before Run
PreRun func(cmd *Command, args []string)
// PreRunE is called before RunE, with error handling
PreRunE func(cmd *Command, args []string) error
// PostRun is called after Run
PostRun func(cmd *Command, args []string)
// PostRunE is called after RunE, with error handling
PostRunE func(cmd *Command, args []string) error
// PersistentPreRun is called before PreRun and inherited by children
PersistentPreRun func(cmd *Command, args []string)
// PersistentPreRunE is called before PreRunE and inherited by children
PersistentPreRunE func(cmd *Command, args []string) error
// PersistentPostRun is called after PostRun and inherited by children
PersistentPostRun func(cmd *Command, args []string)
// PersistentPostRunE is called after PostRunE and inherited by children
PersistentPostRunE func(cmd *Command, args []string) error
// SilenceErrors prevents error messages from being displayed
SilenceErrors bool
// SilenceUsage prevents usage from being displayed on errors
SilenceUsage bool
// DisableFlagParsing disables flag parsing
DisableFlagParsing bool
// DisableAutoGenTag prevents auto-generation tag in help
DisableAutoGenTag bool
// Hidden hides this command from help output
Hidden bool
// Args defines expected arguments
Args PositionalArgs
// ValidArgs is list of all valid non-flag arguments
ValidArgs []string
// ValidArgsFunction is an optional function for custom argument completion
ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, error)
// Version is the version for this command
Version string
// Modern terminal features
// EnableColors enables colored output (default: auto-detect)
EnableColors *bool
// EnableInteractive enables interactive prompts
EnableInteractive bool
// ShowSpinner enables loading spinners
ShowSpinner bool
// contains filtered or unexported fields
}
Command represents a CLI command with modern terminal features.
Command is fully compatible with Cobra's Command struct and can be used as a drop-in replacement. It extends Cobra's functionality with modern terminal features including colored output, interactive prompts, loading spinners, and styled help messages.
Example:
cmd := &mamba.Command{
Use: "myapp",
Short: "My application",
Run: func(cmd *mamba.Command, args []string) {
cmd.PrintSuccess("Hello, Mamba!")
},
}
cmd.Execute()
func (*Command) AddCommand ¶
AddCommand adds one or more subcommands
func (*Command) Context ¶
func (c *Command) Context() interface{}
Context returns the command context
func (*Command) ErrOrStderr ¶
ErrOrStderr returns the error output writer or stderr
func (*Command) ExecuteContext ¶
ExecuteContext runs the command with context
func (*Command) HasSubCommands ¶
HasSubCommands returns true if the command has subcommands
func (*Command) LocalFlags ¶
LocalFlags returns the local FlagSet
func (*Command) ModernHelp ¶
ModernHelp generates a modern styled help message
func (*Command) OutOrStdout ¶
OutOrStdout returns the output writer or stdout
func (*Command) ParseFlags ¶
ParseFlags parses the flags
func (*Command) PersistentFlags ¶
PersistentFlags returns the persistent FlagSet
func (*Command) PrintBullet ¶
PrintBullet prints a bullet point
func (*Command) PrintError ¶
PrintError prints an error message
func (*Command) PrintSubHeader ¶
PrintSubHeader prints a sub-header
func (*Command) PrintSuccess ¶
PrintSuccess prints a success message
func (*Command) PrintWarning ¶
PrintWarning prints a warning message
func (*Command) RemoveCommand ¶
RemoveCommand removes one or more subcommands
func (*Command) SetContext ¶
func (c *Command) SetContext(ctx interface{})
SetContext sets the command context
func (*Command) SetHelpCommand ¶
SetHelpCommand sets the help command
func (*Command) SetHelpFunc ¶
SetHelpFunc sets the help function
func (*Command) SetUsageFunc ¶
SetUsageFunc sets the usage function
func (*Command) SetUsageTemplate ¶
SetUsageTemplate sets the usage template
func (*Command) SetVersionTemplate ¶
SetVersionTemplate sets the version template
func (*Command) UsageString ¶
UsageString returns the usage string (plain version)
type PositionalArgs ¶
PositionalArgs defines a validation function for positional arguments. It is used to validate command arguments before the Run function is called.
Example:
cmd := &mamba.Command{
Use: "copy <source> <dest>",
Args: mamba.ExactArgs(2),
Run: func(cmd *mamba.Command, args []string) { ... },
}