gum

package module
v0.0.0-...-f369262 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2025 License: MIT Imports: 7 Imported by: 0

README ΒΆ


  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—   β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•—   β–ˆβ–ˆβ–ˆβ•—
  β–ˆβ–ˆβ•”β•β•β•β•β• β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ•‘
  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘
  β–ˆβ–ˆβ•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘
  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β•šβ•β• β–ˆβ–ˆβ•‘
  β•šβ•β•β•β•β•β•β•  β•šβ•β•β•β•β•β• β•šβ•β•     β•šβ•β•
  

A blazingly fast, elegant, and dependency-free library for building command-line interfaces in Go.


Go Reference License Dependencies

gum provides a powerful, fluent API that makes defining complex command-line applications simple and readable. It is built from the ground up with performance and developer experience as first-class citizens.

✨ Why Gum?

  • Fluent, Chainable API: Structure your CLI in a natural, declarative way.
  • Zero Dependencies: Keep your applications light and your builds fast. No external modules needed.
  • Blazingly Fast: Optimized for minimal memory allocations and high performance. See the benchmarks below.
  • Automatic Help Generation: Beautiful, detailed, and context-aware help text for all commands.
  • Built-in Shell Completion: Add Bash and Zsh completion with a single line of code.
  • Powerful Middleware: Use UnsureAction to create logging, metrics, or validation layers that don't halt execution.
  • Robust & Battle-Tested: A comprehensive test suite ensures reliability.

πŸš€ Performance

gum is designed to be exceptionally fast. Benchmarks run on a standard Intel(R) Core(TM) i5-5200U show just how little overhead the library adds.

Benchmark Task Time / Operation Memory / Operation Allocations / Operation
Simple Parse ~2,565 ns/op 864 B/op 11 allocs/op
Complex Parse ~2,644 ns/op 1088 B/op 10 allocs/op
Help Text Generation ~10,529 ns/op 2984 B/op 59 allocs/op

This means gum can parse even complex commands with subcommands and multiple flags in ~2.6 microseconds while allocating just over 1KB of memory.

πŸ“¦ Getting Started

First, add gum to your project:

go get github.com/devmdo/gum

Next, create a simple main.go file. This example demonstrates a root command with a flag and a subcommand in just a few lines.

// main.go
package main

import (
	"fmt"

	"github.com/devmdo/gum"
)

func main() {
	app := gum.NewApp("git").
		Description("A simple git-like example app").
		Version("1.0.0").
		Option("-v, --verbose", "Enable verbose output") // Global flag

	// Define the 'clone' command
	app.Command("clone, c").
		Description("Clone a repository into a new directory").
		Arg("repository", "The repository to clone").
		Option("-b, --branch", "Branch to checkout", "main").
		Action(func(args *gum.Args) error {
			repo := args.Arg(0)
			branch := args.String("branch")

			fmt.Printf("Cloning repository '%s' on branch '%s'...\n", repo, branch)
			if args.Bool("verbose") {
				fmt.Println("Verbose mode enabled.")
			}
			return nil
		})

	// Run the application
	app.Run()
}

Try it out!

# Build the application
go build .

# Run the subcommand
./git clone https://github.com/my/repo
# Output: Cloning repository 'https://github.com/my/repo' on branch 'main'...

# Use aliases, flags, and global flags
./git -v c https://github.com/my/repo --branch dev
# Output: Cloning repository 'https://github.com/my/repo' on branch 'dev'...
#         Verbose mode enabled.

# Get automatically generated help
./git clone --help

πŸ“– Features in Detail

1. Commands, Subcommands, and Aliases

The core of gum is the Command. You can chain .Command() calls to create nested subcommands. Provide a comma-separated string to define a primary name and its aliases.

func main() {
	app := gum.NewApp("docker")

	// Command with aliases
	app.Command("run, r").
		Description("Run a command in a new container")

	// Nested subcommands
	remote := app.Command("remote").
		Description("Manage remote connections")

	remote.Command("add").
		Description("Add a new remote")

	remote.Command("rm, remove").
		Description("Remove a remote")
    
    app.Run()
}

2. Arguments and Options (Flags)

gum supports positional arguments and a rich set of flag types.

  • Positional Arguments: Use .Arg() to define arguments for documentation in the help text.
    app.Command("clone").
        Arg("repository", "The repository to clone").
        Arg("directory", "The destination directory (optional)")
    
  • Options (Flags): Use .Option() to define flags.
    // Boolean flag (present or not)
    app.Option("-v, --verbose", "Enable verbose output")
    
    // Flag that takes a value
    app.Option("-o, --output", "Specify output file")
    
    // Flag with a default value
    app.Option("--port", "The port to listen on", "8080")
    
  • Parsing Formats: gum handles all common formats automatically:
    • --flag value
    • --flag=value
    • -f value
    • -abc (for combined boolean flags)

