Merge pull request #7708 from SvenDowideit/programatic-usage-options

add the [OPTIONS] string automatically if there are flags defined
This commit is contained in:
Victor Vieux 2014-08-27 16:40:17 -07:00
commit 241f52bc17
2 changed files with 46 additions and 0 deletions

View file

@ -472,6 +472,23 @@ var Usage = func() {
PrintDefaults()
}
// FlagCount returns the number of flags that have been defined.
func (f *FlagSet) FlagCount() int { return len(f.formal) }
// FlagCountUndeprecated returns the number of undeprecated flags that have been defined.
func (f *FlagSet) FlagCountUndeprecated() int {
count := 0
for _, flag := range sortFlags(f.formal) {
for _, name := range flag.Names {
if name[0] != '#' {
count++
break
}
}
}
return count
}
// NFlag returns the number of flags that have been set.
func (f *FlagSet) NFlag() int { return len(f.actual) }

View file

@ -428,3 +428,32 @@ func TestHelp(t *testing.T) {
t.Fatal("help was called; should not have been for defined help flag")
}
}
// Test the flag count functions.
func TestFlagCounts(t *testing.T) {
fs := NewFlagSet("help test", ContinueOnError)
var flag bool
fs.BoolVar(&flag, []string{"flag1"}, false, "regular flag")
fs.BoolVar(&flag, []string{"#deprecated1"}, false, "regular flag")
fs.BoolVar(&flag, []string{"f", "flag2"}, false, "regular flag")
fs.BoolVar(&flag, []string{"#d", "#deprecated2"}, false, "regular flag")
fs.BoolVar(&flag, []string{"flag3"}, false, "regular flag")
fs.BoolVar(&flag, []string{"g", "#flag4", "-flag4"}, false, "regular flag")
if fs.FlagCount() != 10 {
t.Fatal("FlagCount wrong. ", fs.FlagCount())
}
if fs.FlagCountUndeprecated() != 4 {
t.Fatal("FlagCountUndeprecated wrong. ", fs.FlagCountUndeprecated())
}
if fs.NFlag() != 0 {
t.Fatal("NFlag wrong. ", fs.NFlag())
}
err := fs.Parse([]string{"-fd", "-g", "-flag4"})
if err != nil {
t.Fatal("expected no error for defined -help; got ", err)
}
if fs.NFlag() != 4 {
t.Fatal("NFlag wrong. ", fs.NFlag())
}
}