Documentation
¶
Overview ¶
Example (Hello) ¶
This is a HelloWorld example
package main
import (
"github.com/akeylesslabs/cli"
)
type helloT struct {
cli.Helper
Name string `cli:"name" usage:"tell me your name" dft:"world"`
Age uint8 `cli:"a,age" usage:"tell me your age" dft:"100"`
}
func main() {
args := []string{"app", "--name=Cliper"}
cli.RunWithArgs(new(helloT), args, func(ctx *cli.Context) error {
argv := ctx.Argv().(*helloT)
ctx.String("Hello, %s! Your age is %d?\n", argv.Name, argv.Age)
return nil
})
}
Output: Hello, Cliper! Your age is 100?
Index ¶
- Constants
- Variables
- func Daemon(ctx *Context, successPrefix string) error
- func DaemonResponse(resp string)
- func HelpCommandFn(ctx *Context) error
- func IsValidCommandName(commandName string) bool
- func LaunchEditor(editor string) (content []byte, err error)
- func Parse(args []string, argv interface{}) error
- func ReadJSON(r io.Reader, argv interface{}) error
- func ReadJSONConfigFromFile(filename string, argv interface{}) error
- func ReadJSONFromFile(filename string, argv interface{}) error
- func RegisterFlagParser(name string, creator FlagParserCreator)
- func Run(argv interface{}, fn CommandFunc, descs ...string) int
- func RunWithArgs(argv interface{}, args []string, fn CommandFunc, descs ...string) int
- func SetUsageStyle(style UsageStyle)
- type Addrdeprecated
- func (addr Addr) ToString() stringdeprecated
- type AddrWithShortdeprecated
- type ArgvFunc
- type AutoHelper
- type Command
- func (cmd *Command) ChildrenDescriptions(prefix, indent string) string
- func (cmd *Command) IsClient() bool
- func (cmd *Command) IsServer() bool
- func (cmd *Command) ListChildren() []string
- func (cmd *Command) ListenAndServeHTTP(addr string) error
- func (cmd *Command) Parent() *Command
- func (cmd *Command) Path() string
- func (cmd *Command) RPC(httpc *http.Client, ctx *Context) error
- func (cmd *Command) Register(child *Command) *Command
- func (cmd *Command) RegisterFunc(name string, fn CommandFunc, argvFn ArgvFunc) *Command
- func (cmd *Command) RegisterHTTP(ctxs ...*Context) error
- func (cmd *Command) RegisterTree(forest ...*CommandTree)
- func (cmd *Command) Root() *Command
- func (cmd *Command) Route(router []string) *Command
- func (cmd *Command) Run(args []string) error
- func (cmd *Command) RunWith(args []string, writer io.Writer, resp http.ResponseWriter, ...) error
- func (cmd *Command) Serve(listeners ...net.Listener) (err error)
- func (cmd *Command) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (cmd *Command) SetIsServer(yes bool)
- func (cmd *Command) SubRoute(router []string) (*Command, int)
- func (cmd *Command) Suggestions(path string) []string
- func (cmd *Command) Usage(ctx *Context) string
- type CommandFunc
- type CommandTree
- type Context
- func (ctx *Context) Args() []string
- func (ctx *Context) Argv() interface{}
- func (ctx *Context) Color() *color.Color
- func (ctx *Context) Command() *Command
- func (ctx *Context) FormValues() url.Values
- func (ctx *Context) GetArgvAt(argv interface{}, i int) error
- func (ctx *Context) GetArgvList(curr interface{}, parents ...interface{}) error
- func (ctx *Context) IsSet(flag string, aliasFlags ...string) bool
- func (ctx *Context) JSON(obj interface{}) *Context
- func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) *Context
- func (ctx *Context) JSONIndentln(obj interface{}, prefix, indent string) *Context
- func (ctx *Context) JSONln(obj interface{}) *Context
- func (ctx *Context) NArg() int
- func (ctx *Context) NOpt() int
- func (ctx *Context) NativeArgs() []string
- func (ctx *Context) Path() string
- func (ctx *Context) RootArgv() interface{}
- func (ctx *Context) Router() []string
- func (ctx *Context) String(format string, args ...interface{}) *Context
- func (ctx *Context) Usage() string
- func (ctx *Context) Write(data []byte) (n int, err error)
- func (ctx *Context) WriteUsage()
- func (ctx *Context) Writer() io.Writer
- type Counter
- type CounterDecoder
- type Decoder
- type Encoder
- type FlagParser
- type FlagParserCreator
- type Helper
- type Helper2
- type JSONConfigFileParser
- type JSONFileParser
- type JSONParser
- type NumCheckFunc
- type SliceDecoder
- type URLParser
- type UsageFunc
- type UsageStyle
- type Validator
Examples ¶
Constants ¶
const DefaultEditor = "vim"
Variables ¶
var ExitError = exitError{}
ExitError is a special error, should be ignored but return
var GetEditor func() (string, error)
GetEditor sets callback to get editor program
Functions ¶
func Daemon ¶
Daemon startup app as a daemon process, success if result from stderr has prefix successPrefix
func HelpCommandFn ¶
HelpCommandFn implements buildin help command function
func IsValidCommandName ¶
IsValidCommandName validates name of command
func LaunchEditor ¶
LaunchEditor launchs the specified editor with a random filename
func Parse ¶
Parse parses args to object argv
Example (DefaultValue) ¶
This example demonstrates how to use default value
package main
import (
"os"
"github.com/akeylesslabs/cli"
)
func main() {
type argT1 struct {
Port int `cli:"p,port" usage:"listening port" dft:"8080"`
}
type argT2 struct {
Port int `cli:"p,port" usage:"listening port" dft:"$CLI_TEST_HTTP_PORT"`
}
type argT3 struct {
Port int `cli:"p,port" usage:"listening port" dft:"$CLI_TEST_HTTP_PORT+800"`
}
type argT4 struct {
DevDir string `cli:"dir" usage:"develope directory" dft:"$CLI_TEST_DEV_PARENT_DIR/dev"`
}
type argT5 struct {
Port int `cli:"p,port" usage:"listening port" dft:"1" ignoreDft:"true"`
}
type argT6 struct {
Port int `cli:"p,port" usage:"listening port" dft:"1" ignoreDft:""`
}
type argT7 struct {
Port int `cli:"p,port" usage:"listening port" dft:"1" ignoreDft:""`
}
type argT8 struct {
Port int `cli:"p,port" usage:"listening port" dft:"1" ignoreDft:"not a bool"`
}
os.Setenv("CLI_TEST_DEV_PARENT_DIR", "/home")
os.Setenv("CLI_TEST_HTTP_PORT", "8000")
for _, tt := range []struct {
argv interface{}
args []string
}{
{new(argT1), []string{"app"}},
{new(argT2), []string{"app"}},
{new(argT3), []string{"app"}},
{new(argT4), []string{"app"}},
{new(argT4), []string{"app", "--dir=/dev"}},
{new(argT5), []string{"app"}},
{new(argT6), []string{"app"}},
{new(argT7), []string{"app"}},
{new(argT8), []string{"app"}},
} {
cli.RunWithArgs(tt.argv, tt.args, func(ctx *cli.Context) error {
ctx.String("argv=%v\n", ctx.Argv())
return nil
})
}
}
Output: argv=&{8080} argv=&{8000} argv=&{8800} argv=&{/home/dev} argv=&{/dev} argv=&{0} argv=&{1} argv=&{1} argv=&{1}
Example (ShortAndLongFlagName) ¶
This example demonstrates how to use short and long format flag
package main
import (
"github.com/akeylesslabs/cli"
)
func main() {
// argument object
type argT struct {
Port int `cli:"p,port" usage:"listening port"`
}
for _, args := range [][]string{
[]string{"app", "-p", "8080"},
[]string{"app", "-p8081"},
[]string{"app", "-p=8082"},
[]string{"app", "--port", "8083"},
[]string{"app", "--port=8084"},
} {
cli.RunWithArgs(&argT{}, args, func(ctx *cli.Context) error {
argv := ctx.Argv().(*argT)
ctx.String("port=%d\n", argv.Port)
return nil
})
}
}
Output: port=8080 port=8081 port=8082 port=8083 port=8084
Example (SliceAndMap) ¶
This example demonstrates to use Slice and Map
package main
import (
"github.com/akeylesslabs/cli"
)
func main() {
type argT1 struct {
Slice []uint32 `cli:"U,u32-slice" usage:"uint32 slice"`
}
type argT2 struct {
Slice []string `cli:"S,str-slice" usage:"string slice"`
}
type argT3 struct {
Slice []bool `cli:"B,bool-slice" usage:"boolean slice"`
}
type argT4 struct {
MapA map[string]int `cli:"A" usage:"string => int"`
MapB map[int]int `cli:"B" usage:"int => int"`
MapC map[int]string `cli:"C" usage:"int => string"`
MapD map[string]bool `cli:"D" usage:"string => bool"`
}
for _, tt := range []struct {
argv interface{}
args []string
}{
{new(argT1), []string{"app", "-U1", "-U2"}},
{new(argT1), []string{"app", "-U", "1", "-U", "2"}},
{new(argT1), []string{"app", "--u32-slice", "1", "--u32-slice", "2"}},
{new(argT2), []string{"app", "-Shello", "-Sworld"}},
{new(argT2), []string{"app", "-S", "hello", "-S", "world"}},
{new(argT2), []string{"app", "--str-slice", "hello", "--str-slice", "world"}},
{new(argT3), []string{"app", "-Btrue", "-Bfalse"}},
{new(argT3), []string{"app", "-B", "true", "-B", "false"}},
{new(argT3), []string{"app", "--bool-slice", "true", "--bool-slice", "false"}},
{new(argT4), []string{"app",
"-Ax=1",
"-B", "1=2",
"-C1=a",
"-Dx",
}},
} {
cli.RunWithArgs(tt.argv, tt.args, func(ctx *cli.Context) error {
ctx.String("argv=%v\n", ctx.Argv())
return nil
})
}
}
Output: argv=&{[1 2]} argv=&{[1 2]} argv=&{[1 2]} argv=&{[hello world]} argv=&{[hello world]} argv=&{[hello world]} argv=&{[true false]} argv=&{[true false]} argv=&{[true false]} argv=&{map[x:1] map[1:2] map[1:a] map[x:true]}
func ReadJSONConfigFromFile ¶ added in v0.0.3
ReadJSONConfigFromFile is similar to ReadJSONFromFile, but allows reading file from where the executable file resides as well
func ReadJSONFromFile ¶ added in v0.0.2
ReadJSONFromFile is similar to ReadJSON, but read from file
func RegisterFlagParser ¶
func RegisterFlagParser(name string, creator FlagParserCreator)
RegisterFlagParser registers FlagParserCreator by name
Example ¶
This example demonstrates how to use custom parser
package main
import (
"reflect"
"github.com/akeylesslabs/cli"
)
type myParser struct {
ptr interface{}
}
func newMyParser(ptr interface{}) cli.FlagParser {
return &myParser{ptr}
}
// Parse implements FlagParser.Parse interface
func (parser *myParser) Parse(s string) error {
typ := reflect.TypeOf(parser.ptr)
val := reflect.ValueOf(parser.ptr)
if typ.Kind() == reflect.Ptr {
kind := reflect.Indirect(val).Type().Kind()
if kind == reflect.Struct {
typElem, valElem := typ.Elem(), val.Elem()
numField := valElem.NumField()
for i := 0; i < numField; i++ {
_, valField := typElem.Field(i), valElem.Field(i)
if valField.Kind() == reflect.Int && valField.CanSet() {
valField.SetInt(2)
}
if valField.Kind() == reflect.String && valField.CanSet() {
valField.SetString("B")
}
}
}
}
return nil
}
type config3 struct {
A int
B string
}
func main() {
// register parser factory function
cli.RegisterFlagParser("myparser", newMyParser)
type argT struct {
Cfg3 config3 `cli:"cfg3" parser:"myparser"`
}
args := []string{"app",
`--cfg3`, `hello`,
}
cli.RunWithArgs(new(argT), args, func(ctx *cli.Context) error {
ctx.JSON(ctx.Argv())
return nil
})
}
Output: {"Cfg3":{"A":2,"B":"B"}}
func Run ¶
func Run(argv interface{}, fn CommandFunc, descs ...string) int
Run runs a single command app
Example ¶
package main
import (
"github.com/akeylesslabs/cli"
)
func main() {
type argT struct {
Flag string `cli:"f"`
}
cli.RunWithArgs(new(argT), []string{"app", "-f=xxx"}, func(ctx *cli.Context) error {
argv := ctx.Argv().(*argT)
ctx.String("flag: %s\n", argv.Flag)
return nil
})
}
Output: flag: xxx
func RunWithArgs ¶
func RunWithArgs(argv interface{}, args []string, fn CommandFunc, descs ...string) int
RunWithArgs is similar to Run, but with args instead of os.Args
Types ¶
type AddrWithShort
deprecated
type AddrWithShort struct {
Host string `cli:"H,host" usage:"specify host" dft:"0.0.0.0"`
Port uint16 `cli:"p,port" usage:"specify port" dft:"8080"`
}
Deprecated: AddrWithShort is builtin host,port flag contains short flag
func (AddrWithShort) ToString
deprecated
func (addr AddrWithShort) ToString() string
Deprecated: ToString ...
type AutoHelper ¶
type AutoHelper interface {
AutoHelp() bool
}
AutoHelper represents interface for showing help information automatically
type Command ¶
type Command struct {
Name string // Command name
Aliases []string // Command aliases name
Desc string // Command abstract
Text string // Command detail description
Hidden bool // should hide command in help menus
// CanSubRoute indicates whether to allow incomplete subcommand routing
// e.g.
//
// ./app cmd1 cmd2
//
// Suppose cmd2 not found in sub-commands of cmd1. Command cmd1 would be
// executed if cmd1.CanSubRoute is true, an error returned otherwise.
CanSubRoute bool
// NoHook indicates whether skip hooked functions
NoHook bool
// Global indicates whether it's argv object should be used to sub-command
Global bool
// functions
Fn CommandFunc // Command handler
UsageFn UsageFunc // Custom usage function
Argv ArgvFunc // Command argument factory function
NumArg NumCheckFunc // NumArg check number of args
NumOption NumCheckFunc // NumOption check num of options
HTTPRouters []string
HTTPMethods []string
// hooks for current command
OnBefore func(*Context) error
OnAfter func(*Context) error
// hooks for all commands if current command is root command
OnRootPrepareError func(error) error
OnRootBefore func(*Context) error
OnRootAfter func(*Context) error
// contains filtered or unexported fields
}
Command is the top-level instance in command-line app
Example ¶
package main
import (
"github.com/akeylesslabs/cli"
)
func main() {
root := &cli.Command{
Name: "app",
}
type childT struct {
S string `cli:"s" usage:"string flag"`
B bool `cli:"b" usage:"boolean flag"`
}
root.Register(&cli.Command{
Name: "child",
Aliases: []string{"sub"},
Desc: "child command",
Text: "detailed description for command",
Argv: func() interface{} { return new(childT) },
CanSubRoute: true,
NoHook: true,
NumArg: cli.ExactN(1),
HTTPRouters: []string{"/v1/child", "/v2/child"},
HTTPMethods: []string{"GET", "POST"},
OnRootPrepareError: func(err error) error {
return err
},
OnBefore: func(ctx *cli.Context) error {
ctx.String("OnBefore\n")
return nil
},
OnAfter: func(ctx *cli.Context) error {
ctx.String("OnAfter\n")
return nil
},
OnRootBefore: func(ctx *cli.Context) error {
ctx.String("OnRootBefore\n")
return nil
},
OnRootAfter: func(ctx *cli.Context) error {
ctx.String("OnRootAfter\n")
return nil
},
Fn: func(ctx *cli.Context) error {
return nil
},
})
}
func HelpCommand ¶
HelpCommand returns a buildin help command
func Root ¶
func Root(root *Command, forest ...*CommandTree) *Command
Root registers forest for root and returns root
func (*Command) ChildrenDescriptions ¶
ChildrenDescriptions returns all children's brief infos by one string
func (*Command) ListChildren ¶
ListChildren returns all names of command children
func (*Command) ListenAndServeHTTP ¶
ListenAndServeHTTP set IsServer flag with true and startup http service
func (*Command) RegisterFunc ¶
func (cmd *Command) RegisterFunc(name string, fn CommandFunc, argvFn ArgvFunc) *Command
RegisterFunc registers handler as child command
func (*Command) RegisterHTTP ¶
RegisterHTTP init HTTPRouters for command
func (*Command) RegisterTree ¶
func (cmd *Command) RegisterTree(forest ...*CommandTree)
RegisterTree registers a command tree
func (*Command) RunWith ¶
func (cmd *Command) RunWith(args []string, writer io.Writer, resp http.ResponseWriter, httpMethods ...string) error
RunWith runs the command with args and writer,httpMethods
func (*Command) ServeHTTP ¶
func (cmd *Command) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements HTTP handler
func (*Command) SetIsServer ¶
SetIsServer sets command running mode(server or not)
func (*Command) Suggestions ¶
Suggestions returns all similar commands
type CommandTree ¶
type CommandTree struct {
// contains filtered or unexported fields
}
CommandTree represents a tree of commands
type Context ¶
type Context struct {
HTTPRequest *http.Request
HTTPResponse http.ResponseWriter
// contains filtered or unexported fields
}
Context provides running context
func (*Context) Args ¶
Args returns free args `./app hello world -a=1 abc xyz` will return ["abc" "xyz"]
func (*Context) FormValues ¶
FormValues returns parsed args as url.Values
func (*Context) GetArgvList ¶ added in v0.0.2
GetArgvList gets argv objects
func (*Context) JSONIndent ¶
JSONIndent writes pretty json string of obj to writer
func (*Context) JSONIndentln ¶
JSONIndentln writes pretty json string of obj end with "\n" to writer
func (*Context) NativeArgs ¶
NativeArgs returns native args `./app hello world -a --xyz=1` will return ["-a" "--xyz=1"]
func (*Context) Path ¶
Path returns full command name `./app hello world -a --xyz=1` will returns "hello world"
func (*Context) RootArgv ¶ added in v0.0.2
func (ctx *Context) RootArgv() interface{}
RootArgv returns parsed root args object
func (*Context) Router ¶
Router returns full command name with string array `./app hello world -a --xyz=1` will returns ["hello" "world"]
type Counter ¶ added in v0.0.2
type Counter struct {
// contains filtered or unexported fields
}
Counter implements counter decoder
type CounterDecoder ¶ added in v0.0.2
type CounterDecoder interface {
Decoder
IsCounter()
}
CounterDecoder represents an counter decoder
type Encoder ¶
type Encoder interface {
Encode() string
}
Encoder represents an interface which encodes to string
type FlagParser ¶
FlagParser represents a parser for parsing flag
Example ¶
This example demonstrates how to use builtin praser(json,jsonfile)
package main
import (
"io/ioutil"
"os"
"github.com/akeylesslabs/cli"
)
type config1 struct {
A string
B int
}
type config2 struct {
C string
D bool
}
func main() {
type argT struct {
Cfg1 config1 `cli:"cfg1" parser:"json"`
Cfg2 config2 `cli:"cfg2" parser:"jsonfile"`
}
jsonfile := "1.json"
args := []string{"app",
`--cfg1`, `{"A": "hello", "B": 2}`,
`--cfg2`, jsonfile,
}
ioutil.WriteFile(jsonfile, []byte(`{"C": "world", "D": true}`), 0644)
defer os.Remove(jsonfile)
cli.RunWithArgs(new(argT), args, func(ctx *cli.Context) error {
ctx.JSON(ctx.Argv())
return nil
})
}
Output: {"Cfg1":{"A":"hello","B":2},"Cfg2":{"C":"world","D":true}}
type FlagParserCreator ¶
type FlagParserCreator func(ptr interface{}) FlagParser
FlagParserCreator represents factory function of FlagParser
type Helper ¶
type Helper struct {
Help bool `cli:"!h,help" usage:"display help information" json:"-"`
}
Helper is builtin Help flag
Example ¶
package main
import (
"github.com/akeylesslabs/cli"
)
func main() {
type argT struct {
cli.Helper
}
cli.RunWithArgs(new(argT), []string{"app", "-h"}, func(ctx *cli.Context) error {
return nil
})
}
Output: Options: -h, --help display help information
type Helper2 ¶ added in v0.0.3
type Helper2 struct {
Help bool `cli:"!h,help" usage:"Display help information" json:"-"`
}
Helper2 is builtin Help flag
type JSONConfigFileParser ¶ added in v0.0.3
type JSONConfigFileParser struct {
// contains filtered or unexported fields
}
JSON config file parser
func (JSONConfigFileParser) Parse ¶ added in v0.0.3
func (p JSONConfigFileParser) Parse(s string) error
type JSONFileParser ¶
type JSONFileParser struct {
// contains filtered or unexported fields
}
JSON file parser
func (JSONFileParser) Parse ¶
func (p JSONFileParser) Parse(s string) error
type JSONParser ¶
type JSONParser struct {
// contains filtered or unexported fields
}
JSON parser
func (JSONParser) Parse ¶
func (p JSONParser) Parse(s string) error
type NumCheckFunc ¶ added in v0.0.2
NumCheckFunc represents function type which used to check num of args
func AtLeast ¶ added in v0.0.2
func AtLeast(num int) NumCheckFunc
AtLeast returns a NumCheckFunc which checks if a number is greater than or equal to num
func AtMost ¶ added in v0.0.2
func AtMost(num int) NumCheckFunc
AtMost returns a NumCheckFunc which checks if a number is less than or equal to num
func ExactN ¶ added in v0.0.2
func ExactN(num int) NumCheckFunc
ExactN returns a NumCheckFunc which checks if a number is equal to num
type SliceDecoder ¶ added in v0.0.2
type SliceDecoder interface {
Decoder
DecodeSlice()
}
SliceDecoder represents an interface which decodes string as slice
type URLParser ¶ added in v0.0.2
type URLParser struct {
// contains filtered or unexported fields
}
URL parser
type UsageFunc ¶ added in v0.0.2
type UsageFunc func() string
UsageFunc represents custom function of usage
type UsageStyle ¶
type UsageStyle int32
UsageStyle is style of usage
const ( // NormalStyle : left-right NormalStyle UsageStyle = iota // DenseNormalStyle : left-right, too DenseNormalStyle // ManualStyle : up-down ManualStyle // DenseManualStyle : up-down, too DenseManualStyle )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
_examples
|
|
|
001-hello
command
|
|
|
002-flag
command
|
|
|
003-required-flag
command
|
|
|
004-default-flag
command
|
|
|
005-slice
command
|
|
|
006-map
command
|
|
|
007-force-flag
command
|
|
|
008-child-command
command
|
|
|
009-auto-helper
command
|
|
|
010-validator
command
|
|
|
011-prompt-and-password
command
|
|
|
012-decoder
command
|
|
|
013-pidfile
command
|
|
|
014-time-and-duration
command
|
|
|
015-file
command
|
|
|
016-parser
command
|
|
|
017-jsonfile
command
|
|
|
018-custom-parser
command
|
|
|
019-hooks
command
|
|
|
020-daemon
command
|
|
|
021-editor
command
|
|
|
022-custom-editor
command
|
|
|
023-tree
command
|
|
|
024-multi-command
command
|
|
|
025-rpc
command
|
|
|
026-http
command
|
|
|
027-global-option
command
|
|
|
028-reader
command
|
|
|
029-writer
command
|
|
|
030-counter
command
|
|
|
031-newline-after-usage
command
|
|
|
032-jsoncfg
command
|
|
|
cmd
|
|
|
clint
command
|
|
|
yocli
command
|
|
