Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions count_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pflag

import (
"os"
"strings"
"testing"
)

Expand Down Expand Up @@ -54,3 +55,32 @@ func TestCount(t *testing.T) {
}
}
}

// Count flags take an optional --flag=N value (NoOptDefVal), so --foo 2
// treats "2" as a positional argument. Help used to print a required-looking
// "count" argument, which implied the space-separated form would work (#267).
func TestCountUsageShowsOptionalValue(t *testing.T) {
f := NewFlagSet("test", ContinueOnError)
var n int
f.CountVar(&n, "foo", "increment")
usage := f.FlagUsages()
if strings.Contains(usage, "--foo count") {
t.Fatalf("usage presents count as a required argument:\n%s", usage)
}
if !strings.Contains(usage, "--foo[=count]") {
t.Fatalf("usage should show optional --foo[=count], got:\n%s", usage)
}

f2 := NewFlagSet("test", ContinueOnError)
var n2 int
f2.CountVar(&n2, "foo", "increment")
if err := f2.Parse([]string{"--foo", "2"}); err != nil {
t.Fatal(err)
}
if n2 != 1 {
t.Fatalf("space-separated --foo 2 should increment once, got %d", n2)
}
if got := f2.Args(); len(got) != 1 || got[0] != "2" {
t.Fatalf("space-separated 2 should remain a positional arg, got %v", got)
}
}
8 changes: 6 additions & 2 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,9 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
varname, usage := UnquoteUsage(flag)
if isNoOptBoolValue(flag.Value) && flag.Value.Type() == "bool" {
line += "[=true|false]"
} else if varname != "" {
} else if varname != "" && !(flag.Value.Type() == "count" && flag.NoOptDefVal != "") {
// Count flags with NoOptDefVal treat a following token as a
// positional argument, so don't print a required-looking type name.
line += " " + varname
}

Expand All @@ -806,7 +808,9 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
case "count":
if flag.NoOptDefVal != "+1" {
if flag.NoOptDefVal == "+1" {
line += "[=count]"
} else {
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
default:
Expand Down
2 changes: 1 addition & 1 deletion flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1477,7 +1477,7 @@ const defaultOutput = ` --A[=true|false] for bootstrapping, a
--custom-with-val custom custom value which has been set from command line while help is shown
--customP custom a VarP with default (default 10)
--maxT timeout set timeout for dial
-v, --verbose count verbosity
-v, --verbose[=count] verbosity
`

// Custom value that satisfies the Value interface.
Expand Down