Bumping k8s dependencies to 1.13

This commit is contained in:
Cheng Xing
2018-11-16 14:08:25 -08:00
parent 305407125c
commit b4c0b68ec7
8002 changed files with 884099 additions and 276228 deletions

209
vendor/github.com/spf13/pflag/bytes.go generated vendored Normal file
View File

@@ -0,0 +1,209 @@
package pflag
import (
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
)
// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded
type bytesHexValue []byte
// String implements pflag.Value.String.
func (bytesHex bytesHexValue) String() string {
return fmt.Sprintf("%X", []byte(bytesHex))
}
// Set implements pflag.Value.Set.
func (bytesHex *bytesHexValue) Set(value string) error {
bin, err := hex.DecodeString(strings.TrimSpace(value))
if err != nil {
return err
}
*bytesHex = bin
return nil
}
// Type implements pflag.Value.Type.
func (*bytesHexValue) Type() string {
return "bytesHex"
}
func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue {
*p = val
return (*bytesHexValue)(p)
}
func bytesHexConv(sval string) (interface{}, error) {
bin, err := hex.DecodeString(sval)
if err == nil {
return bin, nil
}
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
}
// GetBytesHex return the []byte value of a flag with the given name
func (f *FlagSet) GetBytesHex(name string) ([]byte, error) {
val, err := f.getFlagType(name, "bytesHex", bytesHexConv)
if err != nil {
return []byte{}, err
}
return val.([]byte), nil
}
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) {
f.VarP(newBytesHexValue(value, p), name, "", usage)
}
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
f.VarP(newBytesHexValue(value, p), name, shorthand, usage)
}
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func BytesHexVar(p *[]byte, name string, value []byte, usage string) {
CommandLine.VarP(newBytesHexValue(value, p), name, "", usage)
}
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage)
}
// BytesHex defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesHexVarP(p, name, "", value, usage)
return p
}
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesHexVarP(p, name, shorthand, value, usage)
return p
}
// BytesHex defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func BytesHex(name string, value []byte, usage string) *[]byte {
return CommandLine.BytesHexP(name, "", value, usage)
}
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
return CommandLine.BytesHexP(name, shorthand, value, usage)
}
// BytesBase64 adapts []byte for use as a flag. Value of flag is Base64 encoded
type bytesBase64Value []byte
// String implements pflag.Value.String.
func (bytesBase64 bytesBase64Value) String() string {
return base64.StdEncoding.EncodeToString([]byte(bytesBase64))
}
// Set implements pflag.Value.Set.
func (bytesBase64 *bytesBase64Value) Set(value string) error {
bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
if err != nil {
return err
}
*bytesBase64 = bin
return nil
}
// Type implements pflag.Value.Type.
func (*bytesBase64Value) Type() string {
return "bytesBase64"
}
func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value {
*p = val
return (*bytesBase64Value)(p)
}
func bytesBase64ValueConv(sval string) (interface{}, error) {
bin, err := base64.StdEncoding.DecodeString(sval)
if err == nil {
return bin, nil
}
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
}
// GetBytesBase64 return the []byte value of a flag with the given name
func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) {
val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv)
if err != nil {
return []byte{}, err
}
return val.([]byte), nil
}
// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func (f *FlagSet) BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
f.VarP(newBytesBase64Value(value, p), name, "", usage)
}
// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
f.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
}
// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
CommandLine.VarP(newBytesBase64Value(value, p), name, "", usage)
}
// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
func BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
CommandLine.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
}
// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func (f *FlagSet) BytesBase64(name string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesBase64VarP(p, name, "", value, usage)
return p
}
// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesBase64VarP(p, name, shorthand, value, usage)
return p
}
// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func BytesBase64(name string, value []byte, usage string) *[]byte {
return CommandLine.BytesBase64P(name, "", value, usage)
}
// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
func BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
return CommandLine.BytesBase64P(name, shorthand, value, usage)
}

134
vendor/github.com/spf13/pflag/bytes_test.go generated vendored Normal file
View File

@@ -0,0 +1,134 @@
package pflag
import (
"encoding/base64"
"fmt"
"os"
"testing"
)
func setUpBytesHex(bytesHex *[]byte) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.BytesHexVar(bytesHex, "bytes", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX")
f.BytesHexVarP(bytesHex, "bytes2", "B", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX")
return f
}
func TestBytesHex(t *testing.T) {
testCases := []struct {
input string
success bool
expected string
}{
/// Positive cases
{"", true, ""}, // Is empty string OK ?
{"01", true, "01"},
{"0101", true, "0101"},
{"1234567890abcdef", true, "1234567890ABCDEF"},
{"1234567890ABCDEF", true, "1234567890ABCDEF"},
// Negative cases
{"0", false, ""}, // Short string
{"000", false, ""}, /// Odd-length string
{"qq", false, ""}, /// non-hex character
}
devnull, _ := os.Open(os.DevNull)
os.Stderr = devnull
for i := range testCases {
var bytesHex []byte
f := setUpBytesHex(&bytesHex)
tc := &testCases[i]
// --bytes
args := []string{
fmt.Sprintf("--bytes=%s", tc.input),
fmt.Sprintf("-B %s", tc.input),
fmt.Sprintf("--bytes2=%s", tc.input),
}
for _, arg := range args {
err := f.Parse([]string{arg})
if err != nil && tc.success == true {
t.Errorf("expected success, got %q", err)
continue
} else if err == nil && tc.success == false {
// bytesHex, err := f.GetBytesHex("bytes")
t.Errorf("expected failure while processing %q", tc.input)
continue
} else if tc.success {
bytesHex, err := f.GetBytesHex("bytes")
if err != nil {
t.Errorf("Got error trying to fetch the 'bytes' flag: %v", err)
}
if fmt.Sprintf("%X", bytesHex) != tc.expected {
t.Errorf("expected %q, got '%X'", tc.expected, bytesHex)
}
}
}
}
}
func setUpBytesBase64(bytesBase64 *[]byte) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.BytesBase64Var(bytesBase64, "bytes", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in Base64")
f.BytesBase64VarP(bytesBase64, "bytes2", "B", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in Base64")
return f
}
func TestBytesBase64(t *testing.T) {
testCases := []struct {
input string
success bool
expected string
}{
/// Positive cases
{"", true, ""}, // Is empty string OK ?
{"AQ==", true, "AQ=="},
// Negative cases
{"AQ", false, ""}, // Padding removed
{"ï", false, ""}, // non-base64 characters
}
devnull, _ := os.Open(os.DevNull)
os.Stderr = devnull
for i := range testCases {
var bytesBase64 []byte
f := setUpBytesBase64(&bytesBase64)
tc := &testCases[i]
// --bytes
args := []string{
fmt.Sprintf("--bytes=%s", tc.input),
fmt.Sprintf("-B %s", tc.input),
fmt.Sprintf("--bytes2=%s", tc.input),
}
for _, arg := range args {
err := f.Parse([]string{arg})
if err != nil && tc.success == true {
t.Errorf("expected success, got %q", err)
continue
} else if err == nil && tc.success == false {
// bytesBase64, err := f.GetBytesBase64("bytes")
t.Errorf("expected failure while processing %q", tc.input)
continue
} else if tc.success {
bytesBase64, err := f.GetBytesBase64("bytes")
if err != nil {
t.Errorf("Got error trying to fetch the 'bytes' flag: %v", err)
}
if base64.StdEncoding.EncodeToString(bytesBase64) != tc.expected {
t.Errorf("expected %q, got '%X'", tc.expected, bytesBase64)
}
}
}
}
}

View File

@@ -11,13 +11,13 @@ func newCountValue(val int, p *int) *countValue {
}
func (i *countValue) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
// -1 means that no specific value was passed, so increment
if v == -1 {
// "+1" means that no specific value was passed, so increment
if s == "+1" {
*i = countValue(*i + 1)
} else {
*i = countValue(v)
return nil
}
v, err := strconv.ParseInt(s, 0, 0)
*i = countValue(v)
return err
}
@@ -54,7 +54,7 @@ func (f *FlagSet) CountVar(p *int, name string, usage string) {
// CountVarP is like CountVar only take a shorthand for the flag name.
func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) {
flag := f.VarPF(newCountValue(0, p), name, shorthand, usage)
flag.NoOptDefVal = "-1"
flag.NoOptDefVal = "+1"
}
// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set

View File

@@ -17,10 +17,14 @@ func TestCount(t *testing.T) {
success bool
expected int
}{
{[]string{}, true, 0},
{[]string{"-v"}, true, 1},
{[]string{"-vvv"}, true, 3},
{[]string{"-v", "-v", "-v"}, true, 3},
{[]string{"-v", "--verbose", "-v"}, true, 3},
{[]string{"-v=3", "-v"}, true, 4},
{[]string{"--verbose=0"}, true, 0},
{[]string{"-v=0"}, true, 0},
{[]string{"-v=a"}, false, 0},
}
@@ -45,7 +49,7 @@ func TestCount(t *testing.T) {
t.Errorf("Got error trying to fetch the counter flag")
}
if c != tc.expected {
t.Errorf("expected %q, got %q", tc.expected, c)
t.Errorf("expected %d, got %d", tc.expected, c)
}
}
}