3. Actions and Accessing Values

The .Action() method is where your command's logic lives. It receives an *Args object to access parsed values.

app.Command("commit").
    Option("-m, --message", "The commit message").
    Option("-a, --all", "Stage all changed files").
    Action(func(args *gum.Args) error {
        // BTW you can count args by args.Len()

        // Check for boolean flag
        if args.Bool("all") {
            fmt.Println("Staging all files...")
        }

        // Get string value from a flag (works with -m or --message)
        message := args.String("message")
        if message == "" {
            return errors.New("commit message is required")
        }

        // Get positional arguments by index
        // e.g., for a command `my-app get user 123`
        resource := args.Arg(0) // "user"
        idStr := args.Arg(1)    // "123"

        // Type conversion helpers
        id, err := args.Int("id") // Also supports Float64()
        if err != nil {
            return err
        }

        fmt.Printf("Committing with message: %s\n", message)
        return nil
    })

4. Automatic Help Text

gum generates beautiful and useful help text automatically. Simply run your command with --help or provide no action for a command that has subcommands.

You can customize the output with:

  • .Description(string): Set the main description.
  • .Example(string): Provide a specific usage example.
  • .ExtraUsage(string): Add a free-form text block at the end of the help message.

Example output for ./git clone --help:

A test CLI application.

USAGE:
  test-cli clone <repo> [options]

ARGUMENTS:
  repo   The repository URL.

OPTIONS:
  --branch, -b   The branch to checkout (default: "main")
  --config       Path to a custom config file (default: "default.json")
  -v             Enable verbose output
  -R             Recursive
  --version      Print version information and exit

EXAMPLE:
  test-cli clone my-repo --branch dev

5. Automatic Shell Completion

Provides a first-class user experience by adding shell completion for bash and zsh.

Your users can enable it with a simple command:

Bash:

eval "$(your-app completion bash)"
```**Zsh:**
```bash
eval "$(your-app completion zsh)"

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation ΒΆ

Overview ΒΆ

Package gum provides a blazingly fast, elegant, and dependency-free library for building command-line interfaces in Go.

Package gum provides a blazingly fast, elegant, and dependency-free library for building command-line interfaces in Go.

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type App ΒΆ

type App = Command

App is the entry point for a CLI application. It's an alias for Command to provide a more intuitive starting point: `app := gum.NewApp(...)`.

func NewApp ΒΆ

func NewApp(name string) *App

NewApp creates the root command of your CLI application.

type ArgDef ΒΆ

type ArgDef struct {
	Name        string
	Description string
}

ArgDef defines a positional argument for documentation in the help text. Gum uses this only for generating the USAGE string.

type Args ΒΆ

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

Args holds the parsed values passed to a command's action. It provides safe and convenient access to positional arguments and option values.

func (*Args) Arg ΒΆ

func (a *Args) Arg(index int) string

Arg returns the positional argument at the given index. It returns an empty string if the index is out of bounds.

func (*Args) Bool ΒΆ

func (a *Args) Bool(name string) bool

Bool is a convenient alias for Has(), improving readability for boolean flags.

func (*Args) Float64 ΒΆ

func (a *Args) Float64(name string) (float64, error)

Float64 returns the option's value as a float64, or an error if it fails.

func (*Args) Has ΒΆ

func (a *Args) Has(name string) bool

Has returns true if an option was provided on the command line. This is the idiomatic way to check for boolean flags.

func (*Args) Int ΒΆ

func (a *Args) Int(name string) (int, error)

Int returns the option's value as an int, or an error if it fails.

func (*Args) Len ΒΆ

func (a *Args) Len() int

func (*Args) Raw ΒΆ

func (a *Args) Raw() *string

Raw returns the arguments that appeared after the `--` separator, if any.

func (*Args) Slice ΒΆ

func (a *Args) Slice(name string) []string

Slice returns all values for a given option, perfect for repeated flags.

func (*Args) String ΒΆ

func (a *Args) String(name string) string

String returns the value of an option as a string. If the option was provided multiple times, it returns the *last* value.

type Command ΒΆ

type Command struct {
	Name    string
	Aliases []string
	// contains filtered or unexported fields
}

Command represents a command or subcommand in the CLI application. Its methods are chainable, creating a fluent API for defining the CLI structure.

func (*Command) Action ΒΆ

func (c *Command) Action(fn func(args *Args) error) *Command

