package main
import (
"github.com/Masterminds/cookoo"
"github.com/Masterminds/cookoo/cli"
"github.com/Masterminds/cookoo/fmt"
"flag"
)
const (
Summary = "A Hello World program"
Description = `This program writes Hello World to standard output.
With the -a flag, the second word can be replaced by an artitary string.
`
)
func main() {
reg, router, cxt := cookoo.Cookoo()
flags := flag.NewFlagSet("global", flag.PanicOnError)
flags.Bool("h", false, "Show help text")
flags.String("a", "World", "A string to place after 'Hello'")
reg.Route("hello", "A Hello World route").
Does(fmt.Printf, "_").
Using("format").WithDefault("Hello %s!\n").
Using("0").From("cxt:a")
cli.New(reg, router, cxt).Help(Summary, Description, flags).Run("hello")
}
go run main.go
Hello World!
go run main.go -h
SUMMARY
=======
A Hello World program
USAGE
=====
This program writes Hello World to standard output.
With the -a flag, the second word can be replaced by an artitary string.
FLAGS
=====
-a: A string to place after 'Hello' (Default: 'World')
-h: Show help text (Default: 'false')
go run main.go -a You
Hello You!
reg.Route("hello", "A Hello World route").
Does(fmt.Printf, "_").
Using("format").WithDefault("Hello %s!\n").
Using("0").From("cxt:a")
reg.Route("goodbye", "A Goodbye World route").
Does(fmt.Printf, "_").
Using("format").WithDefault("Goodbye %s!\n").
Using("0").From("cxt:a")
go run main.go -a Matt hello
Hello Matt!
go run main.go -a Matt goodbye
Goodbye Matt!
但是,如果go run main.go goodbye -a Matt
输出就是Goodbye World!这是为什么呢?
这是因为,在command line的不同位置,flag的类型可能是global类型的,或者subcommand 类型的。
go run main.go [GLOBAL_FLAGS] subcommand [LOCAL_FLAGS]
global类型的flag可以在整个app中共享,local flag只能对指定的subcommand用。
$ go run main.go hello
Hello World!
$ go run main.go hello -s Hi
Hi World!
$ go run main.go -a You hello
Hello You!
$ go run main.go -a You hello -s Hi
Hi You!
让我们来看看,做同样的事情的另外一种实现方式。
1234567891011
reg.Route("hello", "A Hello World route").
Does(cli.ShiftArgs, "cmd").
Using("args").WithDefault("runner.Args").
Using("n").WithDefault(1).
Does(cli.ParseArgs, "extras").
Using("flagset").WithDefault(helloFlags).
Using("args").From("cxt:runner.Args").
Does(fmt.Printf, "_").
Using("format").WithDefault("%s %s!\n").
Using("0").From("cxt:s").
Using("1").From("cxt:a")
这里没有了之前的设置subcommand.WithDefault的true。而是通过移动参数的形式。
go run main.go -a matt hello -s hi
这样会给os.Args设置成这样:[]string{ “-a”, “matt”, “hello”, “-s”, “hi”}
当程序第一次跑的时候,会把global flags提取出来,把剩余的放入runner.Args。类似于cxt.Put("runner.Args", []string{"hello", "-s", "hi"}),但是,当hello command run的时候,我们希望获得他自己的flag,但是hello却是第一个参数,所以,我们要把这个移动一下,就有了那个cli.ShiftArgs,那段代码的意思就是,把第一个参数放入cmd,剩下的参数放入到cxt:runner.Args,接下来的就和上个实现基本一致了。这个方法即可以用来调试,又可以用来定义更多的参数。