128
vendor/github.com/spf13/pflag/duration_slice.go generated vendored Normal file
View File

@@ -0,0 +1,128 @@
package pflag
import (
"fmt"
"strings"
"time"
)
// -- durationSlice Value
type durationSliceValue struct {
value *[]time.Duration
changed bool
}
func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue {
dsv := new(durationSliceValue)
dsv.value = p
*dsv.value = val
return dsv
}
func (s *durationSliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]time.Duration, len(ss))
for i, d := range ss {
var err error
out[i], err = time.ParseDuration(d)
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *durationSliceValue) Type() string {
return "durationSlice"
}
func (s *durationSliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%s", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func durationSliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []time.Duration{}, nil
}
ss := strings.Split(val, ",")
out := make([]time.Duration, len(ss))
for i, d := range ss {
var err error
out[i], err = time.ParseDuration(d)
if err != nil {
return nil, err
}
}
return out, nil
}
// GetDurationSlice returns the []time.Duration value of a flag with the given name
func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) {
val, err := f.getFlagType(name, "durationSlice", durationSliceConv)
if err != nil {
return []time.Duration{}, err
}
return val.([]time.Duration), nil
}
// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string.
// The argument p points to a []time.Duration variable in which to store the value of the flag.
func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
f.VarP(newDurationSliceValue(value, p), name, "", usage)
}
// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
f.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
}
// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string.
// The argument p points to a duration[] variable in which to store the value of the flag.
func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage)
}
// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
}
// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a []time.Duration variable that stores the value of the flag.
func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
p := []time.Duration{}
f.DurationSliceVarP(&p, name, "", value, usage)
return &p
}
// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
p := []time.Duration{}
f.DurationSliceVarP(&p, name, shorthand, value, usage)
return &p
}
// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a []time.Duration variable that stores the value of the flag.
func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
return CommandLine.DurationSliceP(name, "", value, usage)
}
// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
return CommandLine.DurationSliceP(name, shorthand, value, usage)
}

165
vendor/github.com/spf13/pflag/duration_slice_test.go generated vendored Normal file
View File

@@ -0,0 +1,165 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code ds governed by a BSD-style
// license that can be found in the LICENSE file.
package pflag
import (
"fmt"
"strings"
"testing"
"time"
)
func setUpDSFlagSet(dsp *[]time.Duration) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.DurationSliceVar(dsp, "ds", []time.Duration{}, "Command separated list!")
return f
}
func setUpDSFlagSetWithDefault(dsp *[]time.Duration) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.DurationSliceVar(dsp, "ds", []time.Duration{0, 1}, "Command separated list!")
return f
}
func TestEmptyDS(t *testing.T) {
var ds []time.Duration
f := setUpDSFlagSet(&ds)
err := f.Parse([]string{})
if err != nil {
t.Fatal("expected no error; got", err)
}
getDS, err := f.GetDurationSlice("ds")
if err != nil {
t.Fatal("got an error from GetDurationSlice():", err)
}
if len(getDS) != 0 {
t.Fatalf("got ds %v with len=%d but expected length=0", getDS, len(getDS))
}
}
func TestDS(t *testing.T) {
var ds []time.Duration
f := setUpDSFlagSet(&ds)
vals := []string{"1ns", "2ms", "3m", "4h"}
arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ","))
err := f.Parse([]string{arg})
if err != nil {
t.Fatal("expected no error; got", err)
}
for i, v := range ds {
d, err := time.ParseDuration(vals[i])
if err != nil {
t.Fatalf("got error: %v", err)
}
if d != v {
t.Fatalf("expected ds[%d] to be %s but got: %d", i, vals[i], v)
}
}
getDS, err := f.GetDurationSlice("ds")
if err != nil {
t.Fatalf("got error: %v", err)
}
for i, v := range getDS {
d, err := time.ParseDuration(vals[i])
if err != nil {
t.Fatalf("got error: %v", err)
}
if d != v {
t.Fatalf("expected ds[%d] to be %s but got: %d from GetDurationSlice", i, vals[i], v)
}
}
}
func TestDSDefault(t *testing.T) {
var ds []time.Duration
f := setUpDSFlagSetWithDefault(&ds)
vals := []string{"0s", "1ns"}
err := f.Parse([]string{})
if err != nil {
t.Fatal("expected no error; got", err)
}
for i, v := range ds {
d, err := time.ParseDuration(vals[i])
if err != nil {
t.Fatalf("got error: %v", err)
}
if d != v {
t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v)
}
}
getDS, err := f.GetDurationSlice("ds")
if err != nil {
t.Fatal("got an error from GetDurationSlice():", err)
}
for i, v := range getDS {
d, err := time.ParseDuration(vals[i])
if err != nil {
t.Fatal("got an error from GetDurationSlice():", err)
}
if d != v {
t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v)
}
}
}
func TestDSWithDefault(t *testing.T) {
var ds []time.Duration
f := setUpDSFlagSetWithDefault(&ds)
vals := []string{"1ns", "2ns"}
arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ","))
err := f.Parse([]string{arg})
if err != nil {
t.Fatal("expected no error; got", err)
}
for i, v := range ds {
d, err := time.ParseDuration(vals[i])
if err != nil {
t.Fatalf("got error: %v", err)
}
if d != v {
t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v)
}
}
getDS, err := f.GetDurationSlice("ds")
if err != nil {
t.Fatal("got an error from GetDurationSlice():", err)
}
for i, v := range getDS {
d, err := time.ParseDuration(vals[i])
if err != nil {
t.Fatalf("got error: %v", err)
}
if d != v {
t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v)
}
}
}
func TestDSCalledTwice(t *testing.T) {
var ds []time.Duration
f := setUpDSFlagSet(&ds)
in := []string{"1ns,2ns", "3ns"}
expected := []time.Duration{1, 2, 3}
argfmt := "--ds=%s"
arg1 := fmt.Sprintf(argfmt, in[0])
arg2 := fmt.Sprintf(argfmt, in[1])
err := f.Parse([]string{arg1, arg2})
if err != nil {
t.Fatal("expected no error; got", err)
}
for i, v := range ds {
if expected[i] != v {
t.Fatalf("expected ds[%d] to be %d but got: %d", i, expected[i], v)
}
}
}