Action sets the primary function to be executed when the command is invoked. This is a convenient wrapper around UnsureAction that tells the parser to always stop after this action is complete, which is the most common use case.

func (*Command) Arg ΒΆ

func (c *Command) Arg(name, description string) *Command

Arg defines a positional argument for documentation in the help text.

func (*Command) Args ΒΆ

func (c *Command) Args() *Args

Args returns the parsed arguments for the command, useful for post-execution inspection.

func (*Command) Command ΒΆ

func (c *Command) Command(nameAndAliases string) *Command

Command defines a new subcommand. Aliases can be provided in a comma-separated list.

func (*Command) Description ΒΆ

func (c *Command) Description(desc string) *Command

Description sets the description for the command, shown in the help text.

func (*Command) DidActionRun ΒΆ

func (c *Command) DidActionRun() bool

DidActionRun returns true if an action was executed for this command or any of its subcommands.

func (*Command) Example ΒΆ

func (c *Command) Example(example string) *Command

Example sets an example usage string for the command.

func (*Command) ExtraUsage ΒΆ

func (c *Command) ExtraUsage(extra string) *Command

ExtraUsage adds a free-form text block to the end of the help message.

func (*Command) GenCompletion ΒΆ

func (c *Command) GenCompletion(shell string) (string, error)

GenCompletion generates and prints the shell completion script for the given shell.

func (*Command) Option ΒΆ

func (c *Command) Option(names, description string, defaultValue ...string) *Command

Option defines a flag for the command.

func (*Command) Parse ΒΆ

func (c *Command) Parse(osArgs []string) error

Parse analyzes the provided arguments and executes the matched command. This is the core logic of the library.

func (*Command) PrintCompletionScript ΒΆ

func (c *Command) PrintCompletionScript(shell string)

PrintCompletionScript generates and prints the completion script to stdout.

func (*Command) PrintUsage ΒΆ

func (c *Command) PrintUsage()

PrintUsage generates and prints the help text for a command to stdout.

func (*Command) Run ΒΆ

func (c *Command) Run()

Run is the standard entry point. It parses `os.Args` and handles all errors, providing the simplest possible start for a CLI application.

func (*Command) SpecialCall ΒΆ

func (c *Command) SpecialCall() bool

SpecialCall returns true if a built-in action was triggered (like default help, version, or shell completion). This helps developers avoid unnecessary initializations in their main() function for simple calls.

func (*Command) UnsureAction ΒΆ

func (c *Command) UnsureAction(fn UnsureActionFunc) *Command

UnsureAction sets a function that can conditionally halt execution. This is powerful for middleware, logging, or custom flag handling that shouldn't stop the flow to subcommands.

func (*Command) Usage ΒΆ

func (c *Command) Usage() string

Usage generates and returns the help text for a command as a string. This function is heavily optimized to reduce memory allocations.

func (*Command) Version ΒΆ

func (c *Command) Version(version string) *Command

Version sets the version for the app. If set, a default --version flag is automatically handled.

type ErrMissingValue ΒΆ

type ErrMissingValue struct {
	Name string
}

ErrMissingValue is returned when a flag that requires a value is provided without one.

func (ErrMissingValue) Error ΒΆ

func (e ErrMissingValue) Error() string

type ErrUnknownFlag ΒΆ

type ErrUnknownFlag struct {
	Name string
}

ErrUnknownFlag is returned when the parser encounters a flag that has not been defined.

func (ErrUnknownFlag) Error ΒΆ

func (e ErrUnknownFlag) Error() string

type Option ΒΆ

type Option struct {
	// Names contains all valid names for this option, e.g., ["--branch", "-b"].
	// The first name is considered the primary name.
	Names []string

	// Description is the help text shown to the user.
	Description string

	// DefaultValue, if not nil, is the value used if the flag is not provided.
	DefaultValue *string
}

Option represents a command-line flag, like --verbose or -f. It holds all the information needed to parse and document a flag.

type UnsureActionFunc ΒΆ

type UnsureActionFunc func(args *Args) (stop bool, err error)

UnsureActionFunc is the single, unified function type for all command actions. It allows an action to either halt further processing (like a normal command) or to continue processing (like a middleware).

It returns two values:

  • bool: `true` if execution should stop, `false` to continue.
  • error: An error if the action failed.

The public `.Action()` method is a convenient wrapper around this type.

Directories ΒΆ

Path Synopsis
_examples
docker-lite command
_examples/docker-lite/main.go
_examples/docker-lite/main.go
git-assist command
_examples/git-assist/main.go
_examples/git-assist/main.go
git-example command
sys-stats command
_examples/sys-stats/main.go
_examples/sys-stats/main.go

Jump to

Keyboard shortcuts

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