enumer icon indicating copy to clipboard operation
enumer copied to clipboard

Add options to implement flag.Value and pflag.Value methods

Open peczenyj opened this issue 9 months ago • 1 comments

Hello

There are two useful interfaces that I often forget to implement when I am using the enumeration types on command line flags

There are two common interfaces:

  • the stdlib https://pkg.go.dev/flag#Value
type Value interface {
	String() string
	Set(string)error
}
  • the 3rd party https://pkg.go.dev/github.com/spf13/pflag#Value
type Value interface {
	String() string
	Set(string)error
        Type() string
}

Since the pflag.Value IS A flag.Value, with one extra method, but not all people what to implement it, I add two new explicit command line flags (disabled by default):

  -flag.value
    	if true, ensure that the enumeration type implements stdlib flag.Value interface. Default: false
  -pflag.value
    	if true, ensure that the enumeration type implements pflag.Value interface, see: https://pkg.go.dev/github.com/spf13/pflag#Value  Default: false

if both are enabled, we will consider only the pflag case.

this patch is incredible helpfut since I often discover that the Value interface is needed in runtime.

Since some tests became more complex to understand, change the signature of the generate method to receive an private option type, a struct, to improve readability and simplify the program flags itself (instead having a lot of global variables)

There are other merge requests to improve tests and stop using deprecated ioutil package, I will not touch on this part again ( see https://github.com/dmarkham/enumer/pull/103 )

In the pflag case, the Type() string method will return all possible string values joined by | -- and this is helpful to quickly understand the options using a notation that is very common. If someone needs to return a different message, they can just use the flag.Value option and create a custom Type() string

peczenyj avatar Mar 21 '25 11:03 peczenyj

conflict solved

peczenyj avatar Aug 16 '25 08:08 peczenyj