161
vendor/github.com/spf13/pflag/flag.go generated vendored
View File

@@ -101,6 +101,7 @@ package pflag
import (
"bytes"
"errors"
goflag "flag"
"fmt"
"io"
"os"
@@ -123,6 +124,12 @@ const (
PanicOnError
)
// ParseErrorsWhitelist defines the parsing errors that can be ignored
type ParseErrorsWhitelist struct {
// UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags
UnknownFlags bool
}
// NormalizedName is a flag name that has been normalized according to rules
// for the FlagSet (e.g. making '-' and '_' equivalent).
type NormalizedName string
@@ -138,6 +145,9 @@ type FlagSet struct {
// help/usage messages.
SortFlags bool
// ParseErrorsWhitelist is used to configure a whitelist of errors
ParseErrorsWhitelist ParseErrorsWhitelist
name string
parsed bool
actual map[NormalizedName]*Flag
@@ -153,6 +163,8 @@ type FlagSet struct {
output io.Writer // nil means stderr; use out() accessor
interspersed bool // allow interspersed option/non-option args
normalizeNameFunc func(f *FlagSet, name string) NormalizedName
addedGoFlagSets []*goflag.FlagSet
}
// A Flag represents the state of a flag.
@@ -202,12 +214,18 @@ func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
f.normalizeNameFunc = n
f.sortedFormal = f.sortedFormal[:0]
for k, v := range f.orderedFormal {
delete(f.formal, NormalizedName(v.Name))
nname := f.normalizeFlagName(v.Name)
v.Name = string(nname)
f.formal[nname] = v
f.orderedFormal[k] = v
for fname, flag := range f.formal {
nname := f.normalizeFlagName(flag.Name)
if fname == nname {
continue
}
flag.Name = string(nname)
delete(f.formal, fname)
f.formal[nname] = flag
if _, set := f.actual[fname]; set {
delete(f.actual, fname)
f.actual[nname] = flag
}
}
}
@@ -261,16 +279,16 @@ func (f *FlagSet) VisitAll(fn func(*Flag)) {
}
}
// HasFlags returns a bool to indicate if the FlagSet has any flags definied.
// HasFlags returns a bool to indicate if the FlagSet has any flags defined.
func (f *FlagSet) HasFlags() bool {
return len(f.formal) > 0
}
// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
// definied that are not hidden or deprecated.
// that are not hidden.
func (f *FlagSet) HasAvailableFlags() bool {
for _, flag := range f.formal {
if !flag.Hidden && len(flag.Deprecated) == 0 {
if !flag.Hidden {
return true
}
}
@@ -380,6 +398,7 @@ func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
return fmt.Errorf("deprecated message for flag %q must be set", name)
}
flag.Deprecated = usageMessage
flag.Hidden = true
return nil
}
@@ -440,13 +459,15 @@ func (f *FlagSet) Set(name, value string) error {
return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)
}
if f.actual == nil {
f.actual = make(map[NormalizedName]*Flag)
}
f.actual[normalName] = flag
f.orderedActual = append(f.orderedActual, flag)
if !flag.Changed {
if f.actual == nil {
f.actual = make(map[NormalizedName]*Flag)
}
f.actual[normalName] = flag
f.orderedActual = append(f.orderedActual, flag)
flag.Changed = true
flag.Changed = true
}
if flag.Deprecated != "" {
fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
@@ -556,6 +577,14 @@ func UnquoteUsage(flag *Flag) (name string, usage string) {
name = "int"
case "uint64":
name = "uint"
case "stringSlice":
name = "strings"
case "intSlice":
name = "ints"
case "uintSlice":
name = "uints"
case "boolSlice":
name = "bools"
}
return
@@ -570,11 +599,14 @@ func wrapN(i, slop int, s string) (string, string) {
return s, ""
}
w := strings.LastIndexAny(s[:i], " \t")
w := strings.LastIndexAny(s[:i], " \t\n")
if w <= 0 {
return s, ""
}
nlPos := strings.LastIndex(s[:i], "\n")
if nlPos > 0 && nlPos < w {
return s[:nlPos], s[nlPos+1:]
}
return s[:w], s[w+1:]
}
@@ -583,7 +615,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 s
return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
}
// space between indent i and end of line width w into which
@@ -601,7 +633,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 s
return strings.Replace(s, "\n", r, -1)
}
// Try to avoid short orphan words on the final line, by
@@ -613,14 +645,14 @@ 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 + l
r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
// Now wrap the rest
for s != "" {
var t string
t, s = wrapN(wrap, slop, s)
r = r + "\n" + strings.Repeat(" ", i) + t
r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
}
return r
@@ -637,7 +669,7 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
maxlen := 0
f.VisitAll(func(flag *Flag) {
if flag.Deprecated != "" || flag.Hidden {
if flag.Hidden {
return
}
@@ -660,6 +692,10 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
if flag.NoOptDefVal != "true" {
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
case "count":
if flag.NoOptDefVal != "+1" {
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
default:
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
@@ -680,6 +716,9 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
line += fmt.Sprintf(" (default %s)", flag.DefValue)
}
}
if len(flag.Deprecated) != 0 {
line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)
}
lines = append(lines, line)
})
@@ -857,8 +896,10 @@ func VarP(value Value, name, shorthand, usage string) {
// returns the error.
func (f *FlagSet) failf(format string, a ...interface{}) error {
err := fmt.Errorf(format, a...)
fmt.Fprintln(f.out(), err)
f.usage()
if f.errorHandling != ContinueOnError {
fmt.Fprintln(f.out(), err)
f.usage()
}
return err
}
@@ -874,6 +915,28 @@ func (f *FlagSet) usage() {
}
}
//--unknown (args will be empty)
//--unknown --next-flag ... (args will be --next-flag ...)
//--unknown arg ... (args will be arg ...)
func stripUnknownFlagValue(args []string) []string {
if len(args) == 0 {
//--unknown
return args
}
first := args[0]
if len(first) > 0 && first[0] == '-' {
//--unknown --next-flag ...
return args
}
//--unknown arg ... (args will be arg ...)
if len(args) > 1 {
return args[1:]
}
return nil
}
func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
a = args
name := s[2:]
@@ -885,13 +948,24 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin
split := strings.SplitN(name, "=", 2)
name = split[0]
flag, exists := f.formal[f.normalizeFlagName(name)]
if !exists {
if name == "help" { // special case for nice help message.
switch {
case name == "help":
f.usage()
return a, ErrHelp
case f.ParseErrorsWhitelist.UnknownFlags:
// --unknown=unknownval arg ...
// we do not want to lose arg in this case
if len(split) >= 2 {
return a, nil
}
return stripUnknownFlagValue(a), nil
default:
err = f.failf("unknown flag: --%s", name)
return
}
err = f.failf("unknown flag: --%s", name)
return
}
var value string
@@ -912,27 +986,43 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin
}
err = fn(flag, value)
if err != nil {
f.failf(err.Error())
}
return
}
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
outArgs = args
if strings.HasPrefix(shorthands, "test.") {
return
}
outArgs = args
outShorts = shorthands[1:]
c := shorthands[0]
flag, exists := f.shorthands[c]
if !exists {
if c == 'h' { // special case for nice help message.
switch {
case c == 'h':
f.usage()
err = ErrHelp
return
case f.ParseErrorsWhitelist.UnknownFlags:
// '-f=arg arg ...'
// we do not want to lose arg in this case
if len(shorthands) > 2 && shorthands[1] == '=' {
outShorts = ""
return
}
outArgs = stripUnknownFlagValue(outArgs)
return
default:
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
return
}
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
return
}
var value string
@@ -962,6 +1052,9 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse
}
err = fn(flag, value)
if err != nil {
f.failf(err.Error())
}
return
}
@@ -1016,6 +1109,11 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
// are defined and before flags are accessed by the program.
// The return value will be ErrHelp if -help was set but not defined.
func (f *FlagSet) Parse(arguments []string) error {
if f.addedGoFlagSets != nil {
for _, goFlagSet := range f.addedGoFlagSets {
goFlagSet.Parse(nil)
}
}
f.parsed = true
if len(arguments) < 0 {
@@ -1034,6 +1132,7 @@ func (f *FlagSet) Parse(arguments []string) error {
case ContinueOnError:
return err
case ExitOnError:
fmt.Println(err)
os.Exit(2)
case PanicOnError:
panic(err)

View File

@@ -106,8 +106,8 @@ func TestUsage(t *testing.T) {
if GetCommandLine().Parse([]string{"--x"}) == nil {
t.Error("parse did not fail for unknown flag")
}
if !called {
t.Error("did not call Usage for unknown flag")
if called {
t.Error("did call Usage while using ContinueOnError")
}
}
@@ -168,6 +168,7 @@ func testParse(f *FlagSet, t *testing.T) {
bool3Flag := f.Bool("bool3", false, "bool3 value")
intFlag := f.Int("int", 0, "int value")
int8Flag := f.Int8("int8", 0, "int value")
int16Flag := f.Int16("int16", 0, "int value")
int32Flag := f.Int32("int32", 0, "int value")
int64Flag := f.Int64("int64", 0, "int64 value")
uintFlag := f.Uint("uint", 0, "uint value")
@@ -192,6 +193,7 @@ func testParse(f *FlagSet, t *testing.T) {
"--bool3=false",
"--int=22",
"--int8=-8",
"--int16=-16",
"--int32=-32",
"--int64=0x23",
"--uint", "24",
@@ -236,9 +238,15 @@ func testParse(f *FlagSet, t *testing.T) {
if *int8Flag != -8 {
t.Error("int8 flag should be 0x23, is ", *int8Flag)
}
if *int16Flag != -16 {
t.Error("int16 flag should be -16, is ", *int16Flag)
}
if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag {
t.Error("GetInt8 does not work.")
}
if v, err := f.GetInt16("int16"); err != nil || v != *int16Flag {
t.Error("GetInt16 does not work.")
}
if *int32Flag != -32 {
t.Error("int32 flag should be 0x23, is ", *int32Flag)
}
@@ -381,7 +389,83 @@ func testParseAll(f *FlagSet, t *testing.T) {
}
if !reflect.DeepEqual(got, want) {
t.Errorf("f.ParseAll() fail to restore the args")
t.Errorf("Got: %v", got)
t.Errorf("Got: %v", got)
t.Errorf("Want: %v", want)
}
}
func testParseWithUnknownFlags(f *FlagSet, t *testing.T) {
if f.Parsed() {
t.Error("f.Parse() = true before Parse")
}
f.ParseErrorsWhitelist.UnknownFlags = true
f.BoolP("boola", "a", false, "bool value")
f.BoolP("boolb", "b", false, "bool2 value")
f.BoolP("boolc", "c", false, "bool3 value")
f.BoolP("boold", "d", false, "bool4 value")
f.BoolP("boole", "e", false, "bool4 value")
f.StringP("stringa", "s", "0", "string value")
f.StringP("stringz", "z", "0", "string value")
f.StringP("stringx", "x", "0", "string value")
f.StringP("stringy", "y", "0", "string value")
f.StringP("stringo", "o", "0", "string value")
f.Lookup("stringx").NoOptDefVal = "1"
args := []string{
"-ab",
"-cs=xx",
"--stringz=something",
"--unknown1",
"unknown1Value",
"-d=true",
"-x",
"--unknown2=unknown2Value",
"-u=unknown3Value",
"-p",
"unknown4Value",
"-q", //another unknown with bool value
"-y",
"ee",
"--unknown7=unknown7value",
"--stringo=ovalue",
"--unknown8=unknown8value",
"--boole",
"--unknown6",
"",
"-uuuuu",
"",
"--unknown10",
"--unknown11",
}
want := []string{
"boola", "true",
"boolb", "true",
"boolc", "true",
"stringa", "xx",
"stringz", "something",
"boold", "true",
"stringx", "1",
"stringy", "ee",
"stringo", "ovalue",
"boole", "true",
}
got := []string{}
store := func(flag *Flag, value string) error {
got = append(got, flag.Name)
if len(value) > 0 {
got = append(got, value)
}
return nil
}
if err := f.ParseAll(args, store); err != nil {
t.Errorf("expected no error, got %s", err)
}
if !f.Parsed() {
t.Errorf("f.Parse() = false after Parse")
}
if !reflect.DeepEqual(got, want) {
t.Errorf("f.ParseAll() fail to restore the args")
t.Errorf("Got: %v", got)
t.Errorf("Want: %v", want)
}
}
@@ -492,6 +576,11 @@ func TestParseAll(t *testing.T) {
testParseAll(GetCommandLine(), t)
}
func TestIgnoreUnknownFlags(t *testing.T) {
ResetForTesting(func() { t.Error("bad parse") })
testParseWithUnknownFlags(GetCommandLine(), t)
}
func TestFlagSetParse(t *testing.T) {
testParse(NewFlagSet("test", ContinueOnError), t)
}
@@ -604,7 +693,6 @@ func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName {
switch name {
case oldName:
name = newName
break
}
return NormalizedName(name)
@@ -658,6 +746,70 @@ func TestNormalizationFuncShouldChangeFlagName(t *testing.T) {
}
}
// Related to https://github.com/spf13/cobra/issues/521.
func TestNormalizationSharedFlags(t *testing.T) {
f := NewFlagSet("set f", ContinueOnError)
g := NewFlagSet("set g", ContinueOnError)
nfunc := wordSepNormalizeFunc
testName := "valid_flag"
normName := nfunc(nil, testName)
if testName == string(normName) {
t.Error("TestNormalizationSharedFlags meaningless: the original and normalized flag names are identical:", testName)
}
f.Bool(testName, false, "bool value")
g.AddFlagSet(f)
f.SetNormalizeFunc(nfunc)
g.SetNormalizeFunc(nfunc)
if len(f.formal) != 1 {
t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal)
}
if f.orderedFormal[0].Name != string(normName) {
t.Error("Flag name not normalized")
}
for k := range f.formal {
if k != "valid.flag" {
t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k)
}
}
if !reflect.DeepEqual(f.formal, g.formal) || !reflect.DeepEqual(f.orderedFormal, g.orderedFormal) {
t.Error("Two flag sets sharing the same flags should stay consistent after being normalized. Original set:", f.formal, "Duplicate set:", g.formal)
}
}
func TestNormalizationSetFlags(t *testing.T) {
f := NewFlagSet("normalized", ContinueOnError)
nfunc := wordSepNormalizeFunc
testName := "valid_flag"
normName := nfunc(nil, testName)
if testName == string(normName) {
t.Error("TestNormalizationSetFlags meaningless: the original and normalized flag names are identical:", testName)
}
f.Bool(testName, false, "bool value")
f.Set(testName, "true")
f.SetNormalizeFunc(nfunc)
if len(f.formal) != 1 {
t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal)
}
if f.orderedFormal[0].Name != string(normName) {
t.Error("Flag name not normalized")
}
for k := range f.formal {
if k != "valid.flag" {
t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k)
}
}
if !reflect.DeepEqual(f.formal, f.actual) {
t.Error("The map of set flags should get normalized. Formal:", f.formal, "Actual:", f.actual)
}
}
// Declare a user-defined flag type.
type flagVar []string
@@ -819,10 +971,14 @@ func TestTermination(t *testing.T) {
}
}
func TestDeprecatedFlagInDocs(t *testing.T) {
func getDeprecatedFlagSet() *FlagSet {
f := NewFlagSet("bob", ContinueOnError)
f.Bool("badflag", true, "always true")
f.MarkDeprecated("badflag", "use --good-flag instead")
return f
}
func TestDeprecatedFlagInDocs(t *testing.T) {
f := getDeprecatedFlagSet()
out := new(bytes.Buffer)
f.SetOutput(out)
@@ -833,6 +989,27 @@ func TestDeprecatedFlagInDocs(t *testing.T) {
}
}
func TestUnHiddenDeprecatedFlagInDocs(t *testing.T) {
f := getDeprecatedFlagSet()
flg := f.Lookup("badflag")
if flg == nil {
t.Fatalf("Unable to lookup 'bob' in TestUnHiddenDeprecatedFlagInDocs")
}
flg.Hidden = false
out := new(bytes.Buffer)
f.SetOutput(out)
f.PrintDefaults()
defaults := out.String()
if !strings.Contains(defaults, "badflag") {
t.Errorf("Did not find deprecated flag in usage!")
}
if !strings.Contains(defaults, "use --good-flag instead") {
t.Errorf("Did not find 'use --good-flag instead' in defaults")
}
}
func TestDeprecatedFlagShorthandInDocs(t *testing.T) {
f := NewFlagSet("bob", ContinueOnError)
name := "noshorthandflag"
@@ -978,16 +1155,17 @@ const defaultOutput = ` --A for bootstrapping, allo
--IP ip IP address with no default
--IPMask ipMask Netmask address with no default
--IPNet ipNet IP network with no default
--Ints intSlice int slice with zero default
--Ints ints int slice with zero default
--N int a non-zero int (default 27)
--ND1 string[="bar"] a string with NoOptDefVal (default "foo")
--ND2 num[=4321] a num with NoOptDefVal (default 1234)
--StringArray stringArray string array with zero default
--StringSlice stringSlice string slice with zero default
--StringSlice strings string slice with zero default
--Z int an int that defaults to zero
--custom custom custom Value implementation
--customP custom a VarP with default (default 10)
--maxT timeout set timeout for dial
-v, --verbose count verbosity
`
// Custom value that satisfies the Value interface.
@@ -1028,6 +1206,7 @@ func TestPrintDefaults(t *testing.T) {
fs.ShorthandLookup("E").NoOptDefVal = "1234"
fs.StringSlice("StringSlice", []string{}, "string slice with zero default")
fs.StringArray("StringArray", []string{}, "string array with zero default")
fs.CountP("verbose", "v", "verbosity")
var cv customValue
fs.Var(&cv, "custom", "custom Value implementation")

View File

@@ -98,4 +98,8 @@ func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
newSet.VisitAll(func(goflag *goflag.Flag) {
f.AddGoFlag(goflag)
})
if f.addedGoFlagSets == nil {
f.addedGoFlagSets = make([]*goflag.FlagSet, 0)
}
f.addedGoFlagSets = append(f.addedGoFlagSets, newSet)
}

View File

@@ -36,4 +36,12 @@ func TestGoflags(t *testing.T) {
if getBool != true {
t.Fatalf("expected getBool=true but got getBool=%v", getBool)
}
if !f.Parsed() {
t.Fatal("f.Parsed() return false after f.Parse() called")
}
// in fact it is useless. because `go test` called flag.Parse()
if !goflag.CommandLine.Parsed() {
t.Fatal("goflag.CommandLine.Parsed() return false after f.Parse() called")
}
}

88
vendor/github.com/spf13/pflag/int16.go generated vendored Normal file
View File

@@ -0,0 +1,88 @@
package pflag
import "strconv"
// -- int16 Value
type int16Value int16
func newInt16Value(val int16, p *int16) *int16Value {
*p = val
return (*int16Value)(p)
}
func (i *int16Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 16)
*i = int16Value(v)
return err
}
func (i *int16Value) Type() string {
return "int16"
}
func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) }
func int16Conv(sval string) (interface{}, error) {
v, err := strconv.ParseInt(sval, 0, 16)
if err != nil {
return 0, err
}
return int16(v), nil
}
// GetInt16 returns the int16 value of a flag with the given name
func (f *FlagSet) GetInt16(name string) (int16, error) {
val, err := f.getFlagType(name, "int16", int16Conv)
if err != nil {
return 0, err
}
return val.(int16), nil
}
// Int16Var defines an int16 flag with specified name, default value, and usage string.
// The argument p points to an int16 variable in which to store the value of the flag.
func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) {
f.VarP(newInt16Value(value, p), name, "", usage)
}
// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) {
f.VarP(newInt16Value(value, p), name, shorthand, usage)
}
// Int16Var defines an int16 flag with specified name, default value, and usage string.
// The argument p points to an int16 variable in which to store the value of the flag.
func Int16Var(p *int16, name string, value int16, usage string) {
CommandLine.VarP(newInt16Value(value, p), name, "", usage)
}
// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash.
func Int16VarP(p *int16, name, shorthand string, value int16, usage string) {
CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage)
}
// Int16 defines an int16 flag with specified name, default value, and usage string.
// The return value is the address of an int16 variable that stores the value of the flag.
func (f *FlagSet) Int16(name string, value int16, usage string) *int16 {
p := new(int16)
f.Int16VarP(p, name, "", value, usage)
return p
}
// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 {
p := new(int16)
f.Int16VarP(p, name, shorthand, value, usage)
return p
}
// Int16 defines an int16 flag with specified name, default value, and usage string.
// The return value is the address of an int16 variable that stores the value of the flag.
func Int16(name string, value int16, usage string) *int16 {
return CommandLine.Int16P(name, "", value, usage)
}
// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash.
func Int16P(name, shorthand string, value int16, usage string) *int16 {
return CommandLine.Int16P(name, shorthand, value, usage)
}

