Skip to content

flag: prevent BoolWithInverseFlag.String from panicking without a tab#2314

Open
alliasgher wants to merge 2 commits intourfave:mainfrom
alliasgher:fix-bool-with-inverse-string-no-tab
Open

flag: prevent BoolWithInverseFlag.String from panicking without a tab#2314
alliasgher wants to merge 2 commits intourfave:mainfrom
alliasgher:fix-bool-with-inverse-string-no-tab

Conversation

@alliasgher
Copy link
Copy Markdown

Summary

`BoolWithInverseFlag.String()` panics with `slice bounds out of range [-1:]` when the configured `FlagStringer` returns a string that does not contain a tab character.

```go
out := FlagStringer(bif)
i := strings.Index(out, "\t") // -1 when no tab
// ...
out[i:] // panic: slice bounds out of range [-1:]
```

This happens with custom stringers and with the default stringer when the flag doesn't implement `DocGenerationFlag`.

Fix

Clamp the tab index to 0 when no tab is found. The full `FlagStringer` output is then used as the suffix portion of the formatted string, matching the intent of callers using a custom stringer without the usual tab layout.

Fixes #2303

Checklist

  • Test added covering both multi-character and single-character flag names with a no-tab `FlagStringer`
  • Full test suite passes

When FlagStringer returns a string without a tab character,
strings.Index returns -1 and out[-1:] panics with
"slice bounds out of range [-1:]".

Guard against this by clamping the index to 0 when no tab is
found. In that case the entire FlagStringer output is used as
the suffix portion of the formatted string, matching the intent
of callers who use a custom stringer without the usual tab layout.

Fixes urfave#2303

Signed-off-by: alliasgher <alliasgher123@gmail.com>
Splits TestBoolWithInverseFlagStringNoPanicWithNoTabStringer into
multi-character and single-character sub-tests so the `-` vs `--`
prefix branch added by the panic guard is fully covered.

Signed-off-by: alliasgher <alliasgher123@gmail.com>
@alliasgher alliasgher requested a review from a team as a code owner April 15, 2026 12:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BoolWithInverseFlag.String() panics when FlagStringer returns string without tab

1 participant