cli: github.com/mkideal/cli Index | Examples | Files | Directories

package cli

import "github.com/mkideal/cli"

This is a HelloWorld example

Code:

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

Examples

Package Files

builtin.go cli.go cliutil.go coder.go command.go context.go editor.go errors.go flag.go flag_set.go fuzzy.go http.go parser.go tag.go tagm.go

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

func Daemon Uses

func Daemon(ctx *Context, successPrefix string) error

Daemon startup app as a daemon process, success if result from stderr has prefix successPrefix

func DaemonResponse Uses

func DaemonResponse(resp string)

DaemonResponse output response to stderr

func HelpCommandFn Uses

func HelpCommandFn(ctx *Context) error

HelpCommandFn implements buildin help command function

func IsValidCommandName Uses

func IsValidCommandName(commandName string) bool

IsValidCommandName validates name of command

func LaunchEditor Uses

func LaunchEditor(editor string) (content []byte, err error)

LaunchEditor launchs the specified editor with a random filename

func Parse Uses

func Parse(args []string, argv interface{}) error

Parse parses args to object argv

This example demonstrates how to use default value

Code:

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"`
}

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"}},
} {
    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}

This example demonstrates how to use short and long format flag

Code:

// 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

This example demonstrates to use Slice and Map

Code:

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 ReadJSON Uses

func ReadJSON(r io.Reader, argv interface{}) error

ReadJSON reads data as a json structure into argv

func ReadJSONConfigFromFile Uses

func ReadJSONConfigFromFile(filename string, argv interface{}) error

ReadJSONConfigFromFile is similar to ReadJSONFromFile, but allows reading file from where the executable file resides as well

func ReadJSONFromFile Uses

func ReadJSONFromFile(filename string, argv interface{}) error

ReadJSONFromFile is similar to ReadJSON, but read from file

func RegisterFlagParser Uses

func RegisterFlagParser(name string, creator FlagParserCreator)

RegisterFlagParser registers FlagParserCreator by name

This example demonstrates how to use custom parser

Code:

// 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 Uses

func Run(argv interface{}, fn CommandFunc, descs ...string) int

Run runs a single command app

Code:

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 Uses

func RunWithArgs(argv interface{}, args []string, fn CommandFunc, descs ...string) int

RunWithArgs is similar to Run, but with args instead of os.Args

func SetUsageStyle Uses

func SetUsageStyle(style UsageStyle)

SetUsageStyle sets default style

type Addr Uses

type Addr struct {
    Host string `cli:"host" usage:"specify host" dft:"0.0.0.0"`
    Port uint16 `cli:"port" usage:"specify port" dft:"8080"`
}

Deprecated: Addr is builtin host,port flag

func (Addr) ToString Uses

func (addr Addr) ToString() string

Deprecated: ToString ...

type AddrWithShort Uses

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 Uses

func (addr AddrWithShort) ToString() string

Deprecated: ToString ...

type ArgvFunc Uses

type ArgvFunc func() interface{}

ArgvFunc ...

type AutoHelper Uses

type AutoHelper interface {
    AutoHelp() bool
}

AutoHelper represents interface for showing help information automatically

type Command Uses

type Command struct {
    Name    string   // Command name
    Aliases []string // Command aliases name
    Desc    string   // Command abstract
    Text    string   // Command detail description

    // 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

Code:

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 Uses

func HelpCommand(desc string) *Command

HelpCommand returns a buildin help command

func Root Uses

func Root(root *Command, forest ...*CommandTree) *Command

Root registers forest for root and returns root

func (*Command) ChildrenDescriptions Uses

func (cmd *Command) ChildrenDescriptions(prefix, indent string) string

ChildrenDescriptions returns all children's brief infos by one string

func (*Command) IsClient Uses

func (cmd *Command) IsClient() bool

IsClient returns command whether if run as client

func (*Command) IsServer Uses

func (cmd *Command) IsServer() bool

IsServer returns command whether if run as server

func (*Command) ListChildren Uses

func (cmd *Command) ListChildren() []string

ListChildren returns all names of command children

func (*Command) ListenAndServeHTTP Uses

func (cmd *Command) ListenAndServeHTTP(addr string) error

ListenAndServeHTTP set IsServer flag with true and startup http service

func (*Command) Parent Uses

func (cmd *Command) Parent() *Command

Parent returns command's parent

func (*Command) Path Uses

func (cmd *Command) Path() string

Path returns space-separated command full name

func (*Command) RPC Uses

func (cmd *Command) RPC(httpc *http.Client, ctx *Context) error

RPC runs the command from remote

func (*Command) Register Uses

func (cmd *Command) Register(child *Command) *Command

Register registers a child command

func (*Command) RegisterFunc Uses

func (cmd *Command) RegisterFunc(name string, fn CommandFunc, argvFn ArgvFunc) *Command

RegisterFunc registers handler as child command

func (*Command) RegisterHTTP Uses

func (cmd *Command) RegisterHTTP(ctxs ...*Context) error

RegisterHTTP init HTTPRouters for command

func (*Command) RegisterTree Uses

func (cmd *Command) RegisterTree(forest ...*CommandTree)

RegisterTree registers a command tree

func (*Command) Root Uses

func (cmd *Command) Root() *Command

Root returns command's ancestor

func (*Command) Route Uses

func (cmd *Command) Route(router []string) *Command

Route finds command full matching router

func (*Command) Run Uses

func (cmd *Command) Run(args []string) error

Run runs the command with args

func (*Command) RunWith Uses

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) Serve Uses

