项目作者: corpix

项目描述 :
Addon for github.com/urfave/cli to generate flags from structs and set flags data into structs
高级语言: Go
项目地址: git://github.com/corpix/clistruct.git
创建时间: 2017-04-17T21:40:47Z
项目社区:https://github.com/corpix/clistruct

开源协议:MIT License

下载


clistruct

Build Status

Go struct mapper for urfave/cli.

Mapping what?

  • Structure fields into flag declarations
  • Parsed flags values into structure fields

Limitations

  • Has no support for github.com/urfave/cli.Global* getters(idk how to map them, don’t think you will ever need to do this, if you need then tell me your case)
  • You can’t pass default value for generic at this time, clear solution required(at this time it will return an error about incompatible types)

Also, reflection is full of shit so… there could be bugs.
Feel free to send pull requests or open an issue if you have problems.

Example

Let’s write a simple program which will accept two special flags:

  • --debug
  • --say
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/corpix/clistruct"
  5. "github.com/urfave/cli"
  6. )
  7. var (
  8. flags = &Flags{}
  9. )
  10. type Flags struct {
  11. Debug bool `usage:"Enable debug mode"`
  12. Say string `usage:"Tell me what to say" value:"I could say nothing"`
  13. }
  14. func rootAction(context *cli.Context) error {
  15. if flags.Debug {
  16. fmt.Println("I am in debug mode")
  17. }
  18. fmt.Println(
  19. "Here is what I say:",
  20. flags.Say,
  21. )
  22. return nil
  23. }
  24. func main() {
  25. cliFlags, err := clistruct.FlagsFromStruct(flags)
  26. if err != nil {
  27. panic(err)
  28. }
  29. app := cli.NewApp()
  30. app.Flags = cliFlags
  31. app.Before = func(context *cli.Context) error {
  32. return clistruct.FlagsToStruct(context, flags)
  33. }
  34. app.Action = rootAction
  35. app.RunAndExitOnError()
  36. }

Now let’s run it:

  1. go run examples/simple/main.go --say="hello"
  2. Here is what I say: hello

We define a bool --debug flag, let’s try to run application with it:

  1. go run examples/simple/main.go --say="hello" --debug
  2. I am in debug mode
  3. Here is what I say: hello

That’s it. Little summary:

  • You could use FlagsFromStruct to construct flags from the structure.
  • You could use FlagsToStruct to write parsed flags into the structure.

License

MIT