74
vendor/github.com/spf13/pflag/printusage_test.go generated vendored Normal file
View File

@@ -0,0 +1,74 @@
package pflag
import (
"bytes"
"io"
"testing"
)
const expectedOutput = ` --long-form Some description
--long-form2 Some description
with multiline
-s, --long-name Some description
-t, --long-name2 Some description with
multiline
`
func setUpPFlagSet(buf io.Writer) *FlagSet {
f := NewFlagSet("test", ExitOnError)
f.Bool("long-form", false, "Some description")
f.Bool("long-form2", false, "Some description\n with multiline")
f.BoolP("long-name", "s", false, "Some description")
f.BoolP("long-name2", "t", false, "Some description with\n multiline")
f.SetOutput(buf)
return f
}
func TestPrintUsage(t *testing.T) {
buf := bytes.Buffer{}
f := setUpPFlagSet(&buf)
f.PrintDefaults()
res := buf.String()
if res != expectedOutput {
t.Errorf("Expected \n%s \nActual \n%s", expectedOutput, res)
}
}
func setUpPFlagSet2(buf io.Writer) *FlagSet {
f := NewFlagSet("test", ExitOnError)
f.Bool("long-form", false, "Some description")
f.Bool("long-form2", false, "Some description\n with multiline")
f.BoolP("long-name", "s", false, "Some description")
f.BoolP("long-name2", "t", false, "Some description with\n multiline")
f.StringP("some-very-long-arg", "l", "test", "Some very long description having break the limit")
f.StringP("other-very-long-arg", "o", "long-default-value", "Some very long description having break the limit")
f.String("some-very-long-arg2", "very long default value", "Some very long description\nwith line break\nmultiple")
f.SetOutput(buf)
return f
}
const expectedOutput2 = ` --long-form Some description
--long-form2 Some description
with multiline
-s, --long-name Some description
-t, --long-name2 Some description with
multiline
-o, --other-very-long-arg string Some very long description having
break the limit (default
"long-default-value")
-l, --some-very-long-arg string Some very long description having
break the limit (default "test")
--some-very-long-arg2 string Some very long description
with line break
multiple (default "very long default
value")
`
func TestPrintUsage_2(t *testing.T) {
buf := bytes.Buffer{}
f := setUpPFlagSet2(&buf)
res := f.FlagUsagesWrapped(80)
if res != expectedOutput2 {
t.Errorf("Expected \n%q \nActual \n%q", expectedOutput2, res)
}
}