func (cmd *Command) Serve(listeners ...net.Listener) (err error)

Serve set IsServer with true and serve http with listeners

func (*Command) ServeHTTP Uses

func (cmd *Command) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements HTTP handler

func (*Command) SetIsServer Uses

func (cmd *Command) SetIsServer(yes bool)

SetIsServer sets command running mode(server or not)

func (*Command) SubRoute Uses

func (cmd *Command) SubRoute(router []string) (*Command, int)

SubRoute finds command partial matching router

func (*Command) Suggestions Uses

func (cmd *Command) Suggestions(path string) []string

Suggestions returns all similar commands

func (*Command) Usage Uses

func (cmd *Command) Usage(ctx *Context) string

Usage returns the usage string of command

type CommandFunc Uses

type CommandFunc func(*Context) error

CommandFunc ...

type CommandTree Uses

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

CommandTree represents a tree of commands

func Tree Uses

func Tree(cmd *Command, forest ...*CommandTree) *CommandTree

Tree creates a CommandTree

type Context Uses

type Context struct {
    HTTPRequest  *http.Request
    HTTPResponse http.ResponseWriter
    // contains filtered or unexported fields
}

Context provides running context

func (*Context) Args Uses

func (ctx *Context) Args() []string

Args returns free args `./app hello world -a=1 abc xyz` will return ["abc" "xyz"]

func (*Context) Argv Uses

func (ctx *Context) Argv() interface{}

Argv returns parsed args object

func (*Context) Color Uses

func (ctx *Context) Color() *color.Color

Color returns color instance

func (*Context) Command Uses

func (ctx *Context) Command() *Command

Command returns current command instance

func (*Context) FormValues Uses

func (ctx *Context) FormValues() url.Values

FormValues returns parsed args as url.Values

func (*Context) GetArgvAt Uses

func (ctx *Context) GetArgvAt(argv interface{}, i int) error

GetArgvAt gets the i-th argv object

func (*Context) GetArgvList Uses

func (ctx *Context) GetArgvList(curr interface{}, parents ...interface{}) error

GetArgvList gets argv objects

func (*Context) IsSet Uses

func (ctx *Context) IsSet(flag string, aliasFlags ...string) bool

IsSet determins whether `flag` is set

func (*Context) JSON Uses

func (ctx *Context) JSON(obj interface{}) *Context

JSON writes json string of obj to writer

func (*Context) JSONIndent Uses

func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) *Context

JSONIndent writes pretty json string of obj to writer

func (*Context) JSONIndentln Uses

func (ctx *Context) JSONIndentln(obj interface{}, prefix, indent string) *Context

JSONIndentln writes pretty json string of obj end with "\n" to writer

func (*Context) JSONln Uses

func (ctx *Context) JSONln(obj interface{}) *Context

JSONln writes json string of obj end with "\n" to writer

func (*Context) NArg Uses

func (ctx *Context) NArg() int

NArg returns length of Args

func (*Context) NOpt Uses

func (ctx *Context) NOpt() int

NOpt returns num of options

func (*Context) NativeArgs Uses

func (ctx *Context) NativeArgs() []string

NativeArgs returns native args `./app hello world -a --xyz=1` will return ["-a" "--xyz=1"]

func (*Context) Path Uses

