cli

package module
v0.0.0-...-73cbc83 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 9 Imported by: 0

README

cli

A minimal, dependency-free CLI framework for building command-line applications in Go.

Inspired by Cobra but with a simpler design and zero external dependencies.

Features

  • Commands & Subcommands – Build nested command structures.
  • Flags – Local and persistent flags using Go’s standard flag package.
  • Help System – Automatic help generation with grouping.
  • Argument Validation – Custom positional argument validators.
  • Hooks – PersistentPreRun, PreRun, PostRun, PersistentPostRun.
  • Error Handling – Silence errors/usage when needed.
  • Command Suggestions – Levenshtein-based suggestions for mistyped commands.
  • Shell Completions – Generate completions for Bash, Zsh, Fish, and PowerShell.
  • No Dependencies – Only uses the Go standard library.

Installation

go get github.com/neomen/cli

Quick Start

Create a simple command with a flag:

package main

import (
    "fmt"
    "log"

    "github.com/neomen/cli"
)

func main() {
    root := cli.NewCommand("myapp", "A simple CLI app", "")

    var name string
    root.Flags().StringVar(&name, "name", "World", "who to greet")

    root.Run = func(cmd *cli.Command, args []string) error {
        fmt.Printf("Hello, %s!\n", name)
        return nil
    }

    if err := root.Execute(); err != nil {
        log.Fatal(err)
    }
}

Run it:

$ go build -o myapp
$ ./myapp --name=Alice
Hello, Alice!

Usage Examples

Adding Subcommands
serve := cli.NewCommand("serve", "Start the server", "Long description...")
serve.Flags().Int("port", 8080, "Port to listen on")
serve.Run = func(cmd *cli.Command, args []string) error {
    port, _ := cmd.Flags().GetInt("port")
    fmt.Printf("Starting server on port %d\n", port)
    return nil
}

root.AddCommand(serve)
Persistent Flags

Persistent flags are available to the command and all its subcommands.

root.PersistentFlags().Bool("verbose", false, "Enable verbose output")

// In a subcommand:
verbose, _ := cmd.PersistentFlags().GetBool("verbose")
Argument Validation
cmd.Args = func(cmd *cli.Command, args []string) error {
    if len(args) != 2 {
        return fmt.Errorf("requires exactly 2 arguments")
    }
    return nil
}
Hooks
cmd.PersistentPreRunE = func(cmd *cli.Command, args []string) error {
    fmt.Println("Before command execution")
    return nil
}

cmd.PostRunE = func(cmd *cli.Command, args []string) error {
    fmt.Println("After command execution")
    return nil
}
Shell Completions

Generate completion scripts for various shells:

// For Bash
root.GenBashCompletion(os.Stdout)

// For Zsh
root.GenZshCompletion(os.Stdout)

// For Fish
root.GenFishCompletion(os.Stdout)

// For PowerShell
root.GenPowerShellCompletion(os.Stdout)

Documentation

The API is fully documented in the source code. See the GoDoc for detailed information.

License

MIT License – see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Command

type Command struct {
	// Use is the one-line usage message. Recommended syntax: "cmd [flags] [arg...]"
	Use string
	// Short is the short description shown in help.
	Short string
	// Long is the long message shown in help.
	Long string
	// Example is an optional field to show usage examples.
	Example string
	// Deprecated marks this command as deprecated and prints the given message.
	Deprecated string
	// Version defines the version for this command. If set on the root command,
	// a --version flag will be added automatically.
	Version string
	// Annotations are arbitrary key-value pairs attached to the command.
	Annotations map[string]string

	// Run is the function that executes the command. If nil, the command is considered a group.
	// The command's context is available via cmd.Context().
	Run func(cmd *Command, args []string) error

	// Aliases is a list of alternative names for this command.
	Aliases []string
	// SuggestFor is a list of command names for which this command will be suggested.
	SuggestFor []string
	// Args defines validation for positional arguments.
	Args PositionalArgs
	// ValidArgs is a list of valid positional arguments for shell completion.
	ValidArgs []string
	// ArgAliases is a list of aliases for ValidArgs (accepted but not suggested).
	ArgAliases []string

	// GroupID identifies the command group in help output.
	GroupID string
	// CommandGroups is a list of groups for subcommands (used on parent).
	CommandGroups []*Group

	// Hidden, if true, hides the command from help output.
	Hidden bool
	// SilenceErrors, if true, suppresses automatic error printing.
	SilenceErrors bool
	// SilenceUsage, if true, suppresses usage printing when an error occurs.
	SilenceUsage bool
	// DisableFlagParsing disables flag parsing entirely; all arguments are treated as positional.
	DisableFlagParsing bool
	// DisableSuggestions disables command name suggestions for unknown commands.
	DisableSuggestions bool
	// SuggestionsMinimumDistance sets the minimum Levenshtein distance for suggestions.
	SuggestionsMinimumDistance int
	// TraverseChildren, if true, parses flags on all parents before executing child commands.
	TraverseChildren bool

	// PersistentPreRunE is executed before any children commands (in parent order).
	PersistentPreRunE func(cmd *Command, args []string) error
	// PreRunE is executed before the command's Run function.
	PreRunE func(cmd *Command, args []string) error
	// PostRunE is executed after the command's Run function.
	PostRunE func(cmd *Command, args []string) error
	// PersistentPostRunE is executed after all children commands (in child order).
	PersistentPostRunE func(cmd *Command, args []string) error
	// contains filtered or unexported fields
}

