diff --git a/glide.lock b/glide.lock index efcf86103..2def07991 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ hash: 5fdc0d878c9c89c11572d15e0ebf1616840ff0fdd45350fd453461d668c8095f -updated: 2020-02-22T07:46:48.738180303-08:00 +updated: 2020-03-18T08:36:55.623354484-07:00 imports: - name: github.com/beorn7/perks version: 3ac7bf7a47d159a033b107610db8a1b6575507a4 @@ -31,11 +31,11 @@ imports: subpackages: - log - name: github.com/evanphx/json-patch - version: bf22ed9311622d93e213ba31e4ae7a5771e5d379 + version: 5858425f75500d40c52783dce87d085a483ce135 - name: github.com/getsentry/raven-go version: c977f96e109525a5d8fa10a19165341f601f38b0 - name: github.com/ghodss/yaml - version: 25d852aebe32c875e9c044af3eef9c7dc6bc777f + version: 73d445a93680fa1a78ae23a5839bad48f32ba1ee - name: github.com/go-openapi/jsonpointer version: ef5f0afec364d3b9396b7b77b43dbe26bf1f8004 - name: github.com/go-openapi/jsonreference @@ -172,7 +172,7 @@ imports: - operator/listers/operator/v1 - operator/listers/operator/v1alpha1 - name: github.com/openshift/library-go - version: 2cf86bbd930b78997e198b204a59b1711bad3c02 + version: d58edcb9e7bca8b6c77e261db8df547364f69fb2 subpackages: - pkg/config/client - pkg/config/clusteroperator/v1helpers @@ -197,10 +197,8 @@ imports: - pkg/serviceability - name: github.com/pborman/uuid version: ca53cad383cad2479bbba7f7a1a05797ec1386e4 -- name: github.com/pkg/errors - version: 645ef00459ed84a119197bfb8d8205042c6df63d - name: github.com/pkg/profile - version: acd64d450fd45fb2afa41f833f3788c8a7797219 + version: f6fe06335df110bcf1ed6d4e852b760bfc15beee - name: github.com/prometheus/client_golang version: 505eaef017263e299324067d40ca2c48f6a2cf50 subpackages: @@ -227,7 +225,7 @@ imports: - name: github.com/sirupsen/logrus version: 89742aefa4b206dcf400792f3bd35b542998eb3b - name: github.com/spf13/cobra - version: 39cf99f556817dc31535a3fbc8a60c7fbd70ba56 + version: 95f2f73ed97e57387762620175ccdc277a8597a0 - name: github.com/spf13/pflag version: 2e9d26c8c37aae03e3f9d4e90b7116f5accb7cab - name: golang.org/x/crypto @@ -273,7 +271,7 @@ imports: subpackages: - rate - name: google.golang.org/appengine - version: b6ce0843b556e44e6416df5c2fd05db0869cc8d4 + version: 54a98f90d1c46b7731eb8fb305d2a321c30ef610 subpackages: - internal - internal/base @@ -767,7 +765,7 @@ imports: - typed - value - name: sigs.k8s.io/yaml - version: 9fc95527decd95bb9d28cc2eab08179b2d0f6971 + version: fd68e9863619f6ec2fdd8625fe1f02e7c877e480 testImports: - name: github.com/google/uuid - version: c2e93f3ae59f2904160ceaab466009f965df46d6 + version: 0cd6bf5da1e1c83f8b45653022c74f71af0538a4 diff --git a/pkg/operator/rotate.go b/pkg/operator/rotate.go index 267fce2b9..c0490336f 100644 --- a/pkg/operator/rotate.go +++ b/pkg/operator/rotate.go @@ -5,6 +5,7 @@ import ( "crypto/x509" "encoding/json" "fmt" + "math/big" "time" corev1 "k8s.io/api/core/v1" @@ -197,6 +198,19 @@ func createIntermediateCACert(targetCACert, signingCACert *x509.Certificate, sig // Enable key identity chaining template.AuthorityKeyId = signingCACert.SubjectKeyId + // Set a new serial number so that the intermediate CA cert is + // differentiated from the target CA cert. This ensures that a serving + // cert bundle that includes the issuing CA cert and an intermediate CA + // cert generated by this function - with the issuing CA cert as the + // target and the previous CA as the signer - will not result in + // SEC_ERROR_REUSED_ISSUER_AND_SERIAL when read by applications like curl. + serialGenerator := crypto.RandomSerialGenerator{} + serial, err := serialGenerator.Next(template) + if err != nil { + return nil, fmt.Errorf("failed to find next serial number: %v", err) + } + template.SerialNumber = big.NewInt(serial) + // Update the expiry if necessary if expiry != nil { template.NotAfter = *expiry diff --git a/pkg/operator/rotate_test.go b/pkg/operator/rotate_test.go index 89d020735..7ced90640 100644 --- a/pkg/operator/rotate_test.go +++ b/pkg/operator/rotate_test.go @@ -245,3 +245,35 @@ func TestRotateSigningCA(t *testing.T) { dnsName := oldServingCert.Certs[0].Subject.CommonName util.CheckRotation(t, dnsName, oldCertPEM, oldKeyPEM, oldBundlePEM, newCertPEM, newKeyPEM, newBundlePEM) } + +// TestCreateIntermediateCACert checks that the intermediate CA cert +// created by signing a target CA cert supports identity key chaining +// and uses a serial number distinct from that of the target CA cert. +func TestCreateIntermediateCACert(t *testing.T) { + // Create the signing CA + signingCAConfig, err := crypto.MakeSelfSignedCAConfig("foo", signingCertificateLifetimeInDays) + if err != nil { + t.Fatalf("error generating a new ca: %v", err) + } + signingCACert := signingCAConfig.Certs[0] + + // Create the CA targeted for signing + targetCAConfig, err := crypto.MakeSelfSignedCAConfig("foo", signingCertificateLifetimeInDays) + if err != nil { + t.Fatalf("error generating a new ca: %v", err) + } + targetCACert := targetCAConfig.Certs[0] + + intermediateCACert, err := createIntermediateCACert(targetCACert, signingCACert, signingCAConfig.Key.(*rsa.PrivateKey), nil) + if err != nil { + t.Fatalf("Failed to create intermediate CA cert: %v", err) + } + + if bytes.Compare(intermediateCACert.AuthorityKeyId, signingCACert.SubjectKeyId) != 0 { + t.Fatalf("Expected intermediate CA cert AuthorityKeyId to match signing CA cert SubjectKeyId") + } + + if intermediateCACert.SerialNumber.Cmp(targetCACert.SerialNumber) == 0 { + t.Fatalf("Expected intermediate CA cert serial number to differ from serial number of target CA cert") + } +} diff --git a/vendor/github.com/evanphx/json-patch/README.md b/vendor/github.com/evanphx/json-patch/README.md index f1ae56922..9c7f87f7c 100644 --- a/vendor/github.com/evanphx/json-patch/README.md +++ b/vendor/github.com/evanphx/json-patch/README.md @@ -1,5 +1,5 @@ # JSON-Patch -`jsonpatch` is a library which provides functionality for both applying +`jsonpatch` is a library which provides functionallity for both applying [RFC6902 JSON patches](http://tools.ietf.org/html/rfc6902) against documents, as well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ietf.org/html/rfc7396). @@ -164,7 +164,7 @@ func main() { } if !jsonpatch.Equal(original, different) { - fmt.Println(`"original" is _not_ structurally equal to "different"`) + fmt.Println(`"original" is _not_ structurally equal to "similar"`) } } ``` @@ -173,7 +173,7 @@ When ran, you get the following output: ```bash $ go run main.go "original" is structurally equal to "similar" -"original" is _not_ structurally equal to "different" +"original" is _not_ structurally equal to "similar" ``` ## Combine merge patches diff --git a/vendor/github.com/evanphx/json-patch/go.mod b/vendor/github.com/evanphx/json-patch/go.mod deleted file mode 100644 index a858cab29..000000000 --- a/vendor/github.com/evanphx/json-patch/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module github.com/evanphx/json-patch - -go 1.12 - -require github.com/pkg/errors v0.8.1 diff --git a/vendor/github.com/evanphx/json-patch/go.sum b/vendor/github.com/evanphx/json-patch/go.sum deleted file mode 100644 index f29ab350a..000000000 --- a/vendor/github.com/evanphx/json-patch/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= diff --git a/vendor/github.com/evanphx/json-patch/merge.go b/vendor/github.com/evanphx/json-patch/merge.go index 5dc6d344a..6806c4c20 100644 --- a/vendor/github.com/evanphx/json-patch/merge.go +++ b/vendor/github.com/evanphx/json-patch/merge.go @@ -307,8 +307,10 @@ func matchesValue(av, bv interface{}) bool { return true case map[string]interface{}: bt := bv.(map[string]interface{}) - if len(bt) != len(at) { - return false + for key := range at { + if !matchesValue(at[key], bt[key]) { + return false + } } for key := range bt { if !matchesValue(at[key], bt[key]) { diff --git a/vendor/github.com/evanphx/json-patch/merge_test.go b/vendor/github.com/evanphx/json-patch/merge_test.go index c87b078d9..994b1b59e 100644 --- a/vendor/github.com/evanphx/json-patch/merge_test.go +++ b/vendor/github.com/evanphx/json-patch/merge_test.go @@ -1,7 +1,6 @@ package jsonpatch import ( - "fmt" "strings" "testing" ) @@ -448,45 +447,6 @@ func TestCreateMergePatchComplexAddAll(t *testing.T) { } } -// createNestedMap created a series of nested map objects such that the number of -// objects is roughly 2^n (precisely, 2^(n+1)-1). -func createNestedMap(m map[string]interface{}, depth int, objectCount *int) { - if depth == 0 { - return - } - for i := 0; i< 2;i++ { - nested := map[string]interface{}{} - *objectCount += 1 - createNestedMap(nested, depth-1, objectCount) - m[fmt.Sprintf("key-%v", i)] = nested - } -} - -func benchmarkMatchesValueWithDeeplyNestedFields(depth int, b *testing.B) { - a := map[string]interface{}{} - objCount := 1 - createNestedMap(a, depth, &objCount) - b.ResetTimer() - b.Run(fmt.Sprintf("objectCount=%v", objCount), func(b *testing.B) { - for i := 0; i < b.N; i++ { - if !matchesValue(a, a) { - b.Errorf("Should be equal") - } - } - }) -} - -func BenchmarkMatchesValue1(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(1, b) } -func BenchmarkMatchesValue2(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(2, b) } -func BenchmarkMatchesValue3(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(3, b) } -func BenchmarkMatchesValue4(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(4, b) } -func BenchmarkMatchesValue5(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(5, b) } -func BenchmarkMatchesValue6(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(6, b) } -func BenchmarkMatchesValue7(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(7, b) } -func BenchmarkMatchesValue8(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(8, b) } -func BenchmarkMatchesValue9(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(9, b) } -func BenchmarkMatchesValue10(b *testing.B) { benchmarkMatchesValueWithDeeplyNestedFields(10, b) } - func TestCreateMergePatchComplexRemoveAll(t *testing.T) { doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` exp := `{"a":null,"f":null,"hello":null,"i":null,"n":null,"nested":null,"pi":null,"t":null}` diff --git a/vendor/github.com/evanphx/json-patch/patch.go b/vendor/github.com/evanphx/json-patch/patch.go index 0e5034b0a..c9cf59021 100644 --- a/vendor/github.com/evanphx/json-patch/patch.go +++ b/vendor/github.com/evanphx/json-patch/patch.go @@ -6,8 +6,6 @@ import ( "fmt" "strconv" "strings" - - "github.com/pkg/errors" ) const ( @@ -26,14 +24,6 @@ var ( AccumulatedCopySizeLimit int64 = 0 ) -var ( - ErrTestFailed = errors.New("test failed") - ErrMissing = errors.New("missing value") - ErrUnknownType = errors.New("unknown object type") - ErrInvalid = errors.New("invalid state detected") - ErrInvalidIndex = errors.New("invalid index referenced") -) - type lazyNode struct { raw *json.RawMessage doc partialDoc @@ -41,11 +31,10 @@ type lazyNode struct { which int } -// Operation is a single JSON-Patch step, such as a single 'add' operation. -type Operation map[string]*json.RawMessage +type operation map[string]*json.RawMessage -// Patch is an ordered collection of Operations. -type Patch []Operation +// Patch is an ordered collection of operations. +type Patch []operation type partialDoc map[string]*lazyNode type partialArray []*lazyNode @@ -70,7 +59,7 @@ func (n *lazyNode) MarshalJSON() ([]byte, error) { case eAry: return json.Marshal(n.ary) default: - return nil, ErrUnknownType + return nil, fmt.Errorf("Unknown type") } } @@ -102,7 +91,7 @@ func (n *lazyNode) intoDoc() (*partialDoc, error) { } if n.raw == nil { - return nil, ErrInvalid + return nil, fmt.Errorf("Unable to unmarshal nil pointer as partial document") } err := json.Unmarshal(*n.raw, &n.doc) @@ -121,7 +110,7 @@ func (n *lazyNode) intoAry() (*partialArray, error) { } if n.raw == nil { - return nil, ErrInvalid + return nil, fmt.Errorf("Unable to unmarshal nil pointer as partial array") } err := json.Unmarshal(*n.raw, &n.ary) @@ -202,10 +191,6 @@ func (n *lazyNode) equal(o *lazyNode) bool { return false } - if len(n.doc) != len(o.doc) { - return false - } - for k, v := range n.doc { ov, ok := o.doc[k] @@ -242,8 +227,7 @@ func (n *lazyNode) equal(o *lazyNode) bool { return true } -// Kind reads the "op" field of the Operation. -func (o Operation) Kind() string { +func (o operation) kind() string { if obj, ok := o["op"]; ok && obj != nil { var op string @@ -259,41 +243,39 @@ func (o Operation) Kind() string { return "unknown" } -// Path reads the "path" field of the Operation. -func (o Operation) Path() (string, error) { +func (o operation) path() string { if obj, ok := o["path"]; ok && obj != nil { var op string err := json.Unmarshal(*obj, &op) if err != nil { - return "unknown", err + return "unknown" } - return op, nil + return op } - return "unknown", errors.Wrapf(ErrMissing, "operation missing path field") + return "unknown" } -// From reads the "from" field of the Operation. -func (o Operation) From() (string, error) { +func (o operation) from() string { if obj, ok := o["from"]; ok && obj != nil { var op string err := json.Unmarshal(*obj, &op) if err != nil { - return "unknown", err + return "unknown" } - return op, nil + return op } - return "unknown", errors.Wrapf(ErrMissing, "operation, missing from field") + return "unknown" } -func (o Operation) value() *lazyNode { +func (o operation) value() *lazyNode { if obj, ok := o["value"]; ok { return newLazyNode(obj) } @@ -301,23 +283,6 @@ func (o Operation) value() *lazyNode { return nil } -// ValueInterface decodes the operation value into an interface. -func (o Operation) ValueInterface() (interface{}, error) { - if obj, ok := o["value"]; ok && obj != nil { - var v interface{} - - err := json.Unmarshal(*obj, &v) - - if err != nil { - return nil, err - } - - return v, nil - } - - return nil, errors.Wrapf(ErrMissing, "operation, missing value field") -} - func isArray(buf []byte) bool { Loop: for _, c := range buf { @@ -388,17 +353,13 @@ func (d *partialDoc) add(key string, val *lazyNode) error { } func (d *partialDoc) get(key string) (*lazyNode, error) { - v, ok := (*d)[key] - if !ok { - return v, errors.Wrapf(ErrMissing, "unable to get nonexistent key: %s", key) - } - return v, nil + return (*d)[key], nil } func (d *partialDoc) remove(key string) error { _, ok := (*d)[key] if !ok { - return errors.Wrapf(ErrMissing, "unable to remove nonexistent key: %s", key) + return fmt.Errorf("Unable to remove nonexistent key: %s", key) } delete(*d, key) @@ -424,7 +385,7 @@ func (d *partialArray) add(key string, val *lazyNode) error { idx, err := strconv.Atoi(key) if err != nil { - return errors.Wrapf(err, "value was not a proper array index: '%s'", key) + return err } sz := len(*d) + 1 @@ -434,17 +395,17 @@ func (d *partialArray) add(key string, val *lazyNode) error { cur := *d if idx >= len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d", idx) } - if idx < 0 { - if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } + if SupportNegativeIndices { if idx < -len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d", idx) + } + + if idx < 0 { + idx += len(ary) } - idx += len(ary) } copy(ary[0:idx], cur[0:idx]) @@ -463,7 +424,7 @@ func (d *partialArray) get(key string) (*lazyNode, error) { } if idx >= len(*d) { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return nil, fmt.Errorf("Unable to access invalid index: %d", idx) } return (*d)[idx], nil @@ -478,17 +439,17 @@ func (d *partialArray) remove(key string) error { cur := *d if idx >= len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d", idx) } - if idx < 0 { - if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } + if SupportNegativeIndices { if idx < -len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d", idx) + } + + if idx < 0 { + idx += len(cur) } - idx += len(cur) } ary := make([]*lazyNode, len(cur)-1) @@ -501,189 +462,140 @@ func (d *partialArray) remove(key string) error { } -func (p Patch) add(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "add operation failed to decode path") - } +func (p Patch) add(doc *container, op operation) error { + path := op.path() con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "add operation does not apply: doc is missing path: \"%s\"", path) + return fmt.Errorf("jsonpatch add operation does not apply: doc is missing path: \"%s\"", path) } - err = con.add(key, op.value()) - if err != nil { - return errors.Wrapf(err, "error in add for path: '%s'", path) - } - - return nil + return con.add(key, op.value()) } -func (p Patch) remove(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "remove operation failed to decode path") - } +func (p Patch) remove(doc *container, op operation) error { + path := op.path() con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "remove operation does not apply: doc is missing path: \"%s\"", path) - } - - err = con.remove(key) - if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) + return fmt.Errorf("jsonpatch remove operation does not apply: doc is missing path: \"%s\"", path) } - return nil + return con.remove(key) } -func (p Patch) replace(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "replace operation failed to decode path") - } +func (p Patch) replace(doc *container, op operation) error { + path := op.path() con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing path: %s", path) + return fmt.Errorf("jsonpatch replace operation does not apply: doc is missing path: %s", path) } _, ok := con.get(key) if ok != nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing key: %s", path) + return fmt.Errorf("jsonpatch replace operation does not apply: doc is missing key: %s", path) } - err = con.set(key, op.value()) - if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) - } - - return nil + return con.set(key, op.value()) } -func (p Patch) move(doc *container, op Operation) error { - from, err := op.From() - if err != nil { - return errors.Wrapf(err, "move operation failed to decode from") - } +func (p Patch) move(doc *container, op operation) error { + from := op.from() con, key := findObject(doc, from) if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing from path: %s", from) + return fmt.Errorf("jsonpatch move operation does not apply: doc is missing from path: %s", from) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) + return err } err = con.remove(key) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) + return err } - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "move operation failed to decode path") - } + path := op.path() con, key = findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing destination path: %s", path) - } - - err = con.add(key, val) - if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", path) + return fmt.Errorf("jsonpatch move operation does not apply: doc is missing destination path: %s", path) } - return nil + return con.add(key, val) } -func (p Patch) test(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "test operation failed to decode path") - } +func (p Patch) test(doc *container, op operation) error { + path := op.path() con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "test operation does not apply: is missing path: %s", path) + return fmt.Errorf("jsonpatch test operation does not apply: is missing path: %s", path) } val, err := con.get(key) - if err != nil && errors.Cause(err) != ErrMissing { - return errors.Wrapf(err, "error in test for path: '%s'", path) + + if err != nil { + return err } if val == nil { if op.value().raw == nil { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("Testing value %s failed", path) } else if op.value() == nil { - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("Testing value %s failed", path) } if val.equal(op.value()) { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("Testing value %s failed", path) } -func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64) error { - from, err := op.From() - if err != nil { - return errors.Wrapf(err, "copy operation failed to decode from") - } +func (p Patch) copy(doc *container, op operation, accumulatedCopySize *int64) error { + from := op.from() con, key := findObject(doc, from) if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing from path: %s", from) + return fmt.Errorf("jsonpatch copy operation does not apply: doc is missing from path: %s", from) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in copy for from: '%s'", from) + return err } - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "copy operation failed to decode path") - } + path := op.path() con, key = findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing destination path: %s", path) + return fmt.Errorf("jsonpatch copy operation does not apply: doc is missing destination path: %s", path) } valCopy, sz, err := deepCopy(val) if err != nil { - return errors.Wrapf(err, "error while performing deep copy") + return err } - (*accumulatedCopySize) += int64(sz) if AccumulatedCopySizeLimit > 0 && *accumulatedCopySize > AccumulatedCopySizeLimit { return NewAccumulatedCopySizeError(AccumulatedCopySizeLimit, *accumulatedCopySize) } - err = con.add(key, valCopy) - if err != nil { - return errors.Wrapf(err, "error while adding value during copy") - } - - return nil + return con.add(key, valCopy) } // Equal indicates if 2 JSON documents have the same structural equality. @@ -739,7 +651,7 @@ func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { var accumulatedCopySize int64 for _, op := range p { - switch op.Kind() { + switch op.kind() { case "add": err = p.add(&pd, op) case "remove": @@ -753,7 +665,7 @@ func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { case "copy": err = p.copy(&pd, op, &accumulatedCopySize) default: - err = fmt.Errorf("Unexpected kind: %s", op.Kind()) + err = fmt.Errorf("Unexpected kind: %s", op.kind()) } if err != nil { diff --git a/vendor/github.com/evanphx/json-patch/patch_test.go b/vendor/github.com/evanphx/json-patch/patch_test.go index 60c044f00..96bcef494 100644 --- a/vendor/github.com/evanphx/json-patch/patch_test.go +++ b/vendor/github.com/evanphx/json-patch/patch_test.go @@ -186,11 +186,6 @@ var Cases = []Case{ `[{"op": "copy", "path": "/foo/0", "from": "/foo"}]`, `{ "foo": [["bar"], "bar"]}`, }, - { - `{ "foo": null}`, - `[{"op": "copy", "path": "/bar", "from": "/foo"}]`, - `{ "foo": null, "bar": null}`, - }, { `{ "foo": ["bar","qux","baz"]}`, `[ { "op": "remove", "path": "/foo/-2"}]`, @@ -337,15 +332,6 @@ var BadCases = []BadCase{ `{ "foo": [ "all", "grass", "cows", "eat" ] }`, `[ { "op": "move", "from": "/foo/1", "path": "/foo/4" } ]`, }, - { - `{ "baz": "qux" }`, - `[ { "op": "replace", "path": "/foo", "value": "bar" } ]`, - }, - // Can't copy from non-existent "from" key. - { - `{ "foo": "bar"}`, - `[{"op": "copy", "path": "/qux", "from": "/baz"}]`, - }, } // This is not thread safe, so we cannot run patch tests in parallel. @@ -473,18 +459,6 @@ var TestCases = []TestCase{ false, "/foo", }, - { - `{ "foo": "bar" }`, - `[ { "op": "test", "path": "/baz", "value": "bar" } ]`, - false, - "/baz", - }, - { - `{ "foo": "bar" }`, - `[ { "op": "test", "path": "/baz", "value": null } ]`, - true, - "/baz", - }, } func TestAllTest(t *testing.T) { @@ -496,99 +470,10 @@ func TestAllTest(t *testing.T) { } else if !c.result && err == nil { t.Errorf("Testing passed when it should have faild: %s", err) } else if !c.result { - expected := fmt.Sprintf("testing value %s failed: test failed", c.failedPath) + expected := fmt.Sprintf("Testing value %s failed", c.failedPath) if err.Error() != expected { t.Errorf("Testing failed as expected but invalid message: expected [%s], got [%s]", expected, err) } } } } - -func TestAdd(t *testing.T) { - testCases := []struct { - name string - key string - val lazyNode - arr partialArray - rejectNegativeIndicies bool - err string - }{ - { - name: "should work", - key: "0", - val: lazyNode{}, - arr: partialArray{}, - }, - { - name: "index too large", - key: "1", - val: lazyNode{}, - arr: partialArray{}, - err: "Unable to access invalid index: 1: invalid index referenced", - }, - { - name: "negative should work", - key: "-1", - val: lazyNode{}, - arr: partialArray{}, - }, - { - name: "negative too small", - key: "-2", - val: lazyNode{}, - arr: partialArray{}, - err: "Unable to access invalid index: -2: invalid index referenced", - }, - { - name: "negative but negative disabled", - key: "-1", - val: lazyNode{}, - arr: partialArray{}, - rejectNegativeIndicies: true, - err: "Unable to access invalid index: -1: invalid index referenced", - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - SupportNegativeIndices = !tc.rejectNegativeIndicies - key := tc.key - arr := &tc.arr - val := &tc.val - err := arr.add(key, val) - if err == nil && tc.err != "" { - t.Errorf("Expected error but got none! %v", tc.err) - } else if err != nil && tc.err == "" { - t.Errorf("Did not expect error but go: %v", err) - } else if err != nil && err.Error() != tc.err { - t.Errorf("Expected error %v but got error %v", tc.err, err) - } - }) - } -} - -type EqualityCase struct { - a, b string - equal bool -} - -var EqualityCases = []EqualityCase{ - EqualityCase{ - `{"foo": "bar"}`, - `{"foo": "bar", "baz": "qux"}`, - false, - }, -} - -func TestEquality(t *testing.T) { - for _, tc := range EqualityCases { - got := Equal([]byte(tc.a), []byte(tc.b)) - if got != tc.equal { - t.Errorf("Expected Equal(%s, %s) to return %t, but got %t", tc.a, tc.b, tc.equal, got) - } - - got = Equal([]byte(tc.b), []byte(tc.a)) - if got != tc.equal { - t.Errorf("Expected Equal(%s, %s) to return %t, but got %t", tc.b, tc.a, tc.equal, got) - } - } -} diff --git a/vendor/github.com/ghodss/yaml/.travis.yml b/vendor/github.com/ghodss/yaml/.travis.yml index 98ad417e2..0e9d6edc0 100644 --- a/vendor/github.com/ghodss/yaml/.travis.yml +++ b/vendor/github.com/ghodss/yaml/.travis.yml @@ -1,8 +1,7 @@ language: go go: - - "1.9" - - "1.10" - - "1.11" + - 1.3 + - 1.4 script: - go test - go build diff --git a/vendor/github.com/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md index 0200f75b4..f8f7e3695 100644 --- a/vendor/github.com/ghodss/yaml/README.md +++ b/vendor/github.com/ghodss/yaml/README.md @@ -4,13 +4,13 @@ ## Introduction -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. +A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). ## Compatibility -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). +This package uses [go-yaml v2](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). ## Caveats @@ -44,8 +44,6 @@ import "github.com/ghodss/yaml" Usage is very similar to the JSON library: ```go -package main - import ( "fmt" @@ -53,8 +51,8 @@ import ( ) type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` + Name string `json:"name"` // Affects YAML field names too. + Age int `json:"name"` } func main() { @@ -67,13 +65,13 @@ func main() { } fmt.Println(string(y)) /* Output: - age: 30 name: John + age: 30 */ // Unmarshal the YAML back into a Person struct. var p2 Person - err = yaml.Unmarshal(y, &p2) + err := yaml.Unmarshal(y, &p2) if err != nil { fmt.Printf("err: %v\n", err) return @@ -88,14 +86,11 @@ func main() { `yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: ```go -package main - import ( "fmt" "github.com/ghodss/yaml" ) - func main() { j := []byte(`{"name": "John", "age": 30}`) y, err := yaml.JSONToYAML(j) diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go index 586007402..0bd3c2b46 100644 --- a/vendor/github.com/ghodss/yaml/fields.go +++ b/vendor/github.com/ghodss/yaml/fields.go @@ -45,11 +45,7 @@ func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.Te break } if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } + v.Set(reflect.New(v.Type().Elem())) } if v.Type().NumMethod() > 0 { if u, ok := v.Interface().(json.Unmarshaler); ok { diff --git a/vendor/github.com/ghodss/yaml/go.mod b/vendor/github.com/ghodss/yaml/go.mod deleted file mode 100644 index 8d9ad7b64..000000000 --- a/vendor/github.com/ghodss/yaml/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/ghodss/yaml - -require gopkg.in/yaml.v2 v2.2.2 diff --git a/vendor/github.com/ghodss/yaml/go.sum b/vendor/github.com/ghodss/yaml/go.sum deleted file mode 100644 index bd555a333..000000000 --- a/vendor/github.com/ghodss/yaml/go.sum +++ /dev/null @@ -1,3 +0,0 @@ -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go index dfd264d6c..c02beacb9 100644 --- a/vendor/github.com/ghodss/yaml/yaml.go +++ b/vendor/github.com/ghodss/yaml/yaml.go @@ -1,20 +1,9 @@ -// Package yaml provides a wrapper around go-yaml designed to enable a better -// way of handling YAML when marshaling to and from structs. -// -// In short, this package first converts YAML to JSON using go-yaml and then -// uses json.Marshal and json.Unmarshal to convert to or from the struct. This -// means that it effectively reuses the JSON struct tags as well as the custom -// JSON methods MarshalJSON and UnmarshalJSON unlike go-yaml. -// -// See also http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang -// -package yaml // import "github.com/ghodss/yaml" +package yaml import ( "bytes" "encoding/json" "fmt" - "io" "reflect" "strconv" @@ -26,41 +15,26 @@ import ( func Marshal(o interface{}) ([]byte, error) { j, err := json.Marshal(o) if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) + return nil, fmt.Errorf("error marshaling into JSON: ", err) } y, err := JSONToYAML(j) if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) + return nil, fmt.Errorf("error converting JSON to YAML: ", err) } return y, nil } -// JSONOpt is a decoding option for decoding from JSON format. -type JSONOpt func(*json.Decoder) *json.Decoder - -// Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object, -// optionally configuring the behavior of the JSON unmarshal. -func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error { - return unmarshal(yaml.Unmarshal, y, o, opts) -} - -// UnmarshalStrict is like Unmarshal except that any mapping keys that are -// duplicates will result in an error. -// To also be strict about unknown fields, add the DisallowUnknownFields option. -func UnmarshalStrict(y []byte, o interface{}, opts ...JSONOpt) error { - return unmarshal(yaml.UnmarshalStrict, y, o, opts) -} - -func unmarshal(f func(in []byte, out interface{}) (err error), y []byte, o interface{}, opts []JSONOpt) error { +// Converts YAML to JSON then uses JSON to unmarshal into an object. +func Unmarshal(y []byte, o interface{}) error { vo := reflect.ValueOf(o) - j, err := yamlToJSON(y, &vo, f) + j, err := yamlToJSON(y, &vo) if err != nil { return fmt.Errorf("error converting YAML to JSON: %v", err) } - err = jsonUnmarshal(bytes.NewReader(j), o, opts...) + err = json.Unmarshal(j, o) if err != nil { return fmt.Errorf("error unmarshaling JSON: %v", err) } @@ -68,28 +42,13 @@ func unmarshal(f func(in []byte, out interface{}) (err error), y []byte, o inter return nil } -// jsonUnmarshal unmarshals the JSON byte stream from the given reader into the -// object, optionally applying decoder options prior to decoding. We are not -// using json.Unmarshal directly as we want the chance to pass in non-default -// options. -func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error { - d := json.NewDecoder(r) - for _, opt := range opts { - d = opt(d) - } - if err := d.Decode(&o); err != nil { - return fmt.Errorf("while decoding JSON: %v", err) - } - return nil -} - // Convert JSON to YAML. func JSONToYAML(j []byte) ([]byte, error) { // Convert the JSON to an object. var jsonObj interface{} // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 + // etc.) when unmarshling to interface{}, it just picks float64 // universally. go-yaml does go through the effort of picking the right // number type, so we can preserve number type throughout this process. err := yaml.Unmarshal(j, &jsonObj) @@ -101,8 +60,8 @@ func JSONToYAML(j []byte) ([]byte, error) { return yaml.Marshal(jsonObj) } -// YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML, -// passing JSON through this method should be a no-op. +// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through +// this method should be a no-op. // // Things YAML can do that are not supported by JSON: // * In YAML you can have binary and null keys in your maps. These are invalid @@ -111,22 +70,14 @@ func JSONToYAML(j []byte) ([]byte, error) { // use binary data with this library, encode the data as base64 as usual but do // not use the !!binary tag in your YAML. This will ensure the original base64 // encoded data makes it all the way through to the JSON. -// -// For strict decoding of YAML, use YAMLToJSONStrict. func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil, yaml.Unmarshal) -} - -// YAMLToJSONStrict is like YAMLToJSON but enables strict YAML decoding, -// returning an error on any duplicate field names. -func YAMLToJSONStrict(y []byte) ([]byte, error) { - return yamlToJSON(y, nil, yaml.UnmarshalStrict) + return yamlToJSON(y, nil) } -func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, interface{}) error) ([]byte, error) { +func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { // Convert the YAML to an object. var yamlObj interface{} - err := yamlUnmarshal(y, &yamlObj) + err := yaml.Unmarshal(y, &yamlObj) if err != nil { return nil, err } @@ -134,7 +85,7 @@ func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, // YAML objects are not completely compatible with JSON objects (e.g. you // can have non-string keys in YAML). So, convert the YAML-compatible object // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilities happen along the way. + // incompatibilties happen along the way. jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) if err != nil { return nil, err diff --git a/vendor/github.com/ghodss/yaml/yaml_go110.go b/vendor/github.com/ghodss/yaml/yaml_go110.go deleted file mode 100644 index ab3e06a22..000000000 --- a/vendor/github.com/ghodss/yaml/yaml_go110.go +++ /dev/null @@ -1,14 +0,0 @@ -// This file contains changes that are only compatible with go 1.10 and onwards. - -// +build go1.10 - -package yaml - -import "encoding/json" - -// DisallowUnknownFields configures the JSON decoder to error out if unknown -// fields come along, instead of dropping them by default. -func DisallowUnknownFields(d *json.Decoder) *json.Decoder { - d.DisallowUnknownFields() - return d -} diff --git a/vendor/github.com/ghodss/yaml/yaml_go110_test.go b/vendor/github.com/ghodss/yaml/yaml_go110_test.go deleted file mode 100644 index 753ee3f6f..000000000 --- a/vendor/github.com/ghodss/yaml/yaml_go110_test.go +++ /dev/null @@ -1,100 +0,0 @@ -// +build go1.10 - -package yaml - -import ( - "fmt" - "reflect" - "strings" - "testing" -) - -func TestUnmarshalWithTags(t *testing.T) { - type WithTaggedField struct { - Field string `json:"field"` - } - - t.Run("Known tagged field", func(t *testing.T) { - y := []byte(`field: "hello"`) - v := WithTaggedField{} - if err := Unmarshal(y, &v, DisallowUnknownFields); err != nil { - t.Errorf("unexpected error: %v", err) - } - if v.Field != "hello" { - t.Errorf("v.Field=%v, want 'hello'", v.Field) - } - - }) - t.Run("With unknown tagged field", func(t *testing.T) { - y := []byte(`unknown: "hello"`) - v := WithTaggedField{} - err := Unmarshal(y, &v, DisallowUnknownFields) - if err == nil { - t.Errorf("want error because of unknown field, got : v=%#v", v) - } - }) - -} - -// TestUnmarshalStrictWithJSONOpts tests that we return an error if there are -// duplicate fields in the YAML input. -func TestUnmarshalStrictWithJSONOpts(t *testing.T) { - for _, tc := range []struct { - yaml []byte - opts []JSONOpt - want UnmarshalString - wantErr string - }{ - { - // By default, unknown field is ignored. - yaml: []byte("a: 1\nunknownField: 2"), - want: UnmarshalString{A: "1"}, - }, - { - // Unknown field produces an error with `DisallowUnknownFields` option. - yaml: []byte("a: 1\nunknownField: 2"), - opts: []JSONOpt{DisallowUnknownFields}, - wantErr: `unknown field "unknownField"`, - }, - } { - po := prettyFunctionName(tc.opts) - s := UnmarshalString{} - err := UnmarshalStrict(tc.yaml, &s, tc.opts...) - if tc.wantErr != "" && err == nil { - t.Errorf("UnmarshalStrict(%#q, &s, %v) = nil; want error", string(tc.yaml), po) - continue - } - if tc.wantErr == "" && err != nil { - t.Errorf("UnmarshalStrict(%#q, &s, %#v) = %v; want no error", string(tc.yaml), po, err) - continue - } - // We expect that duplicate fields are discovered during JSON unmarshalling. - if want := "error unmarshaling JSON"; tc.wantErr != "" && !strings.Contains(err.Error(), want) { - t.Errorf("UnmarshalStrict(%#q, &s, %#v) = %v; want err contains %#q", string(tc.yaml), po, err, want) - } - if tc.wantErr != "" && !strings.Contains(err.Error(), tc.wantErr) { - t.Errorf("UnmarshalStrict(%#q, &s, %#v) = %v; want err contains %#q", string(tc.yaml), po, err, tc.wantErr) - } - - // Only test content of `s` if parsing indicated no error. - // If we got an error, `s` may be partially parsed and contain some data. - if err != nil { - continue - } - - if !reflect.DeepEqual(s, tc.want) { - t.Errorf("UnmarshalStrict(%#q, &s, %#v) = %+#v; want %+#v", string(tc.yaml), po, s, tc.want) - } - } -} - -func ExampleUnknown() { - type WithTaggedField struct { - Field string `json:"field"` - } - y := []byte(`unknown: "hello"`) - v := WithTaggedField{} - fmt.Printf("%v\n", Unmarshal(y, &v, DisallowUnknownFields)) - // Ouptut: - // unmarshaling JSON: while decoding JSON: json: unknown field "unknown" -} diff --git a/vendor/github.com/ghodss/yaml/yaml_test.go b/vendor/github.com/ghodss/yaml/yaml_test.go index e31b402c5..0ae0954e9 100644 --- a/vendor/github.com/ghodss/yaml/yaml_test.go +++ b/vendor/github.com/ghodss/yaml/yaml_test.go @@ -4,9 +4,7 @@ import ( "fmt" "math" "reflect" - "runtime" "strconv" - "strings" "testing" ) @@ -21,7 +19,7 @@ type MarshalTest struct { func TestMarshal(t *testing.T) { f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32} - e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", int64(math.MaxInt64), f32String)) + e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", math.MaxInt64, f32String)) y, err := Marshal(s) if err != nil { @@ -64,186 +62,43 @@ func TestUnmarshal(t *testing.T) { y := []byte("a: 1") s1 := UnmarshalString{} e1 := UnmarshalString{A: "1"} - unmarshalEqual(t, y, &s1, &e1) + unmarshal(t, y, &s1, &e1) y = []byte("a: true") s1 = UnmarshalString{} e1 = UnmarshalString{A: "true"} - unmarshalEqual(t, y, &s1, &e1) + unmarshal(t, y, &s1, &e1) y = []byte("true: 1") s1 = UnmarshalString{} e1 = UnmarshalString{True: "1"} - unmarshalEqual(t, y, &s1, &e1) + unmarshal(t, y, &s1, &e1) y = []byte("a:\n a: 1") s2 := UnmarshalNestedString{} e2 := UnmarshalNestedString{NestedString{"1"}} - unmarshalEqual(t, y, &s2, &e2) + unmarshal(t, y, &s2, &e2) y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") s3 := UnmarshalSlice{} e3 := UnmarshalSlice{[]NestedSlice{NestedSlice{"abc", strPtr("def")}, NestedSlice{"123", strPtr("456")}}} - unmarshalEqual(t, y, &s3, &e3) + unmarshal(t, y, &s3, &e3) y = []byte("a:\n b: 1") s4 := UnmarshalStringMap{} e4 := UnmarshalStringMap{map[string]string{"b": "1"}} - unmarshalEqual(t, y, &s4, &e4) - - y = []byte(` -a: - name: TestA -b: - name: TestB -`) - type NamedThing struct { - Name string `json:"name"` - } - s5 := map[string]*NamedThing{} - e5 := map[string]*NamedThing{ - "a": &NamedThing{Name: "TestA"}, - "b": &NamedThing{Name: "TestB"}, - } - unmarshalEqual(t, y, &s5, &e5) + unmarshal(t, y, &s4, &e4) } -// TestUnmarshalNonStrict tests that we parse ambiguous YAML without error. -func TestUnmarshalNonStrict(t *testing.T) { - for _, tc := range []struct { - yaml []byte - want UnmarshalString - }{ - { - yaml: []byte("a: 1"), - want: UnmarshalString{A: "1"}, - }, - { - // Unknown field get ignored. - yaml: []byte("a: 1\nunknownField: 2"), - want: UnmarshalString{A: "1"}, - }, - { - // Unknown fields get ignored. - yaml: []byte("unknownOne: 2\na: 1\nunknownTwo: 2"), - want: UnmarshalString{A: "1"}, - }, - { - // Last declaration of `a` wins. - yaml: []byte("a: 1\na: 2"), - want: UnmarshalString{A: "2"}, - }, - { - // Even ignore first declaration of `a` with wrong type. - yaml: []byte("a: [1,2,3]\na: value-of-a"), - want: UnmarshalString{A: "value-of-a"}, - }, - { - // Last value of `a` and first and only mention of `true` are parsed. - yaml: []byte("true: string-value-of-yes\na: 1\na: [1,2,3]\na: value-of-a"), - want: UnmarshalString{A: "value-of-a", True: "string-value-of-yes"}, - }, - { - // In YAML, `YES` is a Boolean true. - yaml: []byte("true: YES"), - want: UnmarshalString{True: "true"}, - }, - } { - s := UnmarshalString{} - unmarshalEqual(t, tc.yaml, &s, &tc.want) - } -} - -// prettyFunctionName converts a slice of JSONOpt function pointers to a human -// readable string representation. -func prettyFunctionName(opts []JSONOpt) []string { - var r []string - for _, o := range opts { - r = append(r, runtime.FuncForPC(reflect.ValueOf(o).Pointer()).Name()) - } - return r -} - -func unmarshalEqual(t *testing.T, y []byte, s, e interface{}, opts ...JSONOpt) { - t.Helper() - err := Unmarshal(y, s, opts...) +func unmarshal(t *testing.T, y []byte, s, e interface{}) { + err := Unmarshal(y, s) if err != nil { - t.Errorf("Unmarshal(%#q, s, %v) = %v", string(y), prettyFunctionName(opts), err) - return + t.Errorf("error unmarshaling YAML: %v", err) } if !reflect.DeepEqual(s, e) { - t.Errorf("Unmarshal(%#q, s, %v) = %+#v; want %+#v", string(y), prettyFunctionName(opts), s, e) - } -} - -// TestUnmarshalStrict tests that we return an error on ambiguous YAML. -func TestUnmarshalStrict(t *testing.T) { - for _, tc := range []struct { - yaml []byte - want UnmarshalString - wantErr string - }{ - { - yaml: []byte("a: 1"), - want: UnmarshalString{A: "1"}, - }, - { - // Order does not matter. - yaml: []byte("true: 1\na: 2"), - want: UnmarshalString{A: "2", True: "1"}, - }, - { - // By default, unknown field is ignored. - yaml: []byte("a: 1\nunknownField: 2"), - want: UnmarshalString{A: "1"}, - }, - { - // Declaring `a` twice produces an error. - yaml: []byte("a: 1\na: 2"), - wantErr: `key "a" already set in map`, - }, - { - // Not ignoring first declaration of A with wrong type. - yaml: []byte("a: [1,2,3]\na: value-of-a"), - wantErr: `key "a" already set in map`, - }, - { - // Declaring field `true` twice. - yaml: []byte("true: string-value-of-yes\ntrue: 1"), - wantErr: `key true already set in map`, - }, - { - // In YAML, `YES` is a Boolean true. - yaml: []byte("true: YES"), - want: UnmarshalString{True: "true"}, - }, - } { - s := UnmarshalString{} - err := UnmarshalStrict(tc.yaml, &s) - if tc.wantErr != "" && err == nil { - t.Errorf("UnmarshalStrict(%#q, &s) = nil; want error", string(tc.yaml)) - continue - } - if tc.wantErr == "" && err != nil { - t.Errorf("UnmarshalStrict(%#q, &s) = %v; want no error", string(tc.yaml), err) - continue - } - // We only expect errors during unmarshalling YAML. - if want := "yaml: unmarshal errors"; tc.wantErr != "" && !strings.Contains(err.Error(), want) { - t.Errorf("UnmarshalStrict(%#q, &s) = %v; want err contains %#q", string(tc.yaml), err, want) - } - if tc.wantErr != "" && !strings.Contains(err.Error(), tc.wantErr) { - t.Errorf("UnmarshalStrict(%#q, &s) = %v; want err contains %#q", string(tc.yaml), err, tc.wantErr) - } - - // Even if there was an error, we continue the test: We expect that all - // errors occur during YAML unmarshalling. Such errors leaves `s` unmodified - // and the following check will compare default values of `UnmarshalString`. - - if !reflect.DeepEqual(s, tc.want) { - t.Errorf("UnmarshalStrict(%#q, &s) = %+#v; want %+#v", string(tc.yaml), s, tc.want) - } + t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", + e, s) } } @@ -414,16 +269,3 @@ func runCases(t *testing.T, runType RunType, cases []Case) { func strPtr(s string) *string { return &s } - -func TestYAMLToJSONStrict(t *testing.T) { - const data = ` -foo: bar -foo: baz -` - if _, err := YAMLToJSON([]byte(data)); err != nil { - t.Error("expected YAMLtoJSON to pass on duplicate field names") - } - if _, err := YAMLToJSONStrict([]byte(data)); err == nil { - t.Error("expected YAMLtoJSONStrict to fail on duplicate field names") - } -} diff --git a/vendor/github.com/google/uuid/uuid_test.go b/vendor/github.com/google/uuid/uuid_test.go index 2a43fb13f..e7876f151 100644 --- a/vendor/github.com/google/uuid/uuid_test.go +++ b/vendor/github.com/google/uuid/uuid_test.go @@ -479,46 +479,6 @@ func TestBadRand(t *testing.T) { } } -func TestSetRand(t *testing.T) { - myString := "805-9dd6-1a877cb526c678e71d38-7122-44c0-9b7c-04e7001cc78783ac3e82-47a3-4cc3-9951-13f3339d88088f5d685a-11f7-4078-ada9-de44ad2daeb7" - - SetRand(strings.NewReader(myString)) - uuid1 := New() - uuid2 := New() - - SetRand(strings.NewReader(myString)) - uuid3 := New() - uuid4 := New() - - if uuid1 != uuid3 { - t.Errorf("expected duplicates, got %q and %q", uuid1, uuid3) - } - if uuid2 != uuid4 { - t.Errorf("expected duplicates, got %q and %q", uuid2, uuid4) - } -} - -func TestRandomFromReader(t *testing.T) { - myString := "8059ddhdle77cb52" - r := bytes.NewReader([]byte(myString)) - r2 := bytes.NewReader([]byte(myString)) - uuid1, err := NewRandomFromReader(r) - if err != nil { - t.Errorf("failed generating UUID from a reader") - } - _, err = NewRandomFromReader(r) - if err == nil { - t.Errorf("expecting an error as reader has no more bytes. Got uuid. NewRandomFromReader may not be using the provided reader") - } - uuid3, err := NewRandomFromReader(r2) - if err != nil { - t.Errorf("failed generating UUID from a reader") - } - if uuid1 != uuid3 { - t.Errorf("expected duplicates, got %q and %q", uuid1, uuid3) - } -} - var asString = "f47ac10b-58cc-0372-8567-0e02b2c3d479" var asBytes = []byte(asString) diff --git a/vendor/github.com/google/uuid/version4.go b/vendor/github.com/google/uuid/version4.go index 9ad1abad0..84af91c9f 100644 --- a/vendor/github.com/google/uuid/version4.go +++ b/vendor/github.com/google/uuid/version4.go @@ -27,12 +27,8 @@ func New() UUID { // equivalent to the odds of creating a few tens of trillions of UUIDs in a // year and having one duplicate. func NewRandom() (UUID, error) { - return NewRandomFromReader(rander) -} - -func NewRandomFromReader(r io.Reader) (UUID, error) { var uuid UUID - _, err := io.ReadFull(r, uuid[:]) + _, err := io.ReadFull(rander, uuid[:]) if err != nil { return Nil, err } @@ -40,4 +36,3 @@ func NewRandomFromReader(r io.Reader) (UUID, error) { uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 return uuid, nil } - diff --git a/vendor/github.com/openshift/library-go/pkg/crypto/crypto.go b/vendor/github.com/openshift/library-go/pkg/crypto/crypto.go index a6cffed0d..5e8eb5b71 100644 --- a/vendor/github.com/openshift/library-go/pkg/crypto/crypto.go +++ b/vendor/github.com/openshift/library-go/pkg/crypto/crypto.go @@ -461,8 +461,16 @@ type RandomSerialGenerator struct { } func (s *RandomSerialGenerator) Next(template *x509.Certificate) (int64, error) { + return randomSerialNumber(), nil +} + +// randomSerialNumber returns a random int64 serial number based on +// time.Now. It is defined separately from the generator interface so +// that the caller doesn't have to worry about an input template or +// error - these are unnecessary when creating a random serial. +func randomSerialNumber() int64 { r := mathrand.New(mathrand.NewSource(time.Now().UTC().UnixNano())) - return r.Int63(), nil + return r.Int63() } // EnsureCA returns a CA, whether it was created (as opposed to pre-existing), and any error @@ -843,9 +851,13 @@ func newSigningCertificateTemplateForDuration(subject pkix.Name, caLifetime time SignatureAlgorithm: x509.SHA256WithRSA, - NotBefore: currentTime().Add(-1 * time.Second), - NotAfter: currentTime().Add(caLifetime), - SerialNumber: big.NewInt(1), + NotBefore: currentTime().Add(-1 * time.Second), + NotAfter: currentTime().Add(caLifetime), + + // Specify a random serial number to avoid the same issuer+serial + // number referring to different certs in a chain of trust if the + // signing certificate is ever rotated. + SerialNumber: big.NewInt(randomSerialNumber()), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, BasicConstraintsValid: true, diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1b..000000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 588ceca18..000000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.4.3 - - 1.5.4 - - 1.6.2 - - 1.7.1 - - tip - -script: - - go test -v ./... diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e75..000000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 273db3c98..000000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## Licence - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade0..000000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/bench_test.go b/vendor/github.com/pkg/errors/bench_test.go deleted file mode 100644 index 0416a3cbb..000000000 --- a/vendor/github.com/pkg/errors/bench_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// +build go1.7 - -package errors - -import ( - "fmt" - "testing" - - stderrors "errors" -) - -func noErrors(at, depth int) error { - if at >= depth { - return stderrors.New("no error") - } - return noErrors(at+1, depth) -} -func yesErrors(at, depth int) error { - if at >= depth { - return New("ye error") - } - return yesErrors(at+1, depth) -} - -func BenchmarkErrors(b *testing.B) { - var toperr error - type run struct { - stack int - std bool - } - runs := []run{ - {10, false}, - {10, true}, - {100, false}, - {100, true}, - {1000, false}, - {1000, true}, - } - for _, r := range runs { - part := "pkg/errors" - if r.std { - part = "errors" - } - name := fmt.Sprintf("%s-stack-%d", part, r.stack) - b.Run(name, func(b *testing.B) { - var err error - f := yesErrors - if r.std { - f = noErrors - } - b.ReportAllocs() - for i := 0; i < b.N; i++ { - err = f(0, r.stack) - } - b.StopTimer() - toperr = err - }) - } -} diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 842ee8045..000000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,269 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// and the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required the errors.WithStack and errors.WithMessage -// functions destructure errors.Wrap into its component operations of annotating -// an error with a stack trace and an a message, respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// causer interface is not exported by this package, but is considered a part -// of stable public API. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported -// -// %s print the error. If the error has a Cause it will be -// printed recursively -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface. -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// Where errors.StackTrace is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) -// } -// } -// -// stackTracer interface is not exported by this package, but is considered a part -// of stable public API. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is call, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/errors_test.go b/vendor/github.com/pkg/errors/errors_test.go deleted file mode 100644 index 1d8c63558..000000000 --- a/vendor/github.com/pkg/errors/errors_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "reflect" - "testing" -) - -func TestNew(t *testing.T) { - tests := []struct { - err string - want error - }{ - {"", fmt.Errorf("")}, - {"foo", fmt.Errorf("foo")}, - {"foo", New("foo")}, - {"string with format specifiers: %v", errors.New("string with format specifiers: %v")}, - } - - for _, tt := range tests { - got := New(tt.err) - if got.Error() != tt.want.Error() { - t.Errorf("New.Error(): got: %q, want %q", got, tt.want) - } - } -} - -func TestWrapNil(t *testing.T) { - got := Wrap(nil, "no error") - if got != nil { - t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrap(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := Wrap(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -type nilError struct{} - -func (nilError) Error() string { return "nil error" } - -func TestCause(t *testing.T) { - x := New("error") - tests := []struct { - err error - want error - }{{ - // nil error is nil - err: nil, - want: nil, - }, { - // explicit nil error is nil - err: (error)(nil), - want: nil, - }, { - // typed nil is nil - err: (*nilError)(nil), - want: (*nilError)(nil), - }, { - // uncaused error is unaffected - err: io.EOF, - want: io.EOF, - }, { - // caused error returns cause - err: Wrap(io.EOF, "ignored"), - want: io.EOF, - }, { - err: x, // return from errors.New - want: x, - }, { - WithMessage(nil, "whoops"), - nil, - }, { - WithMessage(io.EOF, "whoops"), - io.EOF, - }, { - WithStack(nil), - nil, - }, { - WithStack(io.EOF), - io.EOF, - }} - - for i, tt := range tests { - got := Cause(tt.err) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) - } - } -} - -func TestWrapfNil(t *testing.T) { - got := Wrapf(nil, "no error") - if got != nil { - t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrapf(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"}, - {Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"}, - } - - for _, tt := range tests { - got := Wrapf(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -func TestErrorf(t *testing.T) { - tests := []struct { - err error - want string - }{ - {Errorf("read error without format specifiers"), "read error without format specifiers"}, - {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, - } - - for _, tt := range tests { - got := tt.err.Error() - if got != tt.want { - t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) - } - } -} - -func TestWithStackNil(t *testing.T) { - got := WithStack(nil) - if got != nil { - t.Errorf("WithStack(nil): got %#v, expected nil", got) - } -} - -func TestWithStack(t *testing.T) { - tests := []struct { - err error - want string - }{ - {io.EOF, "EOF"}, - {WithStack(io.EOF), "EOF"}, - } - - for _, tt := range tests { - got := WithStack(tt.err).Error() - if got != tt.want { - t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want) - } - } -} - -func TestWithMessageNil(t *testing.T) { - got := WithMessage(nil, "no error") - if got != nil { - t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWithMessage(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := WithMessage(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want) - } - } - -} - -// errors.New, etc values are not expected to be compared by value -// but the change in errors#27 made them incomparable. Assert that -// various kinds of errors have a functional equality operator, even -// if the result of that equality is always false. -func TestErrorEquality(t *testing.T) { - vals := []error{ - nil, - io.EOF, - errors.New("EOF"), - New("EOF"), - Errorf("EOF"), - Wrap(io.EOF, "EOF"), - Wrapf(io.EOF, "EOF%d", 2), - WithMessage(nil, "whoops"), - WithMessage(io.EOF, "whoops"), - WithStack(io.EOF), - WithStack(nil), - } - - for i := range vals { - for j := range vals { - _ = vals[i] == vals[j] // mustn't panic - } - } -} diff --git a/vendor/github.com/pkg/errors/example_test.go b/vendor/github.com/pkg/errors/example_test.go deleted file mode 100644 index c1fc13e38..000000000 --- a/vendor/github.com/pkg/errors/example_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package errors_test - -import ( - "fmt" - - "github.com/pkg/errors" -) - -func ExampleNew() { - err := errors.New("whoops") - fmt.Println(err) - - // Output: whoops -} - -func ExampleNew_printf() { - err := errors.New("whoops") - fmt.Printf("%+v", err) - - // Example output: - // whoops - // github.com/pkg/errors_test.ExampleNew_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:17 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func ExampleWithMessage() { - cause := errors.New("whoops") - err := errors.WithMessage(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func ExampleWithStack() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Println(err) - - // Output: whoops -} - -func ExampleWithStack_printf() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Printf("%+v", err) - - // Example Output: - // whoops - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 -} - -func ExampleWrap() { - cause := errors.New("whoops") - err := errors.Wrap(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func fn() error { - e1 := errors.New("error") - e2 := errors.Wrap(e1, "inner") - e3 := errors.Wrap(e2, "middle") - return errors.Wrap(e3, "outer") -} - -func ExampleCause() { - err := fn() - fmt.Println(err) - fmt.Println(errors.Cause(err)) - - // Output: outer: middle: inner: error - // error -} - -func ExampleWrap_extended() { - err := fn() - fmt.Printf("%+v\n", err) - - // Example output: - // error - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.ExampleCause_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:63 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:104 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer -} - -func ExampleWrapf() { - cause := errors.New("whoops") - err := errors.Wrapf(cause, "oh noes #%d", 2) - fmt.Println(err) - - // Output: oh noes #2: whoops -} - -func ExampleErrorf_extended() { - err := errors.Errorf("whoops: %s", "foo") - fmt.Printf("%+v", err) - - // Example output: - // whoops: foo - // github.com/pkg/errors_test.ExampleErrorf - // /home/dfc/src/github.com/pkg/errors/example_test.go:101 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:102 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func Example_stackTrace() { - type stackTracer interface { - StackTrace() errors.StackTrace - } - - err, ok := errors.Cause(fn()).(stackTracer) - if !ok { - panic("oops, err does not implement stackTracer") - } - - st := err.StackTrace() - fmt.Printf("%+v", st[0:2]) // top two frames - - // Example output: - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.Example_stackTrace - // /home/dfc/src/github.com/pkg/errors/example_test.go:127 -} - -func ExampleCause_printf() { - err := errors.Wrap(func() error { - return func() error { - return errors.Errorf("hello %s", fmt.Sprintf("world")) - }() - }(), "failed") - - fmt.Printf("%v", err) - - // Output: failed: hello world -} diff --git a/vendor/github.com/pkg/errors/format_test.go b/vendor/github.com/pkg/errors/format_test.go deleted file mode 100644 index 15fd7d89d..000000000 --- a/vendor/github.com/pkg/errors/format_test.go +++ /dev/null @@ -1,535 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "regexp" - "strings" - "testing" -) - -func TestFormatNew(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - New("error"), - "%s", - "error", - }, { - New("error"), - "%v", - "error", - }, { - New("error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:26", - }, { - New("error"), - "%q", - `"error"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatErrorf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Errorf("%s", "error"), - "%s", - "error", - }, { - Errorf("%s", "error"), - "%v", - "error", - }, { - Errorf("%s", "error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatErrorf\n" + - "\t.+/github.com/pkg/errors/format_test.go:56", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrap(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrap(New("error"), "error2"), - "%s", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%v", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:82", - }, { - Wrap(io.EOF, "error"), - "%s", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%v", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%+v", - "EOF\n" + - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:96", - }, { - Wrap(Wrap(io.EOF, "error1"), "error2"), - "%+v", - "EOF\n" + - "error1\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:103\n", - }, { - Wrap(New("error with space"), "context"), - "%q", - `"context: error with space"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrapf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrapf(io.EOF, "error%d", 2), - "%s", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%v", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%+v", - "EOF\n" + - "error2\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:134", - }, { - Wrapf(New("error"), "error%d", 2), - "%s", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%v", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:149", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWithStack(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithStack(io.EOF), - "%s", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%v", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:175"}, - }, { - WithStack(New("error")), - "%s", - []string{"error"}, - }, { - WithStack(New("error")), - "%v", - []string{"error"}, - }, { - WithStack(New("error")), - "%+v", - []string{"error", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189"}, - }, { - WithStack(WithStack(io.EOF)), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197"}, - }, { - WithStack(WithStack(Wrapf(io.EOF, "message"))), - "%+v", - []string{"EOF", - "message", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205"}, - }, { - WithStack(Errorf("error%d", 1)), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatWithMessage(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithMessage(New("error"), "error2"), - "%s", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%v", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%+v", - []string{ - "error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:244", - "error2"}, - }, { - WithMessage(io.EOF, "addition1"), - "%s", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%v", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%+v", - []string{"EOF", "addition1"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%v", - []string{"addition2: addition1: EOF"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%+v", - []string{"EOF", "addition1", "addition2"}, - }, { - Wrap(WithMessage(io.EOF, "error1"), "error2"), - "%+v", - []string{"EOF", "error1", "error2", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:272"}, - }, { - WithMessage(Errorf("error%d", 1), "error2"), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:278", - "error2"}, - }, { - WithMessage(WithStack(io.EOF), "error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:285", - "error"}, - }, { - WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "inside-error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "outside-error"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatGeneric(t *testing.T) { - starts := []struct { - err error - want []string - }{ - {New("new-error"), []string{ - "new-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:315"}, - }, {Errorf("errorf-error"), []string{ - "errorf-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:319"}, - }, {errors.New("errors-new-error"), []string{ - "errors-new-error"}, - }, - } - - wrappers := []wrapper{ - { - func(err error) error { return WithMessage(err, "with-message") }, - []string{"with-message"}, - }, { - func(err error) error { return WithStack(err) }, - []string{ - "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + - ".+/github.com/pkg/errors/format_test.go:333", - }, - }, { - func(err error) error { return Wrap(err, "wrap-error") }, - []string{ - "wrap-error", - "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + - ".+/github.com/pkg/errors/format_test.go:339", - }, - }, { - func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, - []string{ - "wrapf-error1", - "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + - ".+/github.com/pkg/errors/format_test.go:346", - }, - }, - } - - for s := range starts { - err := starts[s].err - want := starts[s].want - testFormatCompleteCompare(t, s, err, "%+v", want, false) - testGenericRecursive(t, err, want, wrappers, 3) - } -} - -func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { - got := fmt.Sprintf(format, arg) - gotLines := strings.SplitN(got, "\n", -1) - wantLines := strings.SplitN(want, "\n", -1) - - if len(wantLines) > len(gotLines) { - t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) - return - } - - for i, w := range wantLines { - match, err := regexp.MatchString(w, gotLines[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want) - } - } -} - -var stackLineR = regexp.MustCompile(`\.`) - -// parseBlocks parses input into a slice, where: -// - incase entry contains a newline, its a stacktrace -// - incase entry contains no newline, its a solo line. -// -// Detecting stack boundaries only works incase the WithStack-calls are -// to be found on the same line, thats why it is optionally here. -// -// Example use: -// -// for _, e := range blocks { -// if strings.ContainsAny(e, "\n") { -// // Match as stack -// } else { -// // Match as line -// } -// } -// -func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { - var blocks []string - - stack := "" - wasStack := false - lines := map[string]bool{} // already found lines - - for _, l := range strings.Split(input, "\n") { - isStackLine := stackLineR.MatchString(l) - - switch { - case !isStackLine && wasStack: - blocks = append(blocks, stack, l) - stack = "" - lines = map[string]bool{} - case isStackLine: - if wasStack { - // Detecting two stacks after another, possible cause lines match in - // our tests due to WithStack(WithStack(io.EOF)) on same line. - if detectStackboundaries { - if lines[l] { - if len(stack) == 0 { - return nil, errors.New("len of block must not be zero here") - } - - blocks = append(blocks, stack) - stack = l - lines = map[string]bool{l: true} - continue - } - } - - stack = stack + "\n" + l - } else { - stack = l - } - lines[l] = true - case !isStackLine && !wasStack: - blocks = append(blocks, l) - default: - return nil, errors.New("must not happen") - } - - wasStack = isStackLine - } - - // Use up stack - if stack != "" { - blocks = append(blocks, stack) - } - return blocks, nil -} - -func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { - gotStr := fmt.Sprintf(format, arg) - - got, err := parseBlocks(gotStr, detectStackBoundaries) - if err != nil { - t.Fatal(err) - } - - if len(got) != len(want) { - t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q", - n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr) - } - - for i := range got { - if strings.ContainsAny(want[i], "\n") { - // Match as stack - match, err := regexp.MatchString(want[i], got[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", - n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) - } - } else { - // Match as message - if got[i] != want[i] { - t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) - } - } - } -} - -type wrapper struct { - wrap func(err error) error - want []string -} - -func prettyBlocks(blocks []string, prefix ...string) string { - var out []string - - for _, b := range blocks { - out = append(out, fmt.Sprintf("%v", b)) - } - - return " " + strings.Join(out, "\n ") -} - -func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) { - if len(beforeWant) == 0 { - panic("beforeWant must not be empty") - } - for _, w := range list { - if len(w.want) == 0 { - panic("want must not be empty") - } - - err := w.wrap(beforeErr) - - // Copy required cause append(beforeWant, ..) modified beforeWant subtly. - beforeCopy := make([]string, len(beforeWant)) - copy(beforeCopy, beforeWant) - - beforeWant := beforeCopy - last := len(beforeWant) - 1 - var want []string - - // Merge two stacks behind each other. - if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { - want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) - } else { - want = append(beforeWant, w.want...) - } - - testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) - if maxDepth > 0 { - testGenericRecursive(t, err, want, list, maxDepth-1) - } - } -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 6b1f2891a..000000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,178 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - fmt.Fprintf(s, "%v", []Frame(st)) - } - case 's': - fmt.Fprintf(s, "%s", []Frame(st)) - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} - -func trimGOPATH(name, file string) string { - // Here we want to get the source file path relative to the compile time - // GOPATH. As of Go 1.6.x there is no direct way to know the compiled - // GOPATH at runtime, but we can infer the number of path segments in the - // GOPATH. We note that fn.Name() returns the function name qualified by - // the import path, which does not include the GOPATH. Thus we can trim - // segments from the beginning of the file path until the number of path - // separators remaining is one more than the number of path separators in - // the function name. For example, given: - // - // GOPATH /home/user - // file /home/user/src/pkg/sub/file.go - // fn.Name() pkg/sub.Type.Method - // - // We want to produce: - // - // pkg/sub/file.go - // - // From this we can easily see that fn.Name() has one less path separator - // than our desired output. We count separators from the end of the file - // path until it finds two more than in the function name and then move - // one character forward to preserve the initial path segment without a - // leading separator. - const sep = "/" - goal := strings.Count(name, sep) + 2 - i := len(file) - for n := 0; n < goal; n++ { - i = strings.LastIndex(file[:i], sep) - if i == -1 { - // not enough separators found, set i so that the slice expression - // below leaves file unmodified - i = -len(sep) - break - } - } - // get back to 0 or trim the leading separator - file = file[i+len(sep):] - return file -} diff --git a/vendor/github.com/pkg/errors/stack_test.go b/vendor/github.com/pkg/errors/stack_test.go deleted file mode 100644 index 510c27a9f..000000000 --- a/vendor/github.com/pkg/errors/stack_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package errors - -import ( - "fmt" - "runtime" - "testing" -) - -var initpc, _, _, _ = runtime.Caller(0) - -func TestFrameLine(t *testing.T) { - var tests = []struct { - Frame - want int - }{{ - Frame(initpc), - 9, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) - }(), - 20, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(1) - return Frame(pc) - }(), - 28, - }, { - Frame(0), // invalid PC - 0, - }} - - for _, tt := range tests { - got := tt.Frame.line() - want := tt.want - if want != got { - t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) - } - } -} - -type X struct{} - -func (x X) val() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func (x *X) ptr() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func TestFrameFormat(t *testing.T) { - var tests = []struct { - Frame - format string - want string - }{{ - Frame(initpc), - "%s", - "stack_test.go", - }, { - Frame(initpc), - "%+s", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go", - }, { - Frame(0), - "%s", - "unknown", - }, { - Frame(0), - "%+s", - "unknown", - }, { - Frame(initpc), - "%d", - "9", - }, { - Frame(0), - "%d", - "0", - }, { - Frame(initpc), - "%n", - "init", - }, { - func() Frame { - var x X - return x.ptr() - }(), - "%n", - `\(\*X\).ptr`, - }, { - func() Frame { - var x X - return x.val() - }(), - "%n", - "X.val", - }, { - Frame(0), - "%n", - "", - }, { - Frame(initpc), - "%v", - "stack_test.go:9", - }, { - Frame(initpc), - "%+v", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go:9", - }, { - Frame(0), - "%v", - "unknown:0", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.Frame, tt.format, tt.want) - } -} - -func TestFuncname(t *testing.T) { - tests := []struct { - name, want string - }{ - {"", ""}, - {"runtime.main", "main"}, - {"github.com/pkg/errors.funcname", "funcname"}, - {"funcname", "funcname"}, - {"io.copyBuffer", "copyBuffer"}, - {"main.(*R).Write", "(*R).Write"}, - } - - for _, tt := range tests { - got := funcname(tt.name) - want := tt.want - if got != want { - t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got) - } - } -} - -func TestTrimGOPATH(t *testing.T) { - var tests = []struct { - Frame - want string - }{{ - Frame(initpc), - "github.com/pkg/errors/stack_test.go", - }} - - for i, tt := range tests { - pc := tt.Frame.pc() - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - got := trimGOPATH(fn.Name(), file) - testFormatRegexp(t, i, got, "%s", tt.want) - } -} - -func TestStackTrace(t *testing.T) { - tests := []struct { - err error - want []string - }{{ - New("ooh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:172", - }, - }, { - Wrap(New("ooh"), "ahh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New - }, - }, { - Cause(Wrap(New("ooh"), "ahh")), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New - }, - }, { - func() error { return New("ooh") }(), []string{ - `github.com/pkg/errors.(func·009|TestStackTrace.func1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller - }, - }, { - Cause(func() error { - return func() error { - return Errorf("hello %s", fmt.Sprintf("world")) - }() - }()), []string{ - `github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf - `github.com/pkg/errors.(func·011|TestStackTrace.func2)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller - }, - }} - for i, tt := range tests { - x, ok := tt.err.(interface { - StackTrace() StackTrace - }) - if !ok { - t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err) - continue - } - st := x.StackTrace() - for j, want := range tt.want { - testFormatRegexp(t, i, st[j], "%+v", want) - } - } -} - -func stackTrace() StackTrace { - const depth = 8 - var pcs [depth]uintptr - n := runtime.Callers(1, pcs[:]) - var st stack = pcs[0:n] - return st.StackTrace() -} - -func TestStackTraceFormat(t *testing.T) { - tests := []struct { - StackTrace - format string - want string - }{{ - nil, - "%s", - `\[\]`, - }, { - nil, - "%v", - `\[\]`, - }, { - nil, - "%+v", - "", - }, { - nil, - "%#v", - `\[\]errors.Frame\(nil\)`, - }, { - make(StackTrace, 0), - "%s", - `\[\]`, - }, { - make(StackTrace, 0), - "%v", - `\[\]`, - }, { - make(StackTrace, 0), - "%+v", - "", - }, { - make(StackTrace, 0), - "%#v", - `\[\]errors.Frame{}`, - }, { - stackTrace()[:2], - "%s", - `\[stack_test.go stack_test.go\]`, - }, { - stackTrace()[:2], - "%v", - `\[stack_test.go:225 stack_test.go:272\]`, - }, { - stackTrace()[:2], - "%+v", - "\n" + - "github.com/pkg/errors.stackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:225\n" + - "github.com/pkg/errors.TestStackTraceFormat\n" + - "\t.+/github.com/pkg/errors/stack_test.go:276", - }, { - stackTrace()[:2], - "%#v", - `\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want) - } -} diff --git a/vendor/github.com/pkg/profile/.travis.yml b/vendor/github.com/pkg/profile/.travis.yml index fd72871e0..1c9e6bb6b 100644 --- a/vendor/github.com/pkg/profile/.travis.yml +++ b/vendor/github.com/pkg/profile/.travis.yml @@ -1,8 +1,8 @@ language: go go_import_path: github.com/pkg/profile go: + - 1.10.x - 1.12.x - - 1.13.x - tip script: diff --git a/vendor/github.com/pkg/profile/go.mod b/vendor/github.com/pkg/profile/go.mod deleted file mode 100644 index 2d82f3d84..000000000 --- a/vendor/github.com/pkg/profile/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/pkg/profile - -go 1.12 diff --git a/vendor/github.com/pkg/profile/mutex.go b/vendor/github.com/pkg/profile/mutex.go new file mode 100644 index 000000000..e69c5b44d --- /dev/null +++ b/vendor/github.com/pkg/profile/mutex.go @@ -0,0 +1,13 @@ +// +build go1.8 + +package profile + +import "runtime" + +func enableMutexProfile() { + runtime.SetMutexProfileFraction(1) +} + +func disableMutexProfile() { + runtime.SetMutexProfileFraction(0) +} diff --git a/vendor/github.com/pkg/profile/mutex17.go b/vendor/github.com/pkg/profile/mutex17.go new file mode 100644 index 000000000..b004c21d5 --- /dev/null +++ b/vendor/github.com/pkg/profile/mutex17.go @@ -0,0 +1,9 @@ +// +build !go1.8 + +package profile + +// mock mutex support for Go 1.7 and earlier. + +func enableMutexProfile() {} + +func disableMutexProfile() {} diff --git a/vendor/github.com/pkg/profile/profile.go b/vendor/github.com/pkg/profile/profile.go index b9fdfcfd8..20e285427 100644 --- a/vendor/github.com/pkg/profile/profile.go +++ b/vendor/github.com/pkg/profile/profile.go @@ -10,7 +10,6 @@ import ( "path/filepath" "runtime" "runtime/pprof" - "runtime/trace" "sync/atomic" ) @@ -21,7 +20,6 @@ const ( blockMode traceMode threadCreateMode - goroutineMode ) // Profile represents an active profiling session. @@ -100,10 +98,6 @@ func TraceProfile(p *Profile) { p.mode = traceMode } // It disables any previous profiling settings. func ThreadcreationProfile(p *Profile) { p.mode = threadCreateMode } -// GoroutineProfile enables goroutine profiling. -// It disables any previous profiling settings. -func GoroutineProfile(p *Profile) { p.mode = goroutineMode } - // ProfilePath controls the base path where various profiling // files are written. If blank, the base path will be generated // by ioutil.TempDir. @@ -195,14 +189,14 @@ func Start(options ...func(*Profile)) interface { if err != nil { log.Fatalf("profile: could not create mutex profile %q: %v", fn, err) } - runtime.SetMutexProfileFraction(1) + enableMutexProfile() logf("profile: mutex profiling enabled, %s", fn) prof.closer = func() { if mp := pprof.Lookup("mutex"); mp != nil { mp.WriteTo(f, 0) } f.Close() - runtime.SetMutexProfileFraction(0) + disableMutexProfile() logf("profile: mutex profiling disabled, %s", fn) } @@ -242,29 +236,14 @@ func Start(options ...func(*Profile)) interface { if err != nil { log.Fatalf("profile: could not create trace output file %q: %v", fn, err) } - if err := trace.Start(f); err != nil { + if err := startTrace(f); err != nil { log.Fatalf("profile: could not start trace: %v", err) } logf("profile: trace enabled, %s", fn) prof.closer = func() { - trace.Stop() + stopTrace() logf("profile: trace disabled, %s", fn) } - - case goroutineMode: - fn := filepath.Join(path, "goroutine.pprof") - f, err := os.Create(fn) - if err != nil { - log.Fatalf("profile: could not create goroutine profile %q: %v", fn, err) - } - logf("profile: goroutine profiling enabled, %s", fn) - prof.closer = func() { - if mp := pprof.Lookup("goroutine"); mp != nil { - mp.WriteTo(f, 0) - } - f.Close() - logf("profile: goroutine profiling disabled, %s", fn) - } } if !prof.noShutdownHook { diff --git a/vendor/github.com/pkg/profile/trace.go b/vendor/github.com/pkg/profile/trace.go new file mode 100644 index 000000000..b349ed8b2 --- /dev/null +++ b/vendor/github.com/pkg/profile/trace.go @@ -0,0 +1,8 @@ +// +build go1.7 + +package profile + +import "runtime/trace" + +var startTrace = trace.Start +var stopTrace = trace.Stop diff --git a/vendor/github.com/pkg/profile/trace16.go b/vendor/github.com/pkg/profile/trace16.go new file mode 100644 index 000000000..6aa6566ef --- /dev/null +++ b/vendor/github.com/pkg/profile/trace16.go @@ -0,0 +1,10 @@ +// +build !go1.7 + +package profile + +import "io" + +// mock trace support for Go 1.6 and earlier. + +func startTrace(w io.Writer) error { return nil } +func stopTrace() {} diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index dc6775329..55ddc50fa 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -84,7 +84,8 @@ type Command struct { // Version defines the version for this command. If this value is non-empty and the command does not // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - // will print content of the "Version" variable. + // will print content of the "Version" variable. A shorthand "v" flag will also be added if the + // command does not define one. Version string // The *Run functions are executed in the following order: @@ -1033,7 +1034,11 @@ func (c *Command) InitDefaultVersionFlag() { } else { usage += c.Name() } - c.Flags().Bool("version", false, usage) + if c.Flags().ShorthandLookup("v") == nil { + c.Flags().BoolP("version", "v", false, usage) + } else { + c.Flags().Bool("version", false, usage) + } } } diff --git a/vendor/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go index 05a3c0f27..121559374 100644 --- a/vendor/github.com/spf13/cobra/command_test.go +++ b/vendor/github.com/spf13/cobra/command_test.go @@ -921,6 +921,52 @@ func TestVersionFlagExecuted(t *testing.T) { checkStringContains(t, output, "root version 1.0.0") } +func TestVersionFlagExecutedWithNoName(t *testing.T) { + rootCmd := &Command{Version: "1.0.0", Run: emptyRun} + + output, err := executeCommand(rootCmd, "--version", "arg1") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "version 1.0.0") +} + +func TestShortAndLongVersionFlagInHelp(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "-v, --version") +} + +func TestLongVersionFlagOnlyInHelpWhenShortPredefined(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + rootCmd.Flags().StringP("foo", "v", "", "not a version flag") + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringOmits(t, output, "-v, --version") + checkStringContains(t, output, "--version") +} + +func TestShorthandVersionFlagExecuted(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + + output, err := executeCommand(rootCmd, "-v", "arg1") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "root version 1.0.0") +} + func TestVersionTemplate(t *testing.T) { rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} rootCmd.SetVersionTemplate(`customized version: {{.Version}}`) @@ -933,6 +979,18 @@ func TestVersionTemplate(t *testing.T) { checkStringContains(t, output, "customized version: 1.0.0") } +func TestShorthandVersionTemplate(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + rootCmd.SetVersionTemplate(`customized version: {{.Version}}`) + + output, err := executeCommand(rootCmd, "-v", "arg1") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "customized version: 1.0.0") +} + func TestVersionFlagExecutedOnSubcommand(t *testing.T) { rootCmd := &Command{Use: "root", Version: "1.0.0"} rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) @@ -945,6 +1003,18 @@ func TestVersionFlagExecutedOnSubcommand(t *testing.T) { checkStringContains(t, output, "root version 1.0.0") } +func TestShorthandVersionFlagExecutedOnSubcommand(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0"} + rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "-v", "sub") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "root version 1.0.0") +} + func TestVersionFlagOnlyAddedToRoot(t *testing.T) { rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) @@ -957,6 +1027,18 @@ func TestVersionFlagOnlyAddedToRoot(t *testing.T) { checkStringContains(t, err.Error(), "unknown flag: --version") } +func TestShortVersionFlagOnlyAddedToRoot(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) + + _, err := executeCommand(rootCmd, "sub", "-v") + if err == nil { + t.Errorf("Expected error") + } + + checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v") +} + func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) { rootCmd := &Command{Use: "root", Run: emptyRun} @@ -967,6 +1049,39 @@ func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) { checkStringContains(t, err.Error(), "unknown flag: --version") } +func TestShorthandVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + + _, err := executeCommand(rootCmd, "-v") + if err == nil { + t.Errorf("Expected error") + } + checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v") +} + +func TestShorthandVersionFlagOnlyAddedIfShorthandNotDefined(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"} + rootCmd.Flags().StringP("notversion", "v", "", "not a version flag") + + _, err := executeCommand(rootCmd, "-v") + if err == nil { + t.Errorf("Expected error") + } + check(t, rootCmd.Flags().ShorthandLookup("v").Name, "notversion") + checkStringContains(t, err.Error(), "flag needs an argument: 'v' in -v") +} + +func TestShorthandVersionFlagOnlyAddedIfVersionNotDefined(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"} + rootCmd.Flags().Bool("version", false, "a different kind of version flag") + + _, err := executeCommand(rootCmd, "-v") + if err == nil { + t.Errorf("Expected error") + } + checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v") +} + func TestUsageIsNotPrintedTwice(t *testing.T) { var cmd = &Command{Use: "root"} var sub = &Command{Use: "sub"} diff --git a/vendor/google.golang.org/appengine/README.md b/vendor/google.golang.org/appengine/README.md index 9fdbacd3c..d86768a2c 100644 --- a/vendor/google.golang.org/appengine/README.md +++ b/vendor/google.golang.org/appengine/README.md @@ -71,30 +71,3 @@ A few APIs were cleaned up, and there are some differences: [blobstore package](https://google.golang.org/appengine/blobstore). * `appengine/socket` is not required on App Engine flexible environment / Managed VMs. Use the standard `net` package instead. - -## Key Encode/Decode compatibiltiy to help with datastore library migrations - -Key compatibility updates have been added to help customers transition from google.golang.org/appengine/datastore to cloud.google.com/go/datastore. -The `EnableKeyConversion` enables automatic conversion from a key encoded with cloud.google.com/go/datastore to google.golang.org/appengine/datastore key type. - -### Enabling key conversion - -Enable key conversion by calling `EnableKeyConversion(ctx)` in the `/_ah/start` handler for basic and manual scaling or any handler in automatic scaling. - -#### 1. Basic or manual scaling - -This start handler will enable key conversion for all handlers in the service. - -``` -http.HandleFunc("/_ah/start", func(w http.ResponseWriter, r *http.Request) { - datastore.EnableKeyConversion(appengine.NewContext(r)) -}) -``` - -#### 2. Automatic scaling - -`/_ah/start` is not supported for automatic scaling and `/_ah/warmup` is not guaranteed to run, so you must call `datastore.EnableKeyConversion(appengine.NewContext(r))` -before you use code that needs key conversion. - -You may want to add this to each of your handlers, or introduce middleware where it's called. -`EnableKeyConversion` is safe for concurrent use. Any call to it after the first is ignored. \ No newline at end of file diff --git a/vendor/google.golang.org/appengine/aetest/instance_vm.go b/vendor/google.golang.org/appengine/aetest/instance_vm.go index c8f8ff4e7..820e1ef20 100644 --- a/vendor/google.golang.org/appengine/aetest/instance_vm.go +++ b/vendor/google.golang.org/appengine/aetest/instance_vm.go @@ -215,7 +215,9 @@ func (i *instance) startChild() (err error) { if err != nil { return err } - + if !(i.opts != nil && i.opts.SuppressDevAppServerLog) { + stderr = io.TeeReader(stderr, os.Stderr) + } if err = i.child.Start(); err != nil { return err } @@ -225,10 +227,6 @@ func (i *instance) startChild() (err error) { go func() { s := bufio.NewScanner(stderr) for s.Scan() { - // Pass stderr along as we go so the user can see it. - if !(i.opts != nil && i.opts.SuppressDevAppServerLog) { - fmt.Fprintln(os.Stderr, s.Text()) - } if match := apiServerAddrRE.FindStringSubmatch(s.Text()); match != nil { u, err := url.Parse(match[1]) if err != nil { @@ -241,10 +239,6 @@ func (i *instance) startChild() (err error) { i.adminURL = match[1] } if i.adminURL != "" && i.apiURL != nil { - // Pass along stderr to the user after we're done with it. - if !(i.opts != nil && i.opts.SuppressDevAppServerLog) { - go io.Copy(os.Stderr, stderr) - } break } } @@ -278,7 +272,8 @@ func (i *instance) appYAML() string { const appYAMLTemplate = ` application: %s version: 1 -runtime: go111 +runtime: go +api_version: go1 handlers: - url: /.* diff --git a/vendor/google.golang.org/appengine/capability/capability.go b/vendor/google.golang.org/appengine/capability/capability.go index 35604d4a4..3a60bd55f 100644 --- a/vendor/google.golang.org/appengine/capability/capability.go +++ b/vendor/google.golang.org/appengine/capability/capability.go @@ -29,11 +29,6 @@ import ( // If the underlying RPC fails (if the package is unknown, for example), // false is returned and information is written to the application log. func Enabled(ctx context.Context, api, capability string) bool { - // For non datastore*/write requests always return ENABLED - if !(api == "datastore_v3" && capability == "write") { - return true - } - req := &pb.IsEnabledRequest{ Package: &api, Capability: []string{capability}, @@ -43,5 +38,15 @@ func Enabled(ctx context.Context, api, capability string) bool { log.Warningf(ctx, "capability.Enabled: RPC failed: %v", err) return false } - return *res.SummaryStatus == pb.IsEnabledResponse_ENABLED + switch *res.SummaryStatus { + case pb.IsEnabledResponse_ENABLED, + pb.IsEnabledResponse_SCHEDULED_FUTURE, + pb.IsEnabledResponse_SCHEDULED_NOW: + return true + case pb.IsEnabledResponse_UNKNOWN: + log.Errorf(ctx, "capability.Enabled: unknown API capability %s/%s", api, capability) + return false + default: + return false + } } diff --git a/vendor/google.golang.org/appengine/datastore/internal/cloudkey/cloudkey.go b/vendor/google.golang.org/appengine/datastore/internal/cloudkey/cloudkey.go deleted file mode 100644 index 643d4049c..000000000 --- a/vendor/google.golang.org/appengine/datastore/internal/cloudkey/cloudkey.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2019 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// Package cloudpb is a subset of types and functions, copied from cloud.google.com/go/datastore. -// -// They are copied here to provide compatibility to decode keys generated by the cloud.google.com/go/datastore package. -package cloudkey - -import ( - "encoding/base64" - "errors" - "strings" - - "github.com/golang/protobuf/proto" - cloudpb "google.golang.org/appengine/datastore/internal/cloudpb" -) - -///////////////////////////////////////////////////////////////////// -// Code below is copied from https://github.com/googleapis/google-cloud-go/blob/master/datastore/datastore.go -///////////////////////////////////////////////////////////////////// - -var ( - // ErrInvalidKey is returned when an invalid key is presented. - ErrInvalidKey = errors.New("datastore: invalid key") -) - -///////////////////////////////////////////////////////////////////// -// Code below is copied from https://github.com/googleapis/google-cloud-go/blob/master/datastore/key.go -///////////////////////////////////////////////////////////////////// - -// Key represents the datastore key for a stored entity. -type Key struct { - // Kind cannot be empty. - Kind string - // Either ID or Name must be zero for the Key to be valid. - // If both are zero, the Key is incomplete. - ID int64 - Name string - // Parent must either be a complete Key or nil. - Parent *Key - - // Namespace provides the ability to partition your data for multiple - // tenants. In most cases, it is not necessary to specify a namespace. - // See docs on datastore multitenancy for details: - // https://cloud.google.com/datastore/docs/concepts/multitenancy - Namespace string -} - -// DecodeKey decodes a key from the opaque representation returned by Encode. -func DecodeKey(encoded string) (*Key, error) { - // Re-add padding. - if m := len(encoded) % 4; m != 0 { - encoded += strings.Repeat("=", 4-m) - } - - b, err := base64.URLEncoding.DecodeString(encoded) - if err != nil { - return nil, err - } - - pKey := new(cloudpb.Key) - if err := proto.Unmarshal(b, pKey); err != nil { - return nil, err - } - return protoToKey(pKey) -} - -// valid returns whether the key is valid. -func (k *Key) valid() bool { - if k == nil { - return false - } - for ; k != nil; k = k.Parent { - if k.Kind == "" { - return false - } - if k.Name != "" && k.ID != 0 { - return false - } - if k.Parent != nil { - if k.Parent.Incomplete() { - return false - } - if k.Parent.Namespace != k.Namespace { - return false - } - } - } - return true -} - -// Incomplete reports whether the key does not refer to a stored entity. -func (k *Key) Incomplete() bool { - return k.Name == "" && k.ID == 0 -} - -// protoToKey decodes a protocol buffer representation of a key into an -// equivalent *Key object. If the key is invalid, protoToKey will return the -// invalid key along with ErrInvalidKey. -func protoToKey(p *cloudpb.Key) (*Key, error) { - var key *Key - var namespace string - if partition := p.PartitionId; partition != nil { - namespace = partition.NamespaceId - } - for _, el := range p.Path { - key = &Key{ - Namespace: namespace, - Kind: el.Kind, - ID: el.GetId(), - Name: el.GetName(), - Parent: key, - } - } - if !key.valid() { // Also detects key == nil. - return key, ErrInvalidKey - } - return key, nil -} diff --git a/vendor/google.golang.org/appengine/datastore/internal/cloudpb/entity.pb.go b/vendor/google.golang.org/appengine/datastore/internal/cloudpb/entity.pb.go deleted file mode 100644 index af8195f3f..000000000 --- a/vendor/google.golang.org/appengine/datastore/internal/cloudpb/entity.pb.go +++ /dev/null @@ -1,344 +0,0 @@ -// Copyright 2019 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// Package cloudpb is a subset of protobufs, copied from google.golang.org/genproto/googleapis/datastore/v1. -// -// They are copied here to provide compatibility to decode keys generated by the cloud.google.com/go/datastore package. -package cloudpb - -import ( - "fmt" - - "github.com/golang/protobuf/proto" -) - -// A partition ID identifies a grouping of entities. The grouping is always -// by project and namespace, however the namespace ID may be empty. -// -// A partition ID contains several dimensions: -// project ID and namespace ID. -// -// Partition dimensions: -// -// - May be `""`. -// - Must be valid UTF-8 bytes. -// - Must have values that match regex `[A-Za-z\d\.\-_]{1,100}` -// If the value of any dimension matches regex `__.*__`, the partition is -// reserved/read-only. -// A reserved/read-only partition ID is forbidden in certain documented -// contexts. -// -// Foreign partition IDs (in which the project ID does -// not match the context project ID ) are discouraged. -// Reads and writes of foreign partition IDs may fail if the project is not in -// an active state. -type PartitionId struct { - // The ID of the project to which the entities belong. - ProjectId string `protobuf:"bytes,2,opt,name=project_id,json=projectId,proto3" json:"project_id,omitempty"` - // If not empty, the ID of the namespace to which the entities belong. - NamespaceId string `protobuf:"bytes,4,opt,name=namespace_id,json=namespaceId,proto3" json:"namespace_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PartitionId) Reset() { *m = PartitionId{} } -func (m *PartitionId) String() string { return proto.CompactTextString(m) } -func (*PartitionId) ProtoMessage() {} -func (*PartitionId) Descriptor() ([]byte, []int) { - return fileDescriptor_entity_096a297364b049a5, []int{0} -} -func (m *PartitionId) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PartitionId.Unmarshal(m, b) -} -func (m *PartitionId) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PartitionId.Marshal(b, m, deterministic) -} -func (dst *PartitionId) XXX_Merge(src proto.Message) { - xxx_messageInfo_PartitionId.Merge(dst, src) -} -func (m *PartitionId) XXX_Size() int { - return xxx_messageInfo_PartitionId.Size(m) -} -func (m *PartitionId) XXX_DiscardUnknown() { - xxx_messageInfo_PartitionId.DiscardUnknown(m) -} - -var xxx_messageInfo_PartitionId proto.InternalMessageInfo - -func (m *PartitionId) GetProjectId() string { - if m != nil { - return m.ProjectId - } - return "" -} - -func (m *PartitionId) GetNamespaceId() string { - if m != nil { - return m.NamespaceId - } - return "" -} - -// A unique identifier for an entity. -// If a key's partition ID or any of its path kinds or names are -// reserved/read-only, the key is reserved/read-only. -// A reserved/read-only key is forbidden in certain documented contexts. -type Key struct { - // Entities are partitioned into subsets, currently identified by a project - // ID and namespace ID. - // Queries are scoped to a single partition. - PartitionId *PartitionId `protobuf:"bytes,1,opt,name=partition_id,json=partitionId,proto3" json:"partition_id,omitempty"` - // The entity path. - // An entity path consists of one or more elements composed of a kind and a - // string or numerical identifier, which identify entities. The first - // element identifies a _root entity_, the second element identifies - // a _child_ of the root entity, the third element identifies a child of the - // second entity, and so forth. The entities identified by all prefixes of - // the path are called the element's _ancestors_. - // - // An entity path is always fully complete: *all* of the entity's ancestors - // are required to be in the path along with the entity identifier itself. - // The only exception is that in some documented cases, the identifier in the - // last path element (for the entity) itself may be omitted. For example, - // the last path element of the key of `Mutation.insert` may have no - // identifier. - // - // A path can never be empty, and a path can have at most 100 elements. - Path []*Key_PathElement `protobuf:"bytes,2,rep,name=path,proto3" json:"path,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Key) Reset() { *m = Key{} } -func (m *Key) String() string { return proto.CompactTextString(m) } -func (*Key) ProtoMessage() {} -func (*Key) Descriptor() ([]byte, []int) { - return fileDescriptor_entity_096a297364b049a5, []int{1} -} -func (m *Key) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Key.Unmarshal(m, b) -} -func (m *Key) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Key.Marshal(b, m, deterministic) -} -func (dst *Key) XXX_Merge(src proto.Message) { - xxx_messageInfo_Key.Merge(dst, src) -} -func (m *Key) XXX_Size() int { - return xxx_messageInfo_Key.Size(m) -} -func (m *Key) XXX_DiscardUnknown() { - xxx_messageInfo_Key.DiscardUnknown(m) -} - -// A (kind, ID/name) pair used to construct a key path. -// -// If either name or ID is set, the element is complete. -// If neither is set, the element is incomplete. -type Key_PathElement struct { - // The kind of the entity. - // A kind matching regex `__.*__` is reserved/read-only. - // A kind must not contain more than 1500 bytes when UTF-8 encoded. - // Cannot be `""`. - Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"` - // The type of ID. - // - // Types that are valid to be assigned to IdType: - // *Key_PathElement_Id - // *Key_PathElement_Name - IdType isKey_PathElement_IdType `protobuf_oneof:"id_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Key_PathElement) Reset() { *m = Key_PathElement{} } -func (m *Key_PathElement) String() string { return proto.CompactTextString(m) } -func (*Key_PathElement) ProtoMessage() {} -func (*Key_PathElement) Descriptor() ([]byte, []int) { - return fileDescriptor_entity_096a297364b049a5, []int{1, 0} -} -func (m *Key_PathElement) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Key_PathElement.Unmarshal(m, b) -} -func (m *Key_PathElement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Key_PathElement.Marshal(b, m, deterministic) -} -func (dst *Key_PathElement) XXX_Merge(src proto.Message) { - xxx_messageInfo_Key_PathElement.Merge(dst, src) -} -func (m *Key_PathElement) XXX_Size() int { - return xxx_messageInfo_Key_PathElement.Size(m) -} -func (m *Key_PathElement) XXX_DiscardUnknown() { - xxx_messageInfo_Key_PathElement.DiscardUnknown(m) -} - -var xxx_messageInfo_Key_PathElement proto.InternalMessageInfo - -func (m *Key_PathElement) GetKind() string { - if m != nil { - return m.Kind - } - return "" -} - -type isKey_PathElement_IdType interface { - isKey_PathElement_IdType() -} - -type Key_PathElement_Id struct { - Id int64 `protobuf:"varint,2,opt,name=id,proto3,oneof"` -} - -type Key_PathElement_Name struct { - Name string `protobuf:"bytes,3,opt,name=name,proto3,oneof"` -} - -func (*Key_PathElement_Id) isKey_PathElement_IdType() {} - -func (*Key_PathElement_Name) isKey_PathElement_IdType() {} - -func (m *Key_PathElement) GetIdType() isKey_PathElement_IdType { - if m != nil { - return m.IdType - } - return nil -} - -func (m *Key_PathElement) GetId() int64 { - if x, ok := m.GetIdType().(*Key_PathElement_Id); ok { - return x.Id - } - return 0 -} - -func (m *Key_PathElement) GetName() string { - if x, ok := m.GetIdType().(*Key_PathElement_Name); ok { - return x.Name - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Key_PathElement) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Key_PathElement_OneofMarshaler, _Key_PathElement_OneofUnmarshaler, _Key_PathElement_OneofSizer, []interface{}{ - (*Key_PathElement_Id)(nil), - (*Key_PathElement_Name)(nil), - } -} - -func _Key_PathElement_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Key_PathElement) - // id_type - switch x := m.IdType.(type) { - case *Key_PathElement_Id: - b.EncodeVarint(2<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Id)) - case *Key_PathElement_Name: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Name) - case nil: - default: - return fmt.Errorf("Key_PathElement.IdType has unexpected type %T", x) - } - return nil -} - -func _Key_PathElement_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Key_PathElement) - switch tag { - case 2: // id_type.id - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.IdType = &Key_PathElement_Id{int64(x)} - return true, err - case 3: // id_type.name - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.IdType = &Key_PathElement_Name{x} - return true, err - default: - return false, nil - } -} - -func _Key_PathElement_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Key_PathElement) - // id_type - switch x := m.IdType.(type) { - case *Key_PathElement_Id: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.Id)) - case *Key_PathElement_Name: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Name))) - n += len(x.Name) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -var fileDescriptor_entity_096a297364b049a5 = []byte{ - // 780 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x94, 0xff, 0x6e, 0xdc, 0x44, - 0x10, 0xc7, 0xed, 0xbb, 0x5c, 0x1a, 0x8f, 0xdd, 0xa4, 0x6c, 0x2a, 0x61, 0x02, 0x28, 0x26, 0x80, - 0x74, 0x02, 0xc9, 0x6e, 0xc2, 0x1f, 0x54, 0x14, 0xa4, 0x72, 0x25, 0xe0, 0x28, 0x15, 0x9c, 0x56, - 0x55, 0x24, 0x50, 0xa4, 0xd3, 0xde, 0x79, 0xeb, 0x2e, 0x67, 0xef, 0x5a, 0xf6, 0x3a, 0xaa, 0xdf, - 0x05, 0xf1, 0x00, 0x3c, 0x0a, 0x8f, 0x80, 0x78, 0x18, 0xb4, 0x3f, 0xec, 0x0b, 0xed, 0x35, 0xff, - 0x79, 0x67, 0x3e, 0xdf, 0xd9, 0xef, 0xec, 0xce, 0x1a, 0xa2, 0x5c, 0x88, 0xbc, 0xa0, 0x49, 0x46, - 0x24, 0x69, 0xa4, 0xa8, 0x69, 0x72, 0x73, 0x9a, 0x50, 0x2e, 0x99, 0xec, 0xe2, 0xaa, 0x16, 0x52, - 0xa0, 0x43, 0x43, 0xc4, 0x03, 0x11, 0xdf, 0x9c, 0x1e, 0x7d, 0x64, 0x65, 0xa4, 0x62, 0x09, 0xe1, - 0x5c, 0x48, 0x22, 0x99, 0xe0, 0x8d, 0x91, 0x0c, 0x59, 0xbd, 0x5a, 0xb6, 0x2f, 0x93, 0x46, 0xd6, - 0xed, 0x4a, 0xda, 0xec, 0xf1, 0x9b, 0x59, 0xc9, 0x4a, 0xda, 0x48, 0x52, 0x56, 0x16, 0x08, 0x2d, - 0x20, 0xbb, 0x8a, 0x26, 0x05, 0x91, 0x05, 0xcf, 0x4d, 0xe6, 0xe4, 0x17, 0xf0, 0xe7, 0xa4, 0x96, - 0x4c, 0x6d, 0x76, 0x91, 0xa1, 0x8f, 0x01, 0xaa, 0x5a, 0xfc, 0x4e, 0x57, 0x72, 0xc1, 0xb2, 0x70, - 0x14, 0xb9, 0x53, 0x0f, 0x7b, 0x36, 0x72, 0x91, 0xa1, 0x4f, 0x20, 0xe0, 0xa4, 0xa4, 0x4d, 0x45, - 0x56, 0x54, 0x01, 0x3b, 0x1a, 0xf0, 0x87, 0xd8, 0x45, 0x76, 0xf2, 0x8f, 0x0b, 0xe3, 0x4b, 0xda, - 0xa1, 0x67, 0x10, 0x54, 0x7d, 0x61, 0x85, 0xba, 0x91, 0x3b, 0xf5, 0xcf, 0xa2, 0x78, 0x4b, 0xef, - 0xf1, 0x2d, 0x07, 0xd8, 0xaf, 0x6e, 0xd9, 0x79, 0x0c, 0x3b, 0x15, 0x91, 0xaf, 0xc2, 0x51, 0x34, - 0x9e, 0xfa, 0x67, 0x9f, 0x6d, 0x15, 0x5f, 0xd2, 0x2e, 0x9e, 0x13, 0xf9, 0xea, 0xbc, 0xa0, 0x25, - 0xe5, 0x12, 0x6b, 0xc5, 0xd1, 0x0b, 0xd5, 0xd7, 0x10, 0x44, 0x08, 0x76, 0xd6, 0x8c, 0x1b, 0x17, - 0x1e, 0xd6, 0xdf, 0xe8, 0x01, 0x8c, 0x6c, 0x8f, 0xe3, 0xd4, 0xc1, 0x23, 0x96, 0xa1, 0x87, 0xb0, - 0xa3, 0x5a, 0x09, 0xc7, 0x8a, 0x4a, 0x1d, 0xac, 0x57, 0x33, 0x0f, 0xee, 0xb1, 0x6c, 0xa1, 0x8e, - 0xee, 0xe4, 0x29, 0xc0, 0xf7, 0x75, 0x4d, 0xba, 0x2b, 0x52, 0xb4, 0x14, 0x9d, 0xc1, 0xee, 0x8d, - 0xfa, 0x68, 0x42, 0x57, 0xfb, 0x3b, 0xda, 0xea, 0x4f, 0xb3, 0xd8, 0x92, 0x27, 0x7f, 0x4c, 0x60, - 0x62, 0xd4, 0x4f, 0x00, 0x78, 0x5b, 0x14, 0x0b, 0x9d, 0x08, 0xfd, 0xc8, 0x9d, 0xee, 0x6f, 0x2a, - 0xf4, 0x37, 0x19, 0xff, 0xdc, 0x16, 0x85, 0xe6, 0x53, 0x07, 0x7b, 0xbc, 0x5f, 0xa0, 0xcf, 0xe1, - 0xfe, 0x52, 0x88, 0x82, 0x12, 0x6e, 0xf5, 0xaa, 0xb1, 0xbd, 0xd4, 0xc1, 0x81, 0x0d, 0x0f, 0x18, - 0xe3, 0x92, 0xe6, 0xb4, 0xb6, 0x58, 0xdf, 0x6d, 0x60, 0xc3, 0x06, 0xfb, 0x14, 0x82, 0x4c, 0xb4, - 0xcb, 0x82, 0x5a, 0x4a, 0xf5, 0xef, 0xa6, 0x0e, 0xf6, 0x4d, 0xd4, 0x40, 0xe7, 0x70, 0x30, 0x8c, - 0x95, 0xe5, 0x40, 0xdf, 0xe9, 0xdb, 0xa6, 0x5f, 0xf4, 0x5c, 0xea, 0xe0, 0xfd, 0x41, 0x64, 0xca, - 0x7c, 0x0d, 0xde, 0x9a, 0x76, 0xb6, 0xc0, 0x44, 0x17, 0x08, 0xdf, 0x75, 0xaf, 0xa9, 0x83, 0xf7, - 0xd6, 0xb4, 0x1b, 0x4c, 0x36, 0xb2, 0x66, 0x3c, 0xb7, 0xda, 0xf7, 0xec, 0x25, 0xf9, 0x26, 0x6a, - 0xa0, 0x63, 0x80, 0x65, 0x21, 0x96, 0x16, 0x41, 0x91, 0x3b, 0x0d, 0xd4, 0xc1, 0xa9, 0x98, 0x01, - 0xbe, 0x83, 0x83, 0x9c, 0x8a, 0x45, 0x25, 0x18, 0x97, 0x96, 0xda, 0xd3, 0x26, 0x0e, 0x7b, 0x13, - 0xea, 0xa2, 0xe3, 0xe7, 0x44, 0x3e, 0xe7, 0x79, 0xea, 0xe0, 0xfb, 0x39, 0x15, 0x73, 0x05, 0x1b, - 0xf9, 0x53, 0x08, 0xcc, 0x53, 0xb6, 0xda, 0x5d, 0xad, 0xfd, 0x70, 0x6b, 0x03, 0xe7, 0x1a, 0x54, - 0x0e, 0x8d, 0xc4, 0x54, 0x98, 0x81, 0x4f, 0xd4, 0x08, 0xd9, 0x02, 0x9e, 0x2e, 0x70, 0xbc, 0xb5, - 0xc0, 0x66, 0xd4, 0x52, 0x07, 0x03, 0xd9, 0x0c, 0x5e, 0x08, 0xf7, 0x4a, 0x4a, 0x38, 0xe3, 0x79, - 0xb8, 0x1f, 0xb9, 0xd3, 0x09, 0xee, 0x97, 0xe8, 0x11, 0x3c, 0xa4, 0xaf, 0x57, 0x45, 0x9b, 0xd1, - 0xc5, 0xcb, 0x5a, 0x94, 0x0b, 0xc6, 0x33, 0xfa, 0x9a, 0x36, 0xe1, 0xa1, 0x1a, 0x0f, 0x8c, 0x6c, - 0xee, 0xc7, 0x5a, 0x94, 0x17, 0x26, 0x33, 0x0b, 0x00, 0xb4, 0x13, 0x33, 0xe0, 0xff, 0xba, 0xb0, - 0x6b, 0x7c, 0xa3, 0x2f, 0x60, 0xbc, 0xa6, 0x9d, 0x7d, 0xb7, 0xef, 0xbc, 0x22, 0xac, 0x20, 0x74, - 0xa9, 0x7f, 0x1b, 0x15, 0xad, 0x25, 0xa3, 0x4d, 0x38, 0xd6, 0xaf, 0xe1, 0xcb, 0x3b, 0x0e, 0x25, - 0x9e, 0x0f, 0xf4, 0x39, 0x97, 0x75, 0x87, 0x6f, 0xc9, 0x8f, 0x7e, 0x85, 0x83, 0x37, 0xd2, 0xe8, - 0xc1, 0xc6, 0x8b, 0x67, 0x76, 0x7c, 0x04, 0x93, 0xcd, 0x44, 0xdf, 0xfd, 0xf4, 0x0c, 0xf8, 0xcd, - 0xe8, 0xb1, 0x3b, 0xfb, 0xd3, 0x85, 0xf7, 0x57, 0xa2, 0xdc, 0x06, 0xcf, 0x7c, 0x63, 0x6d, 0xae, - 0x86, 0x78, 0xee, 0xfe, 0xf6, 0xad, 0x65, 0x72, 0x51, 0x10, 0x9e, 0xc7, 0xa2, 0xce, 0x93, 0x9c, - 0x72, 0x3d, 0xe2, 0x89, 0x49, 0x91, 0x8a, 0x35, 0xff, 0xfb, 0xcb, 0x3f, 0x19, 0x16, 0x7f, 0x8d, - 0x3e, 0xf8, 0xc9, 0xc8, 0x9f, 0x15, 0xa2, 0xcd, 0xe2, 0x1f, 0x86, 0x8d, 0xae, 0x4e, 0xff, 0xee, - 0x73, 0xd7, 0x3a, 0x77, 0x3d, 0xe4, 0xae, 0xaf, 0x4e, 0x97, 0xbb, 0x7a, 0x83, 0xaf, 0xfe, 0x0b, - 0x00, 0x00, 0xff, 0xff, 0xf3, 0xdd, 0x11, 0x96, 0x45, 0x06, 0x00, 0x00, -} - -var xxx_messageInfo_Key proto.InternalMessageInfo diff --git a/vendor/google.golang.org/appengine/datastore/key.go b/vendor/google.golang.org/appengine/datastore/key.go index fd598dc96..6ab83eaf6 100644 --- a/vendor/google.golang.org/appengine/datastore/key.go +++ b/vendor/google.golang.org/appengine/datastore/key.go @@ -254,10 +254,6 @@ func DecodeKey(encoded string) (*Key, error) { ref := new(pb.Reference) if err := proto.Unmarshal(b, ref); err != nil { - // Couldn't decode it as an App Engine key, try decoding it as a key encoded by cloud.google.com/go/datastore. - if k := decodeCloudKey(encoded); k != nil { - return k, nil - } return nil, err } diff --git a/vendor/google.golang.org/appengine/datastore/keycompat.go b/vendor/google.golang.org/appengine/datastore/keycompat.go deleted file mode 100644 index 371a64eee..000000000 --- a/vendor/google.golang.org/appengine/datastore/keycompat.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2019 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package datastore - -import ( - "sync" - - "golang.org/x/net/context" - - "google.golang.org/appengine/datastore/internal/cloudkey" - "google.golang.org/appengine/internal" -) - -var keyConversion struct { - mu sync.RWMutex - appID string // read using getKeyConversionAppID -} - -// EnableKeyConversion enables encoded key compatibility with the Cloud -// Datastore client library (cloud.google.com/go/datastore). Encoded keys -// generated by the Cloud Datastore client library will be decoded into App -// Engine datastore keys. -// -// The context provided must be an App Engine context if running in App Engine -// first generation runtime. This can be called in the /_ah/start handler. It is -// safe to call multiple times, and is cheap to call, so can also be inserted as -// middleware. -// -// Enabling key compatibility does not affect the encoding format used by -// Key.Encode, it only expands the type of keys that are able to be decoded with -// DecodeKey. -func EnableKeyConversion(ctx context.Context) { - // Only attempt to set appID if it's unset. - // If already set, ignore. - if getKeyConversionAppID() != "" { - return - } - - keyConversion.mu.Lock() - // Check again to avoid race where another goroutine set appID between the call - // to getKeyConversionAppID above and taking the write lock. - if keyConversion.appID == "" { - keyConversion.appID = internal.FullyQualifiedAppID(ctx) - } - keyConversion.mu.Unlock() -} - -func getKeyConversionAppID() string { - keyConversion.mu.RLock() - appID := keyConversion.appID - keyConversion.mu.RUnlock() - return appID -} - -// decodeCloudKey attempts to decode the given encoded key generated by the -// Cloud Datastore client library (cloud.google.com/go/datastore), returning nil -// if the key couldn't be decoded. -func decodeCloudKey(encoded string) *Key { - appID := getKeyConversionAppID() - if appID == "" { - return nil - } - - k, err := cloudkey.DecodeKey(encoded) - if err != nil { - return nil - } - return convertCloudKey(k, appID) -} - -// convertCloudKey converts a Cloud Datastore key and converts it to an App -// Engine Datastore key. Cloud Datastore keys don't include the project/app ID, -// so we must add it back in. -func convertCloudKey(key *cloudkey.Key, appID string) *Key { - if key == nil { - return nil - } - k := &Key{ - intID: key.ID, - kind: key.Kind, - namespace: key.Namespace, - parent: convertCloudKey(key.Parent, appID), - stringID: key.Name, - appID: appID, - } - return k -} diff --git a/vendor/google.golang.org/appengine/datastore/keycompat_test.go b/vendor/google.golang.org/appengine/datastore/keycompat_test.go deleted file mode 100644 index 923fdac9a..000000000 --- a/vendor/google.golang.org/appengine/datastore/keycompat_test.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2019 Google Inc. All Rights Reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package datastore - -import ( - "reflect" - "testing" -) - -func TestKeyConversion(t *testing.T) { - var tests = []struct { - desc string - key *Key - encodedKey string - }{ - { - desc: "A control test for legacy to legacy key conversion int as the key", - key: &Key{ - kind: "Person", - intID: 1, - appID: "glibrary", - }, - encodedKey: "aghnbGlicmFyeXIMCxIGUGVyc29uGAEM", - }, - { - desc: "A control test for legacy to legacy key conversion string as the key", - key: &Key{ - kind: "Graph", - stringID: "graph:7-day-active", - appID: "glibrary", - }, - encodedKey: "aghnbGlicmFyeXIdCxIFR3JhcGgiEmdyYXBoOjctZGF5LWFjdGl2ZQw", - }, - - // These are keys encoded with cloud.google.com/go/datastore - // Standard int as the key - { - desc: "Convert new key format to old key with int id", - key: &Key{ - kind: "WordIndex", - intID: 1033, - appID: "glibrary", - }, - encodedKey: "Eg4KCVdvcmRJbmRleBCJCA", - }, - // These are keys encoded with cloud.google.com/go/datastore - // Standard string - { - desc: "Convert new key format to old key with string id", - key: &Key{ - kind: "WordIndex", - stringID: "IAmAnID", - appID: "glibrary", - }, - encodedKey: "EhQKCVdvcmRJbmRleBoHSUFtQW5JRA", - }, - - // These are keys encoded with cloud.google.com/go/datastore - // ID String with parent as string - { - desc: "Convert new key format to old key with string id with a parent", - key: &Key{ - kind: "WordIndex", - stringID: "IAmAnID", - appID: "glibrary", - parent: &Key{ - kind: "LetterIndex", - stringID: "IAmAnotherID", - appID: "glibrary", - }, - }, - encodedKey: "EhsKC0xldHRlckluZGV4GgxJQW1Bbm90aGVySUQSFAoJV29yZEluZGV4GgdJQW1BbklE", - }, - } - - // Simulate the key converter enablement - keyConversion.appID = "glibrary" - for _, tc := range tests { - dk, err := DecodeKey(tc.encodedKey) - if err != nil { - t.Fatalf("DecodeKey: %v", err) - } - if !reflect.DeepEqual(dk, tc.key) { - t.Errorf("%s: got %+v, want %+v", tc.desc, dk, tc.key) - } - } -} diff --git a/vendor/google.golang.org/appengine/delay/delay.go b/vendor/google.golang.org/appengine/delay/delay.go index 0a8df6229..a5d818602 100644 --- a/vendor/google.golang.org/appengine/delay/delay.go +++ b/vendor/google.golang.org/appengine/delay/delay.go @@ -118,14 +118,14 @@ var modVersionPat = regexp.MustCompile("@v[^/]+") // For calls from package main: strip all leading path entries, leaving just the filename. // For calls from anywhere else, strip $GOPATH/src, leaving just the package path and file path. func fileKey(file string) (string, error) { - if !internal.IsSecondGen() { + if !internal.IsSecondGen() || internal.MainPath == "" { return file, nil } // If the caller is in the same Dir as mainPath, then strip everything but the file name. if filepath.Dir(file) == internal.MainPath { return filepath.Base(file), nil } - // If the path contains "gopath/src/", which is what the builder uses for + // If the path contains "_gopath/src/", which is what the builder uses for // apps which don't use go modules, strip everything up to and including src. // Or, if the path starts with /tmp/staging, then we're importing a package // from the app's module (and we must be using go modules), and we have a @@ -133,7 +133,7 @@ func fileKey(file string) (string, error) { // including the first /srv/. // And be sure to look at the GOPATH, for local development. s := string(filepath.Separator) - for _, s := range []string{filepath.Join("gopath", "src") + s, s + "srv" + s, filepath.Join(build.Default.GOPATH, "src") + s} { + for _, s := range []string{filepath.Join("_gopath", "src") + s, s + "srv" + s, filepath.Join(build.Default.GOPATH, "src") + s} { if idx := strings.Index(file, s); idx > 0 { return file[idx+len(s):], nil } diff --git a/vendor/google.golang.org/appengine/delay/delay_test.go b/vendor/google.golang.org/appengine/delay/delay_test.go index 217af0c68..06f2912ea 100644 --- a/vendor/google.golang.org/appengine/delay/delay_test.go +++ b/vendor/google.golang.org/appengine/delay/delay_test.go @@ -466,7 +466,7 @@ func TestStandardContext(t *testing.T) { } func TestFileKey(t *testing.T) { - const firstGenTest = 0 + os.Setenv("GAE_ENV", "standard") tests := []struct { mainPath string file string @@ -499,16 +499,6 @@ func TestFileKey(t *testing.T) { filepath.FromSlash("/tmp/staging3234/srv/_gopath/src/example.com/bar/main.go"), filepath.FromSlash("example.com/bar/main.go"), }, - { - filepath.FromSlash("/tmp/staging3234/srv/gopath/src/example.com/foo"), - filepath.FromSlash("/tmp/staging3234/srv/gopath/src/example.com/bar/main.go"), - filepath.FromSlash("example.com/bar/main.go"), - }, - { - filepath.FromSlash(""), - filepath.FromSlash("/tmp/staging3234/srv/gopath/src/example.com/bar/main.go"), - filepath.FromSlash("example.com/bar/main.go"), - }, // go mod, same package { filepath.FromSlash("/tmp/staging3234/srv"), @@ -530,11 +520,6 @@ func TestFileKey(t *testing.T) { filepath.FromSlash("/tmp/staging3234/srv/bar/main.go"), filepath.FromSlash("bar/main.go"), }, - { - filepath.FromSlash(""), - filepath.FromSlash("/tmp/staging3234/srv/bar/main.go"), - filepath.FromSlash("bar/main.go"), - }, // go mod, other package { filepath.FromSlash("/tmp/staging3234/srv"), @@ -543,9 +528,6 @@ func TestFileKey(t *testing.T) { }, } for i, tc := range tests { - if i > firstGenTest { - os.Setenv("GAE_ENV", "standard") - } internal.MainPath = tc.mainPath got, err := fileKey(tc.file) if err != nil { diff --git a/vendor/google.golang.org/appengine/file/file.go b/vendor/google.golang.org/appengine/file/file.go index e63a4aca9..c3cd58baf 100644 --- a/vendor/google.golang.org/appengine/file/file.go +++ b/vendor/google.golang.org/appengine/file/file.go @@ -22,7 +22,7 @@ func DefaultBucketName(c context.Context) (string, error) { err := internal.Call(c, "app_identity_service", "GetDefaultGcsBucketName", req, res) if err != nil { - return "", fmt.Errorf("file: no default bucket name returned in RPC response: %v", err) + return "", fmt.Errorf("file: no default bucket name returned in RPC response: %v", res) } return res.GetDefaultGcsBucketName(), nil } diff --git a/vendor/google.golang.org/appengine/go.mod b/vendor/google.golang.org/appengine/go.mod index 635c34f5a..f449359d2 100644 --- a/vendor/google.golang.org/appengine/go.mod +++ b/vendor/google.golang.org/appengine/go.mod @@ -1,9 +1,7 @@ module google.golang.org/appengine -go 1.11 - require ( - github.com/golang/protobuf v1.3.1 - golang.org/x/net v0.0.0-20190603091049-60506f45cf65 - golang.org/x/text v0.3.2 + github.com/golang/protobuf v1.2.0 + golang.org/x/net v0.0.0-20180724234803-3673e40ba225 + golang.org/x/text v0.3.0 ) diff --git a/vendor/google.golang.org/appengine/go.sum b/vendor/google.golang.org/appengine/go.sum index ce22f6856..1a221c089 100644 --- a/vendor/google.golang.org/appengine/go.sum +++ b/vendor/google.golang.org/appengine/go.sum @@ -1,11 +1,6 @@ -github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225 h1:kNX+jCowfMYzvlSvJu5pQWEmyWFrBXJ3PBy10xKMXK8= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/vendor/google.golang.org/appengine/internal/api.go b/vendor/google.golang.org/appengine/internal/api.go index 721053c20..a6ec19e14 100644 --- a/vendor/google.golang.org/appengine/internal/api.go +++ b/vendor/google.golang.org/appengine/internal/api.go @@ -58,11 +58,8 @@ var ( apiHTTPClient = &http.Client{ Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: limitDial, - MaxIdleConns: 1000, - MaxIdleConnsPerHost: 10000, - IdleConnTimeout: 90 * time.Second, + Proxy: http.ProxyFromEnvironment, + Dial: limitDial, }, } diff --git a/vendor/google.golang.org/appengine/internal/net.go b/vendor/google.golang.org/appengine/internal/net.go index fe429720e..3b94cf0c6 100644 --- a/vendor/google.golang.org/appengine/internal/net.go +++ b/vendor/google.golang.org/appengine/internal/net.go @@ -32,7 +32,7 @@ func limitDial(network, addr string) (net.Conn, error) { // Dial with a timeout in case the API host is MIA. // The connection should normally be very fast. - conn, err := net.DialTimeout(network, addr, 10*time.Second) + conn, err := net.DialTimeout(network, addr, 500*time.Millisecond) if err != nil { limitRelease() return nil, err diff --git a/vendor/sigs.k8s.io/yaml/.travis.yml b/vendor/sigs.k8s.io/yaml/.travis.yml index d20e23eff..03ddc7318 100644 --- a/vendor/sigs.k8s.io/yaml/.travis.yml +++ b/vendor/sigs.k8s.io/yaml/.travis.yml @@ -1,13 +1,14 @@ language: go dist: xenial go: - - 1.12.x - - 1.13.x + - 1.9.x + - 1.10.x + - 1.11.x script: - - diff -u <(echo -n) <(gofmt -d *.go) + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d .) - diff -u <(echo -n) <(golint $(go list -e ./...) | grep -v YAMLToJSON) - - GO111MODULE=on go vet . - - GO111MODULE=on go test -v -race ./... - - git diff --exit-code + - go tool vet . + - go test -v -race ./... install: - - GO111MODULE=off go get golang.org/x/lint/golint + - go get golang.org/x/lint/golint diff --git a/vendor/sigs.k8s.io/yaml/OWNERS b/vendor/sigs.k8s.io/yaml/OWNERS index 325b40b07..11ad7ce1a 100644 --- a/vendor/sigs.k8s.io/yaml/OWNERS +++ b/vendor/sigs.k8s.io/yaml/OWNERS @@ -1,5 +1,3 @@ -# See the OWNERS docs at https://go.k8s.io/owners - approvers: - dims - lavalamp diff --git a/vendor/sigs.k8s.io/yaml/README.md b/vendor/sigs.k8s.io/yaml/README.md index 5a651d916..0200f75b4 100644 --- a/vendor/sigs.k8s.io/yaml/README.md +++ b/vendor/sigs.k8s.io/yaml/README.md @@ -1,14 +1,12 @@ # YAML marshaling and unmarshaling support for Go -[![Build Status](https://travis-ci.org/kubernetes-sigs/yaml.svg)](https://travis-ci.org/kubernetes-sigs/yaml) - -kubernetes-sigs/yaml is a permanent fork of [ghodss/yaml](https://github.com/ghodss/yaml). +[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) ## Introduction A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://web.archive.org/web/20190603050330/http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). +In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). ## Compatibility @@ -34,13 +32,13 @@ GOOD: To install, run: ``` -$ go get sigs.k8s.io/yaml +$ go get github.com/ghodss/yaml ``` And import using: ``` -import "sigs.k8s.io/yaml" +import "github.com/ghodss/yaml" ``` Usage is very similar to the JSON library: @@ -51,7 +49,7 @@ package main import ( "fmt" - "sigs.k8s.io/yaml" + "github.com/ghodss/yaml" ) type Person struct { @@ -95,7 +93,7 @@ package main import ( "fmt" - "sigs.k8s.io/yaml" + "github.com/ghodss/yaml" ) func main() { diff --git a/vendor/sigs.k8s.io/yaml/go.mod b/vendor/sigs.k8s.io/yaml/go.mod deleted file mode 100644 index 7224f3497..000000000 --- a/vendor/sigs.k8s.io/yaml/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module sigs.k8s.io/yaml - -go 1.12 - -require ( - github.com/davecgh/go-spew v1.1.1 - gopkg.in/yaml.v2 v2.2.8 -) diff --git a/vendor/sigs.k8s.io/yaml/go.sum b/vendor/sigs.k8s.io/yaml/go.sum deleted file mode 100644 index 76e49483a..000000000 --- a/vendor/sigs.k8s.io/yaml/go.sum +++ /dev/null @@ -1,9 +0,0 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo= -gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/sigs.k8s.io/yaml/yaml.go b/vendor/sigs.k8s.io/yaml/yaml.go index efbc535d4..024596112 100644 --- a/vendor/sigs.k8s.io/yaml/yaml.go +++ b/vendor/sigs.k8s.io/yaml/yaml.go @@ -317,64 +317,3 @@ func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (in return yamlObj, nil } } - -// JSONObjectToYAMLObject converts an in-memory JSON object into a YAML in-memory MapSlice, -// without going through a byte representation. A nil or empty map[string]interface{} input is -// converted to an empty map, i.e. yaml.MapSlice(nil). -// -// interface{} slices stay interface{} slices. map[string]interface{} becomes yaml.MapSlice. -// -// int64 and float64 are down casted following the logic of github.com/go-yaml/yaml: -// - float64s are down-casted as far as possible without data-loss to int, int64, uint64. -// - int64s are down-casted to int if possible without data-loss. -// -// Big int/int64/uint64 do not lose precision as in the json-yaml roundtripping case. -// -// string, bool and any other types are unchanged. -func JSONObjectToYAMLObject(j map[string]interface{}) yaml.MapSlice { - if len(j) == 0 { - return nil - } - ret := make(yaml.MapSlice, 0, len(j)) - for k, v := range j { - ret = append(ret, yaml.MapItem{Key: k, Value: jsonToYAMLValue(v)}) - } - return ret -} - -func jsonToYAMLValue(j interface{}) interface{} { - switch j := j.(type) { - case map[string]interface{}: - if j == nil { - return interface{}(nil) - } - return JSONObjectToYAMLObject(j) - case []interface{}: - if j == nil { - return interface{}(nil) - } - ret := make([]interface{}, len(j)) - for i := range j { - ret[i] = jsonToYAMLValue(j[i]) - } - return ret - case float64: - // replicate the logic in https://github.com/go-yaml/yaml/blob/51d6538a90f86fe93ac480b35f37b2be17fef232/resolve.go#L151 - if i64 := int64(j); j == float64(i64) { - if i := int(i64); i64 == int64(i) { - return i - } - return i64 - } - if ui64 := uint64(j); j == float64(ui64) { - return ui64 - } - return j - case int64: - if i := int(j); j == int64(i) { - return i - } - return j - } - return j -} diff --git a/vendor/sigs.k8s.io/yaml/yaml_test.go b/vendor/sigs.k8s.io/yaml/yaml_test.go index a88cbf3b3..42a231567 100644 --- a/vendor/sigs.k8s.io/yaml/yaml_test.go +++ b/vendor/sigs.k8s.io/yaml/yaml_test.go @@ -1,16 +1,11 @@ package yaml import ( - "encoding/json" "fmt" "math" "reflect" - "sort" "strconv" "testing" - - "github.com/davecgh/go-spew/spew" - yaml "gopkg.in/yaml.v2" ) type MarshalTest struct { @@ -426,120 +421,3 @@ foo: baz t.Error("expected YAMLtoJSONStrict to fail on duplicate field names") } } - -func TestJSONObjectToYAMLObject(t *testing.T) { - intOrInt64 := func(i64 int64) interface{} { - if i := int(i64); i64 == int64(i) { - return i - } - return i64 - } - - tests := []struct { - name string - input map[string]interface{} - expected yaml.MapSlice - }{ - {name: "nil", expected: yaml.MapSlice(nil)}, - {name: "empty", input: map[string]interface{}{}, expected: yaml.MapSlice(nil)}, - { - name: "values", - input: map[string]interface{}{ - "nil slice": []interface{}(nil), - "nil map": map[string]interface{}(nil), - "empty slice": []interface{}{}, - "empty map": map[string]interface{}{}, - "bool": true, - "float64": float64(42.1), - "fractionless": float64(42), - "int": int(42), - "int64": int64(42), - "int64 big": float64(math.Pow(2, 62)), - "negative int64 big": -float64(math.Pow(2, 62)), - "map": map[string]interface{}{"foo": "bar"}, - "slice": []interface{}{"foo", "bar"}, - "string": string("foo"), - "uint64 big": float64(math.Pow(2, 63)), - }, - expected: yaml.MapSlice{ - {Key: "nil slice"}, - {Key: "nil map"}, - {Key: "empty slice", Value: []interface{}{}}, - {Key: "empty map", Value: yaml.MapSlice(nil)}, - {Key: "bool", Value: true}, - {Key: "float64", Value: float64(42.1)}, - {Key: "fractionless", Value: int(42)}, - {Key: "int", Value: int(42)}, - {Key: "int64", Value: int(42)}, - {Key: "int64 big", Value: intOrInt64(int64(1) << 62)}, - {Key: "negative int64 big", Value: intOrInt64(-(1 << 62))}, - {Key: "map", Value: yaml.MapSlice{{Key: "foo", Value: "bar"}}}, - {Key: "slice", Value: []interface{}{"foo", "bar"}}, - {Key: "string", Value: string("foo")}, - {Key: "uint64 big", Value: uint64(1) << 63}, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := JSONObjectToYAMLObject(tt.input) - sortMapSlicesInPlace(tt.expected) - sortMapSlicesInPlace(got) - if !reflect.DeepEqual(got, tt.expected) { - t.Errorf("jsonToYAML() = %v, want %v", spew.Sdump(got), spew.Sdump(tt.expected)) - } - - jsonBytes, err := json.Marshal(tt.input) - if err != nil { - t.Fatalf("unexpected json.Marshal error: %v", err) - } - var gotByRoundtrip yaml.MapSlice - if err := yaml.Unmarshal(jsonBytes, &gotByRoundtrip); err != nil { - t.Fatalf("unexpected yaml.Unmarshal error: %v", err) - } - - // yaml.Unmarshal loses precision, it's rounding to the 4th last digit. - // Replicate this here in the test, but don't change the type. - for i := range got { - switch got[i].Key { - case "int64 big", "uint64 big", "negative int64 big": - switch v := got[i].Value.(type) { - case int64: - d := int64(500) - if v < 0 { - d = -500 - } - got[i].Value = int64((v+d)/1000) * 1000 - case uint64: - got[i].Value = uint64((v+500)/1000) * 1000 - case int: - d := int(500) - if v < 0 { - d = -500 - } - got[i].Value = int((v+d)/1000) * 1000 - default: - t.Fatalf("unexpected type for key %s: %v:%T", got[i].Key, v, v) - } - } - } - - if !reflect.DeepEqual(got, gotByRoundtrip) { - t.Errorf("yaml.Unmarshal(json.Marshal(tt.input)) = %v, want %v\njson: %s", spew.Sdump(gotByRoundtrip), spew.Sdump(got), string(jsonBytes)) - } - }) - } -} - -func sortMapSlicesInPlace(x interface{}) { - switch x := x.(type) { - case []interface{}: - for i := range x { - sortMapSlicesInPlace(x[i]) - } - case yaml.MapSlice: - sort.Slice(x, func(a, b int) bool { - return x[a].Key.(string) < x[b].Key.(string) - }) - } -}