View File

@@ -52,7 +52,7 @@ func (f *FlagSet) GetStringArray(name string) ([]string, error) {
// StringArrayVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the values of the multiple flags.
// The value of each argument will not try to be separated by comma
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
f.VarP(newStringArrayValue(value, p), name, "", usage)
}
@@ -64,7 +64,7 @@ func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []s
// StringArrayVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
// The value of each argument will not try to be separated by comma
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func StringArrayVar(p *[]string, name string, value []string, usage string) {
CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
}
@@ -76,7 +76,7 @@ func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage
// StringArray defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
p := []string{}
f.StringArrayVarP(&p, name, "", value, usage)
@@ -92,7 +92,7 @@ func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage str
// StringArray defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func StringArray(name string, value []string, usage string) *[]string {
return CommandLine.StringArrayP(name, "", value, usage)
}

View File

@@ -82,6 +82,11 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
// StringSliceVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" -ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
f.VarP(newStringSliceValue(value, p), name, "", usage)
}
@@ -93,6 +98,11 @@ func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []s
// StringSliceVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" -ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func StringSliceVar(p *[]string, name string, value []string, usage string) {
CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
}
@@ -104,6 +114,11 @@ func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage
// StringSlice defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" -ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
p := []string{}
f.StringSliceVarP(&p, name, "", value, usage)
@@ -119,6 +134,11 @@ func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage str
// StringSlice defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" -ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func StringSlice(name string, value []string, usage string) *[]string {
return CommandLine.StringSliceP(name, "", value, usage)
}

