Documentation ¶
Index ¶
- Variables
- func RegisterArgumentType(name string, f argumentTypeFunction)
- type Argument
- type CommandDescriptor
- type CommandHandler
- type CommandHelper
- func (c *CommandHelper) Arg(index int) string
- func (c *CommandHelper) AttachArgumentList(argumets []*Argument)
- func (c *CommandHelper) ErrorForTypedOpt(key string) error
- func (c *CommandHelper) Flag(key string) bool
- func (c *CommandHelper) Log(message string)
- func (c *CommandHelper) Opt(key string) string
- func (c *CommandHelper) Parse(flag []string)
- func (c *CommandHelper) TypedOpt(key string) interface{}
- type CommandRegistry
- type CommandWrapper
- type NewCommandFunc
- type ValidatorFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var FmtPrintf = fmt.Printf
FmtPrintf is fmt.Printf
var OSExtExecutable = osext.Executable
OSExtExecutable returns current executable path
Functions ¶
func RegisterArgumentType ¶ added in v1.1.0
func RegisterArgumentType(name string, f argumentTypeFunction)
RegisterArgumentType registers a new argument type
Example (CustomStruct) ¶
package main import ( "errors" "strconv" "strings" commander "github.com/yitsushi/go-commander" ) type MyCustomType struct { ID uint64 Name string } func main() { 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], }, nil }) }
Output:
Example (Simple) ¶
package main import ( "strconv" commander "github.com/yitsushi/go-commander" ) func main() { commander.RegisterArgumentType("Int32", func(value string) (interface{}, error) { return strconv.ParseInt(value, 10, 32) }) }
Output:
Types ¶
type Argument ¶ added in v1.1.0
type Argument struct { Name string Type string OriginalValue string Value interface{} Error error FailOnError bool }
Argument represents a single argument
type CommandDescriptor ¶ added in v1.1.0
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 ¶ added in v1.1.0
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 ¶ added in v1.1.0
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 ¶ added in v1.1.0
func (c *CommandHelper) Arg(index int) string
Arg return with an item from Flags based on the given index emtpy string if not exists
Example ¶
package main import ( "fmt" commander "github.com/yitsushi/go-commander" ) // (c *MyCommand) Execute(opts *commander.CommandHelper) var opts *commander.CommandHelper func main() { opts.Parse([]string{"my-command", "plain-argument"}) fmt.Println(opts.Arg(0)) }
Output: plain-argument
func (*CommandHelper) AttachArgumentList ¶ added in v1.1.0
func (c *CommandHelper) AttachArgumentList(argumets []*Argument)
AttachArgumentList binds an Argument list to CommandHelper
func (*CommandHelper) ErrorForTypedOpt ¶ added in v1.1.0
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 ¶ added in v1.1.0
func (c *CommandHelper) Flag(key string) bool
Flag return with an item from Flags based on the given key false if not exists
Example ¶
package main import ( "fmt" commander "github.com/yitsushi/go-commander" ) // (c *MyCommand) Execute(opts *commander.CommandHelper) var opts *commander.CommandHelper func main() { 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") } }
Output: -l is defined Color mode is disabled
func (*CommandHelper) Log ¶ added in v1.1.0
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 ¶ added in v1.1.0
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 ¶ added in v1.1.0
func (c *CommandHelper) Parse(flag []string)
Parse is a helper method that parses all passed arguments flags, opts and arguments
func (*CommandHelper) TypedOpt ¶ added in v1.1.0
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
Example ¶
package main import ( "fmt" "log" commander "github.com/yitsushi/go-commander" ) // (c *MyCommand) Execute(opts *commander.CommandHelper) var opts *commander.CommandHelper func main() { opts.AttachArgumentList([]*commander.Argument{ &commander.Argument{ Name: "list", Type: "StringArray[]", }, }) opts.Parse([]string{"my-command", "--list=one,two,three"}) // list is a StringArray[] if opts.ErrorForTypedOpt("list") == nil { log.Println(opts.TypedOpt("list")) 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!") } }
Output: My list: [one two three]
type CommandRegistry ¶
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 ¶
func NewCommandRegistry() *CommandRegistry
NewCommandRegistry is a simple "constructor"-like function that initializes Commands map
func (*CommandRegistry) CommandHelp ¶
func (c *CommandRegistry) CommandHelp(name string)
CommandHelp prints more detailed help for a specific Command
func (*CommandRegistry) Execute ¶
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 ¶
func (c *CommandRegistry) Help()
Help lists all available commands to the user
func (*CommandRegistry) Register ¶
func (c *CommandRegistry) Register(f NewCommandFunc)
Register is a function that adds your command into the registry
type CommandWrapper ¶ added in v1.1.0
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 ¶ added in v1.1.0
type NewCommandFunc func(appName string) *CommandWrapper
NewCommandFunc is the expected type for CommandRegistry.Register
type ValidatorFunc ¶ added in v1.1.0
type ValidatorFunc func(opts *CommandHelper)
ValidatorFunc can pre-validate the command and it's arguments Just throw a panic if something is wrong