Skip to content

mmatczuk/anyflag

Repository files navigation

Anyflag

Build Status Go Report Card

Anyflag is an implementation of Cobra pflag.Value and pflag.SliceValue interfaces using Go Generics.

To bind your custom type to a flag, all you have to do is specify the value type and parser function, and you are done, no boilerplate.

It supports any type including, but not limited to: enums, maps, slices, structs, struct pointers.

It also supports defining custom String() functions to redact passwords, see redact example.

Installation

go get github.com/mmatczuk/anyflag

Examples

This example shows how anytype can be used for JSON encoded maps.

func parseJSONMap(val string) (map[string]interface{}, error) {
	var m map[string]interface{}
	return m, json.Unmarshal([]byte(val), &m)
}

func newCommand() *cobra.Command {
	var m map[string]interface{}

	cmd := &cobra.Command{
		Use: "json-map",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Fprintln(cmd.OutOrStdout(), m)
		},
	}

	fs := cmd.Flags()
	value := anyflag.NewValue[map[string]interface{}](nil, &m, parseJSONMap)

	fs.VarP(value, "map", "", "map")

	return cmd
}

func main() {
	newCommand().Execute()
}

More examples can be found in examples directory.

License

This project is based on spf13/pflag licensed under the BSD 3-Clause "New" or "Revised" License

About

Generic implementation of Cobra Value and SliceValue types

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages