Skip to content
Open
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
4 changes: 2 additions & 2 deletions bool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
package pflag

import (
"bytes"
"strconv"
"strings"
"testing"
)

Expand Down Expand Up @@ -155,7 +155,7 @@ func TestImplicitFalse(t *testing.T) {
func TestInvalidValue(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
var buf bytes.Buffer
var buf strings.Builder
f.SetOutput(&buf)
err := f.Parse([]string{"--tristate=invalid"})
if err == nil {
Expand Down
4 changes: 2 additions & 2 deletions bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func bytesHexConv(sval string) (interface{}, error) {
return bin, nil
}

return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %w", sval, err)
}

// GetBytesHex return the []byte value of a flag with the given name
Expand Down Expand Up @@ -146,7 +146,7 @@ func bytesBase64ValueConv(sval string) (interface{}, error) {
return bin, nil
}

return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %w", sval, err)
}

// GetBytesBase64 return the []byte value of a flag with the given name
Expand Down
2 changes: 1 addition & 1 deletion count.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func newCountValue(val int, p *int) *countValue {
func (i *countValue) Set(s string) error {
// "+1" means that no specific value was passed, so increment
if s == "+1" {
*i = countValue(*i + 1)
*i++
return nil
}
v, err := strconv.ParseInt(s, 0, 0)
Expand Down
5 changes: 2 additions & 3 deletions duration_slice.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package pflag

import (
"fmt"
"strings"
"time"
)
Expand Down Expand Up @@ -46,7 +45,7 @@ func (s *durationSliceValue) Type() string {
func (s *durationSliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%s", d)
out[i] = d.String()
}
return "[" + strings.Join(out, ",") + "]"
}
Expand All @@ -56,7 +55,7 @@ func (s *durationSliceValue) fromString(val string) (time.Duration, error) {
}

func (s *durationSliceValue) toString(val time.Duration) string {
return fmt.Sprintf("%s", val)
return val.String()
}

func (s *durationSliceValue) Append(val string) error {
Expand Down
44 changes: 20 additions & 24 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ flag set.
package pflag

import (
"bytes"
"errors"
goflag "flag"
"fmt"
Expand Down Expand Up @@ -169,17 +168,17 @@ type FlagSet struct {

// A Flag represents the state of a flag.
type Flag struct {
Value Value // value as set
Annotations map[string][]string // used by cobra.Command bash autocomple code
Name string // name as it appears on command line
Shorthand string // one-letter abbreviated flag
Usage string // help message
Value Value // value as set
DefValue string // default value (as text); for usage message
Changed bool // If the user set the value (or if left to default)
NoOptDefVal string // default value (as text); if the flag is on the command line without any options
Deprecated string // If this flag is deprecated, this string is the new or now thing to use
Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
Annotations map[string][]string // used by cobra.Command bash autocomple code
Changed bool // If the user set the value (or if left to default)
Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
}

// Value is the interface to the dynamic value stored in a flag.
Expand Down Expand Up @@ -365,7 +364,7 @@ func (f *FlagSet) ShorthandLookup(name string) *Flag {
}
if len(name) > 1 {
msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)
fmt.Fprintf(f.Output(), msg)
fmt.Fprint(f.Output(), msg)
panic(msg)
}
c := name[0]
Expand Down Expand Up @@ -475,7 +474,7 @@ func (f *FlagSet) Set(name, value string) error {
} else {
flagName = fmt.Sprintf("--%s", flag.Name)
}
return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)
return fmt.Errorf("invalid argument %q for %q flag: %w", value, flagName, err)
}

if !flag.Changed {
Expand Down Expand Up @@ -634,7 +633,7 @@ func wrapN(i, slop int, s string) (string, string) {
// caller). Pass `w` == 0 to do no wrapping
func wrap(i, w int, s string) string {
if w == 0 {
return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
return strings.ReplaceAll(s, "\n", "\n"+strings.Repeat(" ", i))
}

// space between indent i and end of line width w into which
Expand All @@ -652,7 +651,7 @@ func wrap(i, w int, s string) string {
}
// If still not enough space then don't even try to wrap.
if wrap < 24 {
return strings.Replace(s, "\n", r, -1)
return strings.ReplaceAll(s, "\n", r)
}

// Try to avoid short orphan words on the final line, by
Expand All @@ -664,35 +663,33 @@ func wrap(i, w int, s string) string {
// Handle first line, which is indented by the caller (or the
// special case above)
l, s = wrapN(wrap, slop, s)
r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
r = r + strings.ReplaceAll(l, "\n", "\n"+strings.Repeat(" ", i))

// Now wrap the rest
for s != "" {
var t string

t, s = wrapN(wrap, slop, s)
r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
r = r + "\n" + strings.Repeat(" ", i) + strings.ReplaceAll(t, "\n", "\n"+strings.Repeat(" ", i))
}

return r

}

// FlagUsagesWrapped returns a string containing the usage information
// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
// wrapping)
func (f *FlagSet) FlagUsagesWrapped(cols int) string {
buf := new(bytes.Buffer)

lines := make([]string, 0, len(f.formal))

maxlen := 0
var (
max, maxlen int
lines = make([]string, 0, len(f.formal))
)
f.VisitAll(func(flag *Flag) {
if flag.Hidden {
return
}

line := ""
var line string
if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
} else {
Expand Down Expand Up @@ -740,8 +737,11 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
}

lines = append(lines, line)
max += len(line)
})

buf := new(strings.Builder)
buf.Grow(max)
for _, line := range lines {
sidx := strings.Index(line, "\x00")
spacing := strings.Repeat(" ", maxlen-sidx)
Expand Down Expand Up @@ -867,7 +867,7 @@ func (f *FlagSet) AddFlag(flag *Flag) {
}
if len(flag.Shorthand) > 1 {
msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand)
fmt.Fprintf(f.Output(), msg)
fmt.Fprint(f.Output(), msg)
panic(msg)
}
if f.shorthands == nil {
Expand All @@ -877,7 +877,7 @@ func (f *FlagSet) AddFlag(flag *Flag) {
used, alreadyThere := f.shorthands[c]
if alreadyThere {
msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name)
fmt.Fprintf(f.Output(), msg)
fmt.Fprint(f.Output(), msg)
panic(msg)
}
f.shorthands[c] = flag
Expand Down Expand Up @@ -1135,10 +1135,6 @@ func (f *FlagSet) Parse(arguments []string) error {
}
f.parsed = true

if len(arguments) < 0 {
return nil
}

f.args = make([]string, 0, len(arguments))

set := func(flag *Flag, value string) error {
Expand Down
21 changes: 9 additions & 12 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package pflag

import (
"bytes"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -629,7 +628,7 @@ func TestChangedHelper(t *testing.T) {
func replaceSeparators(name string, from []string, to string) string {
result := name
for _, sep := range from {
result = strings.Replace(result, sep, to, -1)
result = strings.ReplaceAll(result, sep, to)
}
// Type convert to indicate normalization has been done.
return result
Expand Down Expand Up @@ -855,7 +854,7 @@ func TestUserDefined(t *testing.T) {

func TestSetOutput(t *testing.T) {
var flags FlagSet
var buf bytes.Buffer
var buf strings.Builder
flags.SetOutput(&buf)
flags.Init("test", ContinueOnError)
flags.Parse([]string{"--unknown"})
Expand All @@ -866,7 +865,7 @@ func TestSetOutput(t *testing.T) {

func TestOutput(t *testing.T) {
var flags FlagSet
var buf bytes.Buffer
var buf strings.Builder
expect := "an example string"
flags.SetOutput(&buf)
fmt.Fprint(flags.Output(), expect)
Expand Down Expand Up @@ -1001,7 +1000,7 @@ func getDeprecatedFlagSet() *FlagSet {
func TestDeprecatedFlagInDocs(t *testing.T) {
f := getDeprecatedFlagSet()

out := new(bytes.Buffer)
out := new(strings.Builder)
f.SetOutput(out)
f.PrintDefaults()

Expand All @@ -1018,7 +1017,7 @@ func TestUnHiddenDeprecatedFlagInDocs(t *testing.T) {
}
flg.Hidden = false

out := new(bytes.Buffer)
out := new(strings.Builder)
f.SetOutput(out)
f.PrintDefaults()

Expand All @@ -1037,7 +1036,7 @@ func TestDeprecatedFlagShorthandInDocs(t *testing.T) {
f.BoolP(name, "n", true, "always true")
f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name))

out := new(bytes.Buffer)
out := new(strings.Builder)
f.SetOutput(out)
f.PrintDefaults()

Expand All @@ -1056,7 +1055,7 @@ func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error)
outC := make(chan string)
// copy the output in a separate goroutine so printing can't block indefinitely
go func() {
var buf bytes.Buffer
var buf strings.Builder
io.Copy(&buf, r)
outC <- buf.String()
}()
Expand Down Expand Up @@ -1140,7 +1139,7 @@ func TestHiddenFlagInUsage(t *testing.T) {
f.Bool("secretFlag", true, "shhh")
f.MarkHidden("secretFlag")

out := new(bytes.Buffer)
out := new(strings.Builder)
f.SetOutput(out)
f.PrintDefaults()

Expand Down Expand Up @@ -1204,7 +1203,7 @@ func (cv *customValue) Type() string { return "custom" }

func TestPrintDefaults(t *testing.T) {
fs := NewFlagSet("print defaults test", ContinueOnError)
var buf bytes.Buffer
var buf strings.Builder
fs.SetOutput(&buf)
fs.Bool("A", false, "for bootstrapping, allow 'any' type")
fs.Bool("Alongflagname", false, "disable bounds checking")
Expand Down Expand Up @@ -1238,8 +1237,6 @@ func TestPrintDefaults(t *testing.T) {
fs.PrintDefaults()
got := buf.String()
if got != defaultOutput {
fmt.Println("\n" + got)
fmt.Println("\n" + defaultOutput)
t.Errorf("got %q want %q\n", got, defaultOutput)
}
}
Expand Down
3 changes: 1 addition & 2 deletions ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ func (i *ipValue) Type() string {
}

func ipConv(sval string) (interface{}, error) {
ip := net.ParseIP(sval)
if ip != nil {
if ip := net.ParseIP(sval); ip != nil {
return ip, nil
}
return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
Expand Down
15 changes: 4 additions & 11 deletions ip_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,31 +72,24 @@ func (s *ipSliceValue) String() string {
return "[" + out + "]"
}

func (s *ipSliceValue) fromString(val string) (net.IP, error) {
return net.ParseIP(strings.TrimSpace(val)), nil
func (s *ipSliceValue) fromString(val string) net.IP {
return net.ParseIP(strings.TrimSpace(val))
}

func (s *ipSliceValue) toString(val net.IP) string {
return val.String()
}

func (s *ipSliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
i := s.fromString(val)
*s.value = append(*s.value, i)
return nil
}

func (s *ipSliceValue) Replace(val []string) error {
out := make([]net.IP, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
out[i] = s.fromString(d)
}
*s.value = out
return nil
Expand Down
6 changes: 3 additions & 3 deletions printusage_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package pflag

import (
"bytes"
"io"
"strings"
"testing"
)

Expand All @@ -25,7 +25,7 @@ func setUpPFlagSet(buf io.Writer) *FlagSet {
}

func TestPrintUsage(t *testing.T) {
buf := bytes.Buffer{}
var buf strings.Builder
f := setUpPFlagSet(&buf)
f.PrintDefaults()
res := buf.String()
Expand Down Expand Up @@ -65,7 +65,7 @@ const expectedOutput2 = ` --long-form Some description
`

func TestPrintUsage_2(t *testing.T) {
buf := bytes.Buffer{}
var buf strings.Builder
f := setUpPFlagSet2(&buf)
res := f.FlagUsagesWrapped(80)
if res != expectedOutput2 {
Expand Down
Loading