go-commander: github.com/yitsushi/go-commander Index | Examples | Files

package commander

import "github.com/yitsushi/go-commander"



Package Files

argument.go command_descriptor.go command_handler.go command_helper.go command_registry.go command_wrapper.go


var FmtPrintf = fmt.Printf

FmtPrintf is fmt.Printf

var OSExtExecutable = osext.Executable

OSExtExecutable returns current executable path

func RegisterArgumentType Uses

func RegisterArgumentType(name string, f argumentTypeFunction)

RegisterArgumentType registers a new argument type


commander.RegisterArgumentType("MyType", func(value string) (interface{}, error) {
    values := strings.Split(value, ":")

    if len(values) < 2 {
        return &MyCustomType{}, errors.New("Invalid format! MyType => 'ID:Name'")

    id, err := strconv.ParseUint(values[0], 10, 64)
    if err != nil {
        return &MyCustomType{}, errors.New("Invalid format! MyType => 'ID:Name'")

    return &MyCustomType{
            ID:   id,
            Name: values[1],


commander.RegisterArgumentType("Int32", func(value string) (interface{}, error) {
    return strconv.ParseInt(value, 10, 32)

type Argument Uses

type Argument struct {
    Name          string
    Type          string
    OriginalValue string
    Value         interface{}
    Error         error
    FailOnError   bool

Argument represents a single argument

func (*Argument) SetValue Uses

func (a *Argument) SetValue(original string) error

SetValue saves the original value to the argument. Returns with an error if conversion failed

type CommandDescriptor Uses

type CommandDescriptor struct {
    // Required! name of the command
    Name string
    // Optional: argument list as a string
    // Basic convention: <required_argument> [optional_argument]
    Arguments string
    // Optional: Short description is used in general help
    ShortDescription string
    // Optional: Long description is used in command specific help
    LongDescription string
    // Optional: Examples array is used in command specific help
    Examples []string

CommandDescriptor describes a command for Help calls

type CommandHandler Uses

type CommandHandler interface {
    // Execute function will be executed when the command is called
    // opts can be used for logging, parsing flags like '-v'
    Execute(opts *CommandHelper)

CommandHandler defines a command. If a struct implements all the required function, it is acceptable as a CommandHandler for CommandRegistry

type CommandHelper Uses

type CommandHelper struct {
    // If -d is defined
    DebugMode bool
    // If -v is defined
    VerboseMode bool
    // Boolean opts
    Flags map[string]bool
    // Other opts passed
    Opts map[string]string
    // Non-flag arguments
    Args []string
    // contains filtered or unexported fields

CommandHelper is a helper struct CommandHandler.Execute will get this as an argument and you can access extra functions, farsed flags with this

func (*CommandHelper) Arg Uses

func (c *CommandHelper) Arg(index int) string

Arg return with an item from Flags based on the given index emtpy string if not exists


opts.Parse([]string{"my-command", "plain-argument"})




func (*CommandHelper) AttachArgumentList Uses

func (c *CommandHelper) AttachArgumentList(argumets []*Argument)

AttachArgumentList binds an Argument list to CommandHelper

func (*CommandHelper) ErrorForTypedOpt Uses

func (c *CommandHelper) ErrorForTypedOpt(key string) error

ErrorForTypedOpt returns an error if the given value for the key is defined but not valid

func (*CommandHelper) Flag Uses

func (c *CommandHelper) Flag(key string) bool

Flag return with an item from Flags based on the given key false if not exists


opts.Parse([]string{"my-command", "plain-argument", "-l", "--no-color"})

if opts.Flag("l") {
    fmt.Println("-l is defined")

if opts.Flag("no-color") {
    fmt.Println("Color mode is disabled")


-l is defined
Color mode is disabled

func (*CommandHelper) Log Uses

func (c *CommandHelper) Log(message string)

Log is a logger function for debug messages it prints a message if DebugeMode is true

func (*CommandHelper) Opt Uses

func (c *CommandHelper) Opt(key string) string

Opt return with an item from Opts based on the given key empty string if not exists

func (*CommandHelper) Parse Uses

func (c *CommandHelper) Parse(flag []string)

Parse is a helper method that parses all passed arguments flags, opts and arguments

func (*CommandHelper) TypedOpt Uses

func (c *CommandHelper) TypedOpt(key string) interface{}

TypedOpt return with an item from the predifined argument list based on the given key empty string if not exists


        Name: "list",
        Type: "StringArray[]",
opts.Parse([]string{"my-command", "--list=one,two,three"})

// list is a StringArray[]
if opts.ErrorForTypedOpt("list") == nil {
    myList := opts.TypedOpt("list").([]string)
    if len(myList) > 0 {
        fmt.Printf("My list: %v\n", myList)

// Never defined, always shoud be an empty string
if opts.TypedOpt("no-key").(string) != "" {
    panic("Something went wrong!")


My list: [one two three]

type CommandRegistry Uses

type CommandRegistry struct {
    Commands map[string]*CommandWrapper
    Helper   *CommandHelper
    Depth    int
    // contains filtered or unexported fields

CommandRegistry will handle all CLI request and find the route to the proper Command

func NewCommandRegistry Uses

func NewCommandRegistry() *CommandRegistry

NewCommandRegistry is a simple "constructor"-like function that initializes Commands map

func (*CommandRegistry) CommandHelp Uses

func (c *CommandRegistry) CommandHelp(name string)

CommandHelp prints more detailed help for a specific Command

func (*CommandRegistry) Execute Uses

func (c *CommandRegistry) Execute()

Execute finds the proper command, handle errors from the command and print Help if the given command it unknown or print the Command specific help if something went wrong or the user asked for it.

func (*CommandRegistry) Help Uses

func (c *CommandRegistry) Help()

Help lists all available commands to the user

func (*CommandRegistry) Register Uses

func (c *CommandRegistry) Register(f NewCommandFunc)

Register is a function that adds your command into the registry

type CommandWrapper Uses

type CommandWrapper struct {
    // Help contains all information about the command
    Help *CommandDescriptor
    // Handler will be called when the user calls that specific command
    Handler CommandHandler
    // Validator will be executed before Execute on the Handler
    Validator ValidatorFunc
    // Arguments is a simple list of possible arguments with type definition
    Arguments []*Argument

CommandWrapper is a general wrapper for a command CommandRegistry will know what to do this a struct like this

type NewCommandFunc Uses

type NewCommandFunc func(appName string) *CommandWrapper

NewCommandFunc is the expected type for CommandRegistry.Register

type ValidatorFunc Uses

type ValidatorFunc func(opts *CommandHelper)

ValidatorFunc can pre-validate the command and it's arguments Just throw a panic if something is wrong

Package commander imports 10 packages (graph) and is imported by 2 packages. Updated 2020-06-01. Refresh now. Tools for package owners.