func (ctx *Context) Path() string

Path returns full command name `./app hello world -a --xyz=1` will returns "hello world"

func (*Context) RootArgv Uses

func (ctx *Context) RootArgv() interface{}

RootArgv returns parsed root args object

func (*Context) Router Uses

func (ctx *Context) Router() []string

Router returns full command name with string array `./app hello world -a --xyz=1` will returns ["hello" "world"]

func (*Context) String Uses

func (ctx *Context) String(format string, args ...interface{}) *Context

String writes formatted string to writer

func (*Context) Usage Uses

func (ctx *Context) Usage() string

Usage returns current command's usage with current context

func (*Context) Write Uses

func (ctx *Context) Write(data []byte) (n int, err error)

Write implements io.Writer

func (*Context) WriteUsage Uses

func (ctx *Context) WriteUsage()

WriteUsage writes usage to writer

func (*Context) Writer Uses

func (ctx *Context) Writer() io.Writer

Writer returns writer

type Counter Uses

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

Counter implements counter decoder

func (*Counter) Decode Uses

func (c *Counter) Decode(s string) error

Decode decodes counter from string

func (Counter) IsCounter Uses

func (c Counter) IsCounter()

IsCounter implements method of interface CounterDecoder

func (Counter) Value Uses

func (c Counter) Value() int

Value returns value of counter

type CounterDecoder Uses

type CounterDecoder interface {
    Decoder
    IsCounter()
}

CounterDecoder represents an counter decoder

type Decoder Uses

type Decoder interface {
    Decode(s string) error
}

Decoder represents an interface which decodes string

type Encoder Uses

type Encoder interface {
    Encode() string
}

Encoder represents an interface which encodes to string

type FlagParser Uses

type FlagParser interface {
    Parse(s string) error
}

FlagParser represents a parser for parsing flag

This example demonstrates how to use builtin praser(json,jsonfile)

Code:

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 Uses

type FlagParserCreator func(ptr interface{}) FlagParser

FlagParserCreator represents factory function of FlagParser

type Helper Uses

type Helper struct {
    Help bool `cli:"!h,help" usage:"display help information" json:"-"`
}

Helper is builtin Help flag

Code:

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

func (Helper) AutoHelp Uses

func (h Helper) AutoHelp() bool

AutoHelp implements AutoHelper interface

type Helper2 Uses

type Helper2 struct {
    Help bool `cli:"!h,help" usage:"Display help information" json:"-"`
}

Helper2 is builtin Help flag

func (Helper2) AutoHelp Uses

func (h Helper2) AutoHelp() bool

AutoHelp implements AutoHelper interface

type JSONConfigFileParser Uses

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

JSON config file parser

func (JSONConfigFileParser) Parse Uses

func (p JSONConfigFileParser) Parse(s string) error

type JSONFileParser Uses

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

JSON file parser

func (JSONFileParser) Parse Uses

func (p JSONFileParser) Parse(s string) error

type JSONParser Uses

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

JSON parser

func (JSONParser) Parse Uses

func (p JSONParser) Parse(s string) error

type NumCheckFunc Uses

type NumCheckFunc func(n int) bool

NumCheckFunc represents function type which used to check num of args

func AtLeast Uses

func AtLeast(num int) NumCheckFunc

AtLeast returns a NumCheckFunc which checks if a number is greater than or equal to num

func AtMost Uses

func AtMost(num int) NumCheckFunc

AtMost returns a NumCheckFunc which checks if a number is less than or equal to num

func ExactN Uses

func ExactN(num int) NumCheckFunc

ExactN returns a NumCheckFunc which checks if a number is equal to num

type SliceDecoder Uses

type SliceDecoder interface {
    Decoder
    DecodeSlice()
}

SliceDecoder represents an interface which decodes string as slice

type URLParser Uses

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

URL parser

func (*URLParser) Parse Uses

func (p *URLParser) Parse(s string) error

type UsageFunc Uses

type UsageFunc func() string

UsageFunc represents custom function of usage

type UsageStyle Uses

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
)

func GetUsageStyle Uses

func GetUsageStyle() UsageStyle

GetUsageStyle gets default style

type Validator Uses

type Validator interface {
    Validate(*Context) error
}

Validator validates flag before running command

Directories

PathSynopsis
clil
clis
ext

Package cli imports 28 packages (graph) and is imported by 47 packages. Updated 2019-09-22. Refresh now. Tools for package owners.