# README
go-flags
go-flags is a library that provides pflag.FlagSet objects for cobra commands.
Installation
This package is available through go get
:
go get github.com/gildas/go-flags
Usage
EnumFlag
You can use the EnumFlag
to define a flag that can only take a set of predefined values:
cmd := &cobra.Command{
Use: "myapp",
. . .
}
state := flags.NewEnumFlag("+one", "two", "three")
cmd.Flags().Var(state, "state", "State of the flag")
_ = cmd.RegisterFlagCompletionFunc("state", state.CompletionFunc("state"))
As you can see, the EnumFlag
is created with a list of strings that are the only values the flag can take. The RegisterFlagCompletionFunc
is used to provide completion for the flag.
The default value is prepended with a +
.
Instead of values, you can provided instead a function that will be called to get the list of allowed values:
cmd := &cobra.Command{
Use: "myapp",
. . .
}
state := flags.NewEnumFlagWithFunc("one", func(context.Context, *cobra.Command, []string) []string {
return []string{"one", "two", "three"}
})
cmd.Flags().Var(state, "state", "State of the flag")
_ = cmd.RegisterFlagCompletionFunc("state", state.CompletionFunc("state"))
Note that the default value is not prepended with a +
in this case.
EnumSliceFlag
You can use the EnumSliceFlag
to define a flag that can only take a set of predefined values:
cmd := &cobra.Command{
Use: "myapp",
. . .
}
state := flags.NewEnumSliceFlag("+one", "+two", "three")
cmd.Flags().Var(state, "state", "State of the flag")
_ = cmd.RegisterFlagCompletionFunc("state", state.CompletionFunc("state"))
The default values are prepended with a +
.
If all values can be provided with an all
value, you can use:
cmd := &cobra.Command{
Use: "myapp",
. . .
}
state := flags.NewEnumSliceFlagWithAllAllowed("one", "two", "three")
cmd.Flags().Var(state, "state", "State of the flag")
_ = cmd.RegisterFlagCompletionFunc("state", state.CompletionFunc("state"))
Note that there is no need to add the all
value to the list of allowed values.