Skip to content

Commit bc00bd4

Browse files
authored
Merge pull request #2311 from alliasgher/fix-boolwithinverse-string-panic
flag: prevent BoolWithInverseFlag.String from panicking without a tab
2 parents efc6352 + 760eb19 commit bc00bd4

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

flag_bool_with_inverse.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,14 @@ func (bif *BoolWithInverseFlag) String() string {
179179
prefix = "-"
180180
}
181181

182+
// Guard against a FlagStringer that returns a string without a tab (e.g.
183+
// a custom stringer or the default stringer when the flag does not
184+
// implement DocGenerationFlag). In that case treat the entire output as
185+
// the tab-delimited suffix so the slice never goes out of bounds.
186+
if i < 0 {
187+
i = 0
188+
}
189+
182190
return fmt.Sprintf("%s[%s]%s%s", prefix, bif.inversePrefix(), bif.Name, out[i:])
183191
}
184192

flag_bool_with_inverse_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,3 +520,26 @@ func TestBoolWithInverseFlag_SatisfiesVisibleFlagInterface(t *testing.T) {
520520

521521
_ = f.IsVisible()
522522
}
523+
524+
// TestBoolWithInverseFlagStringNoPanicWithNoTabStringer is a regression test for
525+
// https://github.com/urfave/cli/issues/2303.
526+
// BoolWithInverseFlag.String() panicked with "slice bounds out of range [-1:]"
527+
// when the FlagStringer returned a string without a tab character.
528+
func TestBoolWithInverseFlagStringNoPanicWithNoTabStringer(t *testing.T) {
529+
orig := FlagStringer
530+
defer func() { FlagStringer = orig }()
531+
532+
FlagStringer = func(f Flag) string {
533+
return "no tab here"
534+
}
535+
536+
flag := &BoolWithInverseFlag{
537+
Name: "verbose",
538+
}
539+
540+
// Must not panic.
541+
got := flag.String()
542+
if !strings.Contains(got, "verbose") {
543+
t.Errorf("expected String() to contain the flag name, got %q", got)
544+
}
545+
}

0 commit comments

Comments
 (0)