149
vendor/github.com/spf13/pflag/string_to_int.go generated vendored Normal file
View File

@@ -0,0 +1,149 @@
package pflag
import (
"bytes"
"fmt"
"strconv"
"strings"
)
// -- stringToInt Value
type stringToIntValue struct {
value *map[string]int
changed bool
}
func newStringToIntValue(val map[string]int, p *map[string]int) *stringToIntValue {
ssv := new(stringToIntValue)
ssv.value = p
*ssv.value = val
return ssv
}
// Format: a=1,b=2
func (s *stringToIntValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make(map[string]int, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("%s must be formatted as key=value", pair)
}
var err error
out[kv[0]], err = strconv.Atoi(kv[1])
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
for k, v := range out {
(*s.value)[k] = v
}
}
s.changed = true
return nil
}
func (s *stringToIntValue) Type() string {
return "stringToInt"
}
func (s *stringToIntValue) String() string {
var buf bytes.Buffer
i := 0
for k, v := range *s.value {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(k)
buf.WriteRune('=')
buf.WriteString(strconv.Itoa(v))
i++
}
return "[" + buf.String() + "]"
}
func stringToIntConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if len(val) == 0 {
return map[string]int{}, nil
}
ss := strings.Split(val, ",")
out := make(map[string]int, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return nil, fmt.Errorf("%s must be formatted as key=value", pair)
}
var err error
out[kv[0]], err = strconv.Atoi(kv[1])
if err != nil {
return nil, err
}
}
return out, nil
}
// GetStringToInt return the map[string]int value of a flag with the given name
func (f *FlagSet) GetStringToInt(name string) (map[string]int, error) {
val, err := f.getFlagType(name, "stringToInt", stringToIntConv)
if err != nil {
return map[string]int{}, err
}
return val.(map[string]int), nil
}
// StringToIntVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]int variable in which to store the values of the multiple flags.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) {
f.VarP(newStringToIntValue(value, p), name, "", usage)
}
// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) {
f.VarP(newStringToIntValue(value, p), name, shorthand, usage)
}
// StringToIntVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]int variable in which to store the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) {
CommandLine.VarP(newStringToIntValue(value, p), name, "", usage)
}
// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash.
func StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) {
CommandLine.VarP(newStringToIntValue(value, p), name, shorthand, usage)
}
// StringToInt defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]int variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToInt(name string, value map[string]int, usage string) *map[string]int {
p := map[string]int{}
f.StringToIntVarP(&p, name, "", value, usage)
return &p
}
// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int {
p := map[string]int{}
f.StringToIntVarP(&p, name, shorthand, value, usage)
return &p
}
// StringToInt defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]int variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToInt(name string, value map[string]int, usage string) *map[string]int {
return CommandLine.StringToIntP(name, "", value, usage)
}
// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash.
func StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int {
return CommandLine.StringToIntP(name, shorthand, value, usage)
}

