Skip to content

Commit

Permalink
Add countable interface
Browse files Browse the repository at this point in the history
  • Loading branch information
dearchap authored and meatballhat committed Oct 3, 2022
1 parent 6b0a3e8 commit a509290
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
8 changes: 3 additions & 5 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
7 changes: 7 additions & 0 deletions flag_bool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit a509290

Please sign in to comment.