Skip to content

Latest commit

 

History

History
99 lines (70 loc) · 2.13 KB

README.md

File metadata and controls

99 lines (70 loc) · 2.13 KB

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
package main

import (
	"fmt"

	"github.com/corpix/clistruct"
	"github.com/urfave/cli"
)

var (
	flags = &Flags{}
)

type Flags struct {
	Debug bool   `usage:"Enable debug mode"`
	Say   string `usage:"Tell me what to say" value:"I could say nothing"`
}

func rootAction(context *cli.Context) error {
	if flags.Debug {
		fmt.Println("I am in debug mode")
	}

	fmt.Println(
		"Here is what I say:",
		flags.Say,
	)

	return nil
}

func main() {
	cliFlags, err := clistruct.FlagsFromStruct(flags)
	if err != nil {
		panic(err)
	}

	app := cli.NewApp()
	app.Flags = cliFlags
	app.Before = func(context *cli.Context) error {
		return clistruct.FlagsToStruct(context, flags)
	}
	app.Action = rootAction

	app.RunAndExitOnError()
}

Now let's run it:

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

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

go run examples/simple/main.go --say="hello" --debug
I am in debug mode
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