156
vendor/github.com/spf13/pflag/string_to_int_test.go generated vendored Normal file
View File

@@ -0,0 +1,156 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of ths2i source code s2i governed by a BSD-style
// license that can be found in the LICENSE file.
package pflag
import (
"bytes"
"fmt"
"strconv"
"testing"
)
func setUpS2IFlagSet(s2ip *map[string]int) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.StringToIntVar(s2ip, "s2i", map[string]int{}, "Command separated ls2it!")
return f
}
func setUpS2IFlagSetWithDefault(s2ip *map[string]int) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.StringToIntVar(s2ip, "s2i", map[string]int{"a": 1, "b": 2}, "Command separated ls2it!")
return f
}
func createS2IFlag(vals map[string]int) string {
var buf bytes.Buffer
i := 0
for k, v := range vals {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(k)
buf.WriteRune('=')
buf.WriteString(strconv.Itoa(v))
i++
}
return buf.String()
}
func TestEmptyS2I(t *testing.T) {
var s2i map[string]int
f := setUpS2IFlagSet(&s2i)
err := f.Parse([]string{})
if err != nil {
t.Fatal("expected no error; got", err)
}
getS2I, err := f.GetStringToInt("s2i")
if err != nil {
t.Fatal("got an error from GetStringToInt():", err)
}
if len(getS2I) != 0 {
t.Fatalf("got s2i %v with len=%d but expected length=0", getS2I, len(getS2I))
}
}
func TestS2I(t *testing.T) {
var s2i map[string]int
f := setUpS2IFlagSet(&s2i)
vals := map[string]int{"a": 1, "b": 2, "d": 4, "c": 3}
arg := fmt.Sprintf("--s2i=%s", createS2IFlag(vals))
err := f.Parse([]string{arg})
if err != nil {
t.Fatal("expected no error; got", err)
}
for k, v := range s2i {
if vals[k] != v {
t.Fatalf("expected s2i[%s] to be %d but got: %d", k, vals[k], v)
}
}
getS2I, err := f.GetStringToInt("s2i")
if err != nil {
t.Fatalf("got error: %v", err)
}
for k, v := range getS2I {
if vals[k] != v {
t.Fatalf("expected s2i[%s] to be %d but got: %d from GetStringToInt", k, vals[k], v)
}
}
}
func TestS2IDefault(t *testing.T) {
var s2i map[string]int
f := setUpS2IFlagSetWithDefault(&s2i)
vals := map[string]int{"a": 1, "b": 2}
err := f.Parse([]string{})
if err != nil {
t.Fatal("expected no error; got", err)
}
for k, v := range s2i {
if vals[k] != v {
t.Fatalf("expected s2i[%s] to be %d but got: %d", k, vals[k], v)
}
}
getS2I, err := f.GetStringToInt("s2i")
if err != nil {
t.Fatal("got an error from GetStringToInt():", err)
}
for k, v := range getS2I {
if vals[k] != v {
t.Fatalf("expected s2i[%s] to be %d from GetStringToInt but got: %d", k, vals[k], v)
}
}
}
func TestS2IWithDefault(t *testing.T) {
var s2i map[string]int
f := setUpS2IFlagSetWithDefault(&s2i)
vals := map[string]int{"a": 1, "b": 2}
arg := fmt.Sprintf("--s2i=%s", createS2IFlag(vals))
err := f.Parse([]string{arg})
if err != nil {
t.Fatal("expected no error; got", err)
}
for k, v := range s2i {
if vals[k] != v {
t.Fatalf("expected s2i[%s] to be %d but got: %d", k, vals[k], v)
}
}
getS2I, err := f.GetStringToInt("s2i")
if err != nil {
t.Fatal("got an error from GetStringToInt():", err)
}
for k, v := range getS2I {
if vals[k] != v {
t.Fatalf("expected s2i[%s] to be %d from GetStringToInt but got: %d", k, vals[k], v)
}
}
}
func TestS2ICalledTwice(t *testing.T) {
var s2i map[string]int
f := setUpS2IFlagSet(&s2i)
in := []string{"a=1,b=2", "b=3"}
expected := map[string]int{"a": 1, "b": 3}
argfmt := "--s2i=%s"
arg1 := fmt.Sprintf(argfmt, in[0])
arg2 := fmt.Sprintf(argfmt, in[1])
err := f.Parse([]string{arg1, arg2})
if err != nil {
t.Fatal("expected no error; got", err)
}
for i, v := range s2i {
if expected[i] != v {
t.Fatalf("expected s2i[%s] to be %d but got: %d", i, expected[i], v)
}
}
}

160
vendor/github.com/spf13/pflag/string_to_string.go generated vendored Normal file
View File

