Add countable interface

This commit is contained in:
Naveen Gogineni 2022-09-05 19:13:26 -04:00 committed by Dan Buch
parent 6b0a3e80b5
commit a509290e75
Signed by: meatballhat
GPG Key ID: A12F782281063434
3 changed files with 16 additions and 5 deletions

View File

@ -105,13 +105,11 @@ func (cCtx *Context) Lineage() []*Context {
return lineage
}
// NumOccurrences returns the num of occurences of this flag
// Count returns the num of occurences of this flag
func (cCtx *Context) Count(name string) int {
if fs := cCtx.lookupFlagSet(name); fs != nil {
if bf, ok := fs.Lookup(name).Value.(*boolValue); ok {
if bf.count != nil {
return *bf.count
}
if cf, ok := fs.Lookup(name).Value.(Countable); ok {
return cf.Count()
}
}
return 0

View File

@ -124,6 +124,12 @@ type Flag interface {
GetValue() string
}
// Countable is an interface to enable detection of flag values which support
// repetitive flags
type Countable interface {
Count() int
}
func flagSet(name string, flags []Flag) (*flag.FlagSet, error) {
set := flag.NewFlagSet(name, flag.ContinueOnError)

View File

@ -51,6 +51,13 @@ func (b *boolValue) String() string {
func (b *boolValue) IsBoolFlag() bool { return true }
func (b *boolValue) Count() int {
if b.count != nil {
return *b.count
}
return 0
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *BoolFlag) GetValue() string {