Command represents a CLI command with subcommands, flags, and an action.

func NewCommand

func NewCommand(use, short, long string) *Command

NewCommand creates a new command with the given name and description.

func (*Command) AddCommand

func (c *Command) AddCommand(children ...*Command)

AddCommand adds one or more subcommands to this command.

func (*Command) AddCompletionCommand

func (c *Command) AddCompletionCommand()

AddCompletionCommand adds the __complete and __completeNoDesc subcommands to the root command. This is automatically called for root commands, but can be called manually if needed.

func (*Command) BoolVarP

func (c *Command) BoolVarP(p *bool, long, short string, value bool, usage string)

BoolVarP defines a boolean flag with both long and short names.

func (*Command) Command

func (c *Command) Command(name string) *Command

Command returns the subcommand with the given name or alias, or nil if not found.

func (*Command) Commands

func (c *Command) Commands() []*Command

Commands returns a list of subcommands.

func (*Command) Context

func (c *Command) Context() context.Context

Context returns the context associated with this command. It is set by ExecuteContext or SetContext.

func (*Command) ErrWriter

func (c *Command) ErrWriter() io.Writer

ErrWriter returns the error writer.

func (*Command) Execute

func (c *Command) Execute() error

Execute runs the command with the given arguments (usually os.Args[1:]). It uses context.Background().

func (*Command) ExecuteContext

func (c *Command) ExecuteContext(ctx context.Context, args []string) error

ExecuteContext runs the command with a context and arguments. It sets the command's context before execution.

func (*Command) Flags

func (c *Command) Flags() *flag.FlagSet

Flags returns the local flag set for this command.

func (*Command) GenBashCompletion

func (c *Command) GenBashCompletion(w io.Writer) error

GenBashCompletion writes bash completion script to the given writer.

func (*Command) GenFishCompletion

func (c *Command) GenFishCompletion(w io.Writer) error

GenFishCompletion writes fish completion script to the given writer.

func (*Command) GenPowerShellCompletion

func (c *Command) GenPowerShellCompletion(w io.Writer) error

GenPowerShellCompletion writes PowerShell completion script to the given writer.

func (*Command) GenZshCompletion

func (c *Command) GenZshCompletion(w io.Writer) error

GenZshCompletion writes zsh completion script to the given writer.

func (*Command) Help

func (c *Command) Help()

Help prints help information for the command.

func (*Command) InReader

func (c *Command) InReader() io.Reader

InReader returns the input reader.

func (*Command) IntVarP

func (c *Command) IntVarP(p *int, long, short string, value int, usage string)

IntVarP defines an integer flag with both long and short names. It sets the variable p to the value given on the command line.

func (*Command) Name

func (c *Command) Name() string

Name returns the command name (the first word of Use).

func (*Command) OutWriter

func (c *Command) OutWriter() io.Writer

OutWriter returns the output writer.

func (*Command) Parent

func (c *Command) Parent() *Command

Parent returns the parent command.

func (*Command) PersistentFlags

func (c *Command) PersistentFlags() *flag.FlagSet

PersistentFlags returns the persistent flag set for this command.

func (*Command) SetContext

func (c *Command) SetContext(ctx context.Context)

SetContext sets the context for this command.

func (*Command) SetErrWriter

func (c *Command) SetErrWriter(w io.Writer)

SetErrWriter sets the error writer.

func (*Command) SetInReader

func (c *Command) SetInReader(r io.Reader)

SetInReader sets the input reader.

func (*Command) SetOutWriter

func (c *Command) SetOutWriter(w io.Writer)

SetOutWriter sets the output writer.

func (*Command) StringVarP

func (c *Command) StringVarP(p *string, long, short string, value string, usage string)

StringVarP defines a string flag with both long and short names.

type Group

type Group struct {
	ID    string
	Title string
}

Group represents a group of commands in help output.

type PositionalArgs

type PositionalArgs func(cmd *Command, args []string) error

PositionalArgs defines a function to validate positional arguments.

Jump to

Keyboard shortcuts

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