@@ -0,0 +1,160 @@
package pflag
import (
"bytes"
"encoding/csv"
"fmt"
"strings"
)
// -- stringToString Value
type stringToStringValue struct {
value *map[string]string
changed bool
}
func newStringToStringValue(val map[string]string, p *map[string]string) *stringToStringValue {
ssv := new(stringToStringValue)
ssv.value = p
*ssv.value = val
return ssv
}
// Format: a=1,b=2
func (s *stringToStringValue) Set(val string) error {
var ss []string
n := strings.Count(val, "=")
switch n {
case 0:
return fmt.Errorf("%s must be formatted as key=value", val)
case 1:
ss = append(ss, strings.Trim(val, `"`))
default:
r := csv.NewReader(strings.NewReader(val))
var err error
ss, err = r.Read()
if err != nil {
return err
}
}
out := make(map[string]string, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("%s must be formatted as key=value", pair)
}
out[kv[0]] = kv[1]
}
if !s.changed {
*s.value = out
} else {
for k, v := range out {
(*s.value)[k] = v
}
}
s.changed = true
return nil
}
func (s *stringToStringValue) Type() string {
return "stringToString"
}
func (s *stringToStringValue) String() string {
records := make([]string, 0, len(*s.value)>>1)
for k, v := range *s.value {
records = append(records, k+"="+v)
}
var buf bytes.Buffer
w := csv.NewWriter(&buf)
if err := w.Write(records); err != nil {
panic(err)
}
w.Flush()
return "[" + strings.TrimSpace(buf.String()) + "]"
}
func stringToStringConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if len(val) == 0 {
return map[string]string{}, nil
}
r := csv.NewReader(strings.NewReader(val))
ss, err := r.Read()
if err != nil {
return nil, err
}
out := make(map[string]string, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return nil, fmt.Errorf("%s must be formatted as key=value", pair)
}
out[kv[0]] = kv[1]
}
return out, nil
}
// GetStringToString return the map[string]string value of a flag with the given name
func (f *FlagSet) GetStringToString(name string) (map[string]string, error) {
val, err := f.getFlagType(name, "stringToString", stringToStringConv)
if err != nil {
return map[string]string{}, err
}
return val.(map[string]string), nil
}
// StringToStringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]string variable in which to store the values of the multiple flags.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) {
f.VarP(newStringToStringValue(value, p), name, "", usage)
}
// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) {
f.VarP(newStringToStringValue(value, p), name, shorthand, usage)
}
// StringToStringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]string variable in which to store the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) {
CommandLine.VarP(newStringToStringValue(value, p), name, "", usage)
}
// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash.
func StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) {
CommandLine.VarP(newStringToStringValue(value, p), name, shorthand, usage)
}
// StringToString defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToString(name string, value map[string]string, usage string) *map[string]string {
p := map[string]string{}
f.StringToStringVarP(&p, name, "", value, usage)
return &p
}
// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string {
p := map[string]string{}
f.StringToStringVarP(&p, name, shorthand, value, usage)
return &p
}
// StringToString defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToString(name string, value map[string]string, usage string) *map[string]string {
return CommandLine.StringToStringP(name, "", value, usage)
}
// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash.
func StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string {
return CommandLine.StringToStringP(name, shorthand, value, usage)
}

162
vendor/github.com/spf13/pflag/string_to_string_test.go generated vendored Normal file
View File

@@ -0,0 +1,162 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of ths2s source code s2s governed by a BSD-style
// license that can be found in the LICENSE file.
package pflag
import (
"bytes"
"encoding/csv"
"fmt"
"strings"
"testing"
)
func setUpS2SFlagSet(s2sp *map[string]string) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.StringToStringVar(s2sp, "s2s", map[string]string{}, "Command separated ls2st!")
return f
}
func setUpS2SFlagSetWithDefault(s2sp *map[string]string) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.StringToStringVar(s2sp, "s2s", map[string]string{"da": "1", "db": "2", "de": "5,6"}, "Command separated ls2st!")
return f
}
func createS2SFlag(vals map[string]string) string {
records := make([]string, 0, len(vals)>>1)
for k, v := range vals {
records = append(records, k+"="+v)
}
var buf bytes.Buffer
w := csv.NewWriter(&buf)
if err := w.Write(records); err != nil {
panic(err)
}
w.Flush()
return strings.TrimSpace(buf.String())
}
func TestEmptyS2S(t *testing.T) {
var s2s map[string]string
f := setUpS2SFlagSet(&s2s)
err := f.Parse([]string{})
if err != nil {
t.Fatal("expected no error; got", err)
}
getS2S, err := f.GetStringToString("s2s")
if err != nil {
t.Fatal("got an error from GetStringToString():", err)
}
if len(getS2S) != 0 {
t.Fatalf("got s2s %v with len=%d but expected length=0", getS2S, len(getS2S))
}
}
func TestS2S(t *testing.T) {
var s2s map[string]string
f := setUpS2SFlagSet(&s2s)
vals := map[string]string{"a": "1", "b": "2", "d": "4", "c": "3", "e": "5,6"}
arg := fmt.Sprintf("--s2s=%s", createS2SFlag(vals))
err := f.Parse([]string{arg})
if err != nil {
t.Fatal("expected no error; got", err)
}
for k, v := range s2s {
if vals[k] != v {
t.Fatalf("expected s2s[%s] to be %s but got: %s", k, vals[k], v)
}
}
getS2S, err := f.GetStringToString("s2s")
if err != nil {
t.Fatalf("got error: %v", err)
}
for k, v := range getS2S {
if vals[k] != v {
t.Fatalf("expected s2s[%s] to be %s but got: %s from GetStringToString", k, vals[k], v)
}
}
}
func TestS2SDefault(t *testing.T) {
var s2s map[string]string
f := setUpS2SFlagSetWithDefault(&s2s)
vals := map[string]string{"da": "1", "db": "2", "de": "5,6"}
err := f.Parse([]string{})
if err != nil {
t.Fatal("expected no error; got", err)
}
for k, v := range s2s {
if vals[k] != v {
t.Fatalf("expected s2s[%s] to be %s but got: %s", k, vals[k], v)
}
}
getS2S, err := f.GetStringToString("s2s")
if err != nil {
t.Fatal("got an error from GetStringToString():", err)
}
for k, v := range getS2S {
if vals[k] != v {
t.Fatalf("expected s2s[%s] to be %s from GetStringToString but got: %s", k, vals[k], v)
}
}
}
func TestS2SWithDefault(t *testing.T) {
var s2s map[string]string
f := setUpS2SFlagSetWithDefault(&s2s)
vals := map[string]string{"a": "1", "b": "2", "e": "5,6"}
arg := fmt.Sprintf("--s2s=%s", createS2SFlag(vals))
err := f.Parse([]string{arg})
if err != nil {
t.Fatal("expected no error; got", err)
}
for k, v := range s2s {
if vals[k] != v {
t.Fatalf("expected s2s[%s] to be %s but got: %s", k, vals[k], v)
}
}
getS2S, err := f.GetStringToString("s2s")
if err != nil {
t.Fatal("got an error from GetStringToString():", err)
}
for k, v := range getS2S {
if vals[k] != v {
t.Fatalf("expected s2s[%s] to be %s from GetStringToString but got: %s", k, vals[k], v)
}
}
}
func TestS2SCalledTwice(t *testing.T) {
var s2s map[string]string
f := setUpS2SFlagSet(&s2s)
in := []string{"a=1,b=2", "b=3", `"e=5,6"`, `f=7,8`}
expected := map[string]string{"a": "1", "b": "3", "e": "5,6", "f": "7,8"}
argfmt := "--s2s=%s"
arg0 := fmt.Sprintf(argfmt, in[0])
arg1 := fmt.Sprintf(argfmt, in[1])
arg2 := fmt.Sprintf(argfmt, in[2])
arg3 := fmt.Sprintf(argfmt, in[3])
err := f.Parse([]string{arg0, arg1, arg2, arg3})
if err != nil {
t.Fatal("expected no error; got", err)
}
if len(s2s) != len(expected) {
t.Fatalf("expected %d flags; got %d flags", len(expected), len(s2s))
}
for i, v := range s2s {
if expected[i] != v {
t.Fatalf("expected s2s[%s] to be %s but got: %s", i, expected[i], v)
}
}
}