flag: use strings.Builder instead of concatenating strings

There is a single function in the flag package whose implementation
uses string concatenation instead of the recommended strings.Builder.
The function was last touched before strings.Builder was introduced
in Go 1.10, which explains the old style code. This PR updates
the implementation.

Fixes #45392

Change-Id: Id2d8f1788765a0c4faaeb1e6870914f72b3c8442
GitHub-Last-Rev: 0e12fe3045
GitHub-Pull-Request: golang/go#45393
Reviewed-on: https://go-review.googlesource.com/c/go/+/307329
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Trust: Josh Bleecher Snyder <josharian@gmail.com>
This commit is contained in:
James Fennell 2021-04-05 18:21:59 +00:00 committed by Ian Lance Taylor
parent ee40bb666b
commit 27015152ec

View file

@ -508,31 +508,33 @@ func UnquoteUsage(flag *Flag) (name string, usage string) {
// documentation for the global function PrintDefaults for more information.
func (f *FlagSet) PrintDefaults() {
f.VisitAll(func(flag *Flag) {
s := fmt.Sprintf(" -%s", flag.Name) // Two spaces before -; see next two comments.
var b strings.Builder
fmt.Fprintf(&b, " -%s", flag.Name) // Two spaces before -; see next two comments.
name, usage := UnquoteUsage(flag)
if len(name) > 0 {
s += " " + name
b.WriteString(" ")
b.WriteString(name)
}
// Boolean flags of one ASCII letter are so common we
// treat them specially, putting their usage on the same line.
if len(s) <= 4 { // space, space, '-', 'x'.
s += "\t"
if b.Len() <= 4 { // space, space, '-', 'x'.
b.WriteString("\t")
} else {
// Four spaces before the tab triggers good alignment
// for both 4- and 8-space tab stops.
s += "\n \t"
b.WriteString("\n \t")
}
s += strings.ReplaceAll(usage, "\n", "\n \t")
b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t"))
if !isZeroValue(flag, flag.DefValue) {
if _, ok := flag.Value.(*stringValue); ok {
// put quotes on the value
s += fmt.Sprintf(" (default %q)", flag.DefValue)
fmt.Fprintf(&b, " (default %q)", flag.DefValue)
} else {
s += fmt.Sprintf(" (default %v)", flag.DefValue)
fmt.Fprintf(&b, " (default %v)", flag.DefValue)
}
}
fmt.Fprint(f.Output(), s, "\n")
fmt.Fprint(f.Output(), b.String(), "\n")
})
}