aboutsummaryrefslogtreecommitdiffstats
path: root/vendor
diff options
context:
space:
mode:
Diffstat (limited to 'vendor')
-rw-r--r--vendor/github.com/BurntSushi/toml/.gitignore2
-rw-r--r--vendor/github.com/BurntSushi/toml/COPYING21
-rw-r--r--vendor/github.com/BurntSushi/toml/README.md120
-rw-r--r--vendor/github.com/BurntSushi/toml/decode.go602
-rw-r--r--vendor/github.com/BurntSushi/toml/decode_go116.go19
-rw-r--r--vendor/github.com/BurntSushi/toml/deprecated.go29
-rw-r--r--vendor/github.com/BurntSushi/toml/doc.go11
-rw-r--r--vendor/github.com/BurntSushi/toml/encode.go759
-rw-r--r--vendor/github.com/BurntSushi/toml/error.go279
-rw-r--r--vendor/github.com/BurntSushi/toml/internal/tz.go36
-rw-r--r--vendor/github.com/BurntSushi/toml/lex.go1283
-rw-r--r--vendor/github.com/BurntSushi/toml/meta.go121
-rw-r--r--vendor/github.com/BurntSushi/toml/parse.go811
-rw-r--r--vendor/github.com/BurntSushi/toml/type_fields.go242
-rw-r--r--vendor/github.com/BurntSushi/toml/type_toml.go70
-rw-r--r--vendor/github.com/google/go-cmp/LICENSE27
-rw-r--r--vendor/github.com/google/go-cmp/cmp/compare.go669
-rw-r--r--vendor/github.com/google/go-cmp/cmp/export_panic.go16
-rw-r--r--vendor/github.com/google/go-cmp/cmp/export_unsafe.go36
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go18
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go123
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go402
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go9
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/function/func.go99
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/value/name.go164
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go34
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go37
-rw-r--r--vendor/github.com/google/go-cmp/cmp/internal/value/sort.go106
-rw-r--r--vendor/github.com/google/go-cmp/cmp/options.go554
-rw-r--r--vendor/github.com/google/go-cmp/cmp/path.go380
-rw-r--r--vendor/github.com/google/go-cmp/cmp/report.go54
-rw-r--r--vendor/github.com/google/go-cmp/cmp/report_compare.go433
-rw-r--r--vendor/github.com/google/go-cmp/cmp/report_references.go264
-rw-r--r--vendor/github.com/google/go-cmp/cmp/report_reflect.go414
-rw-r--r--vendor/github.com/google/go-cmp/cmp/report_slices.go614
-rw-r--r--vendor/github.com/google/go-cmp/cmp/report_text.go432
-rw-r--r--vendor/github.com/google/go-cmp/cmp/report_value.go121
-rw-r--r--vendor/github.com/google/subcommands/CONTRIBUTING27
-rw-r--r--vendor/github.com/google/subcommands/LICENSE202
-rw-r--r--vendor/github.com/google/subcommands/README.md67
-rw-r--r--vendor/github.com/google/subcommands/subcommands.go512
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/.travis.yml13
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/LICENSE19
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/MAINTAINERS2
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/README.md192
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/doc.go8
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/env_os.go7
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/env_syscall.go7
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/envconfig.go382
-rw-r--r--vendor/github.com/kelseyhightower/envconfig/usage.go164
-rw-r--r--vendor/github.com/lib/pq/.gitignore6
-rw-r--r--vendor/github.com/lib/pq/LICENSE.md8
-rw-r--r--vendor/github.com/lib/pq/README.md36
-rw-r--r--vendor/github.com/lib/pq/TESTS.md33
-rw-r--r--vendor/github.com/lib/pq/array.go895
-rw-r--r--vendor/github.com/lib/pq/buf.go91
-rw-r--r--vendor/github.com/lib/pq/conn.go2112
-rw-r--r--vendor/github.com/lib/pq/conn_go115.go8
-rw-r--r--vendor/github.com/lib/pq/conn_go18.go247
-rw-r--r--vendor/github.com/lib/pq/connector.go120
-rw-r--r--vendor/github.com/lib/pq/copy.go348
-rw-r--r--vendor/github.com/lib/pq/doc.go268
-rw-r--r--vendor/github.com/lib/pq/encode.go632
-rw-r--r--vendor/github.com/lib/pq/error.go523
-rw-r--r--vendor/github.com/lib/pq/krb.go27
-rw-r--r--vendor/github.com/lib/pq/notice.go72
-rw-r--r--vendor/github.com/lib/pq/notify.go858
-rw-r--r--vendor/github.com/lib/pq/oid/doc.go6
-rw-r--r--vendor/github.com/lib/pq/oid/types.go343
-rw-r--r--vendor/github.com/lib/pq/rows.go93
-rw-r--r--vendor/github.com/lib/pq/scram/scram.go264
-rw-r--r--vendor/github.com/lib/pq/ssl.go204
-rw-r--r--vendor/github.com/lib/pq/ssl_permissions.go93
-rw-r--r--vendor/github.com/lib/pq/ssl_windows.go10
-rw-r--r--vendor/github.com/lib/pq/url.go76
-rw-r--r--vendor/github.com/lib/pq/user_other.go10
-rw-r--r--vendor/github.com/lib/pq/user_posix.go25
-rw-r--r--vendor/github.com/lib/pq/user_windows.go27
-rw-r--r--vendor/github.com/lib/pq/uuid.go23
-rw-r--r--vendor/gotest.tools/v3/LICENSE13
-rw-r--r--vendor/gotest.tools/v3/assert/assert.go313
-rw-r--r--vendor/gotest.tools/v3/assert/cmp/compare.go404
-rw-r--r--vendor/gotest.tools/v3/assert/cmp/result.go110
-rw-r--r--vendor/gotest.tools/v3/internal/assert/assert.go161
-rw-r--r--vendor/gotest.tools/v3/internal/assert/result.go146
-rw-r--r--vendor/gotest.tools/v3/internal/difflib/LICENSE27
-rw-r--r--vendor/gotest.tools/v3/internal/difflib/difflib.go423
-rw-r--r--vendor/gotest.tools/v3/internal/format/diff.go162
-rw-r--r--vendor/gotest.tools/v3/internal/format/format.go27
-rw-r--r--vendor/gotest.tools/v3/internal/source/defers.go52
-rw-r--r--vendor/gotest.tools/v3/internal/source/source.go148
-rw-r--r--vendor/gotest.tools/v3/internal/source/update.go171
-rw-r--r--vendor/gotest.tools/v3/internal/source/version.go35
-rw-r--r--vendor/modules.txt30
94 files changed, 0 insertions, 20693 deletions
diff --git a/vendor/github.com/BurntSushi/toml/.gitignore b/vendor/github.com/BurntSushi/toml/.gitignore
deleted file mode 100644
index fe79e3a..0000000
--- a/vendor/github.com/BurntSushi/toml/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/toml.test
-/toml-test
diff --git a/vendor/github.com/BurntSushi/toml/COPYING b/vendor/github.com/BurntSushi/toml/COPYING
deleted file mode 100644
index 01b5743..0000000
--- a/vendor/github.com/BurntSushi/toml/COPYING
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013 TOML authors
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/vendor/github.com/BurntSushi/toml/README.md b/vendor/github.com/BurntSushi/toml/README.md
deleted file mode 100644
index 3651cfa..0000000
--- a/vendor/github.com/BurntSushi/toml/README.md
+++ /dev/null
@@ -1,120 +0,0 @@
-TOML stands for Tom's Obvious, Minimal Language. This Go package provides a
-reflection interface similar to Go's standard library `json` and `xml` packages.
-
-Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0).
-
-Documentation: https://godocs.io/github.com/BurntSushi/toml
-
-See the [releases page](https://github.com/BurntSushi/toml/releases) for a
-changelog; this information is also in the git tag annotations (e.g. `git show
-v0.4.0`).
-
-This library requires Go 1.13 or newer; add it to your go.mod with:
-
- % go get github.com/BurntSushi/toml@latest
-
-It also comes with a TOML validator CLI tool:
-
- % go install github.com/BurntSushi/toml/cmd/tomlv@latest
- % tomlv some-toml-file.toml
-
-### Examples
-For the simplest example, consider some TOML file as just a list of keys and
-values:
-
-```toml
-Age = 25
-Cats = [ "Cauchy", "Plato" ]
-Pi = 3.14
-Perfection = [ 6, 28, 496, 8128 ]
-DOB = 1987-07-05T05:45:00Z
-```
-
-Which can be decoded with:
-
-```go
-type Config struct {
- Age int
- Cats []string
- Pi float64
- Perfection []int
- DOB time.Time
-}
-
-var conf Config
-_, err := toml.Decode(tomlData, &conf)
-```
-
-You can also use struct tags if your struct field name doesn't map to a TOML key
-value directly:
-
-```toml
-some_key_NAME = "wat"
-```
-
-```go
-type TOML struct {
- ObscureKey string `toml:"some_key_NAME"`
-}
-```
-
-Beware that like other decoders **only exported fields** are considered when
-encoding and decoding; private fields are silently ignored.
-
-### Using the `Marshaler` and `encoding.TextUnmarshaler` interfaces
-Here's an example that automatically parses values in a `mail.Address`:
-
-```toml
-contacts = [
- "Donald Duck <donald@duckburg.com>",
- "Scrooge McDuck <scrooge@duckburg.com>",
-]
-```
-
-Can be decoded with:
-
-```go
-// Create address type which satisfies the encoding.TextUnmarshaler interface.
-type address struct {
- *mail.Address
-}
-
-func (a *address) UnmarshalText(text []byte) error {
- var err error
- a.Address, err = mail.ParseAddress(string(text))
- return err
-}
-
-// Decode it.
-func decode() {
- blob := `
- contacts = [
- "Donald Duck <donald@duckburg.com>",
- "Scrooge McDuck <scrooge@duckburg.com>",
- ]
- `
-
- var contacts struct {
- Contacts []address
- }
-
- _, err := toml.Decode(blob, &contacts)
- if err != nil {
- log.Fatal(err)
- }
-
- for _, c := range contacts.Contacts {
- fmt.Printf("%#v\n", c.Address)
- }
-
- // Output:
- // &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"}
- // &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"}
-}
-```
-
-To target TOML specifically you can implement `UnmarshalTOML` TOML interface in
-a similar way.
-
-### More complex usage
-See the [`_example/`](/_example) directory for a more complex example.
diff --git a/vendor/github.com/BurntSushi/toml/decode.go b/vendor/github.com/BurntSushi/toml/decode.go
deleted file mode 100644
index 4d38f3b..0000000
--- a/vendor/github.com/BurntSushi/toml/decode.go
+++ /dev/null
@@ -1,602 +0,0 @@
-package toml
-
-import (
- "bytes"
- "encoding"
- "encoding/json"
- "fmt"
- "io"
- "io/ioutil"
- "math"
- "os"
- "reflect"
- "strconv"
- "strings"
- "time"
-)
-
-// Unmarshaler is the interface implemented by objects that can unmarshal a
-// TOML description of themselves.
-type Unmarshaler interface {
- UnmarshalTOML(interface{}) error
-}
-
-// Unmarshal decodes the contents of data in TOML format into a pointer v.
-//
-// See [Decoder] for a description of the decoding process.
-func Unmarshal(data []byte, v interface{}) error {
- _, err := NewDecoder(bytes.NewReader(data)).Decode(v)
- return err
-}
-
-// Decode the TOML data in to the pointer v.
-//
-// See [Decoder] for a description of the decoding process.
-func Decode(data string, v interface{}) (MetaData, error) {
- return NewDecoder(strings.NewReader(data)).Decode(v)
-}
-
-// DecodeFile reads the contents of a file and decodes it with [Decode].
-func DecodeFile(path string, v interface{}) (MetaData, error) {
- fp, err := os.Open(path)
- if err != nil {
- return MetaData{}, err
- }
- defer fp.Close()
- return NewDecoder(fp).Decode(v)
-}
-
-// Primitive is a TOML value that hasn't been decoded into a Go value.
-//
-// This type can be used for any value, which will cause decoding to be delayed.
-// You can use [PrimitiveDecode] to "manually" decode these values.
-//
-// NOTE: The underlying representation of a `Primitive` value is subject to
-// change. Do not rely on it.
-//
-// NOTE: Primitive values are still parsed, so using them will only avoid the
-// overhead of reflection. They can be useful when you don't know the exact type
-// of TOML data until runtime.
-type Primitive struct {
- undecoded interface{}
- context Key
-}
-
-// The significand precision for float32 and float64 is 24 and 53 bits; this is
-// the range a natural number can be stored in a float without loss of data.
-const (
- maxSafeFloat32Int = 16777215 // 2^24-1
- maxSafeFloat64Int = int64(9007199254740991) // 2^53-1
-)
-
-// Decoder decodes TOML data.
-//
-// TOML tables correspond to Go structs or maps; they can be used
-// interchangeably, but structs offer better type safety.
-//
-// TOML table arrays correspond to either a slice of structs or a slice of maps.
-//
-// TOML datetimes correspond to [time.Time]. Local datetimes are parsed in the
-// local timezone.
-//
-// [time.Duration] types are treated as nanoseconds if the TOML value is an
-// integer, or they're parsed with time.ParseDuration() if they're strings.
-//
-// All other TOML types (float, string, int, bool and array) correspond to the
-// obvious Go types.
-//
-// An exception to the above rules is if a type implements the TextUnmarshaler
-// interface, in which case any primitive TOML value (floats, strings, integers,
-// booleans, datetimes) will be converted to a []byte and given to the value's
-// UnmarshalText method. See the Unmarshaler example for a demonstration with
-// email addresses.
-//
-// # Key mapping
-//
-// TOML keys can map to either keys in a Go map or field names in a Go struct.
-// The special `toml` struct tag can be used to map TOML keys to struct fields
-// that don't match the key name exactly (see the example). A case insensitive
-// match to struct names will be tried if an exact match can't be found.
-//
-// The mapping between TOML values and Go values is loose. That is, there may
-// exist TOML values that cannot be placed into your representation, and there
-// may be parts of your representation that do not correspond to TOML values.
-// This loose mapping can be made stricter by using the IsDefined and/or
-// Undecoded methods on the MetaData returned.
-//
-// This decoder does not handle cyclic types. Decode will not terminate if a
-// cyclic type is passed.
-type Decoder struct {
- r io.Reader
-}
-
-// NewDecoder creates a new Decoder.
-func NewDecoder(r io.Reader) *Decoder {
- return &Decoder{r: r}
-}
-
-var (
- unmarshalToml = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
- unmarshalText = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
- primitiveType = reflect.TypeOf((*Primitive)(nil)).Elem()
-)
-
-// Decode TOML data in to the pointer `v`.
-func (dec *Decoder) Decode(v interface{}) (MetaData, error) {
- rv := reflect.ValueOf(v)
- if rv.Kind() != reflect.Ptr {
- s := "%q"
- if reflect.TypeOf(v) == nil {
- s = "%v"
- }
-
- return MetaData{}, fmt.Errorf("toml: cannot decode to non-pointer "+s, reflect.TypeOf(v))
- }
- if rv.IsNil() {
- return MetaData{}, fmt.Errorf("toml: cannot decode to nil value of %q", reflect.TypeOf(v))
- }
-
- // Check if this is a supported type: struct, map, interface{}, or something
- // that implements UnmarshalTOML or UnmarshalText.
- rv = indirect(rv)
- rt := rv.Type()
- if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map &&
- !(rv.Kind() == reflect.Interface && rv.NumMethod() == 0) &&
- !rt.Implements(unmarshalToml) && !rt.Implements(unmarshalText) {
- return MetaData{}, fmt.Errorf("toml: cannot decode to type %s", rt)
- }
-
- // TODO: parser should read from io.Reader? Or at the very least, make it
- // read from []byte rather than string
- data, err := ioutil.ReadAll(dec.r)
- if err != nil {
- return MetaData{}, err
- }
-
- p, err := parse(string(data))
- if err != nil {
- return MetaData{}, err
- }
-
- md := MetaData{
- mapping: p.mapping,
- keyInfo: p.keyInfo,
- keys: p.ordered,
- decoded: make(map[string]struct{}, len(p.ordered)),
- context: nil,
- data: data,
- }
- return md, md.unify(p.mapping, rv)
-}
-
-// PrimitiveDecode is just like the other Decode* functions, except it decodes a
-// TOML value that has already been parsed. Valid primitive values can *only* be
-// obtained from values filled by the decoder functions, including this method.
-// (i.e., v may contain more [Primitive] values.)
-//
-// Meta data for primitive values is included in the meta data returned by the
-// Decode* functions with one exception: keys returned by the Undecoded method
-// will only reflect keys that were decoded. Namely, any keys hidden behind a
-// Primitive will be considered undecoded. Executing this method will update the
-// undecoded keys in the meta data. (See the example.)
-func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error {
- md.context = primValue.context
- defer func() { md.context = nil }()
- return md.unify(primValue.undecoded, rvalue(v))
-}
-
-// unify performs a sort of type unification based on the structure of `rv`,
-// which is the client representation.
-//
-// Any type mismatch produces an error. Finding a type that we don't know
-// how to handle produces an unsupported type error.
-func (md *MetaData) unify(data interface{}, rv reflect.Value) error {
- // Special case. Look for a `Primitive` value.
- // TODO: #76 would make this superfluous after implemented.
- if rv.Type() == primitiveType {
- // Save the undecoded data and the key context into the primitive
- // value.
- context := make(Key, len(md.context))
- copy(context, md.context)
- rv.Set(reflect.ValueOf(Primitive{
- undecoded: data,
- context: context,
- }))
- return nil
- }
-
- rvi := rv.Interface()
- if v, ok := rvi.(Unmarshaler); ok {
- return v.UnmarshalTOML(data)
- }
- if v, ok := rvi.(encoding.TextUnmarshaler); ok {
- return md.unifyText(data, v)
- }
-
- // TODO:
- // The behavior here is incorrect whenever a Go type satisfies the
- // encoding.TextUnmarshaler interface but also corresponds to a TOML hash or
- // array. In particular, the unmarshaler should only be applied to primitive
- // TOML values. But at this point, it will be applied to all kinds of values
- // and produce an incorrect error whenever those values are hashes or arrays
- // (including arrays of tables).
-
- k := rv.Kind()
-
- if k >= reflect.Int && k <= reflect.Uint64 {
- return md.unifyInt(data, rv)
- }
- switch k {
- case reflect.Ptr:
- elem := reflect.New(rv.Type().Elem())
- err := md.unify(data, reflect.Indirect(elem))
- if err != nil {
- return err
- }
- rv.Set(elem)
- return nil
- case reflect.Struct:
- return md.unifyStruct(data, rv)
- case reflect.Map:
- return md.unifyMap(data, rv)
- case reflect.Array:
- return md.unifyArray(data, rv)
- case reflect.Slice:
- return md.unifySlice(data, rv)
- case reflect.String:
- return md.unifyString(data, rv)
- case reflect.Bool:
- return md.unifyBool(data, rv)
- case reflect.Interface:
- if rv.NumMethod() > 0 { /// Only empty interfaces are supported.
- return md.e("unsupported type %s", rv.Type())
- }
- return md.unifyAnything(data, rv)
- case reflect.Float32, reflect.Float64:
- return md.unifyFloat64(data, rv)
- }
- return md.e("unsupported type %s", rv.Kind())
-}
-
-func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error {
- tmap, ok := mapping.(map[string]interface{})
- if !ok {
- if mapping == nil {
- return nil
- }
- return md.e("type mismatch for %s: expected table but found %T",
- rv.Type().String(), mapping)
- }
-
- for key, datum := range tmap {
- var f *field
- fields := cachedTypeFields(rv.Type())
- for i := range fields {
- ff := &fields[i]
- if ff.name == key {
- f = ff
- break
- }
- if f == nil && strings.EqualFold(ff.name, key) {
- f = ff
- }
- }
- if f != nil {
- subv := rv
- for _, i := range f.index {
- subv = indirect(subv.Field(i))
- }
-
- if isUnifiable(subv) {
- md.decoded[md.context.add(key).String()] = struct{}{}
- md.context = append(md.context, key)
-
- err := md.unify(datum, subv)
- if err != nil {
- return err
- }
- md.context = md.context[0 : len(md.context)-1]
- } else if f.name != "" {
- return md.e("cannot write unexported field %s.%s", rv.Type().String(), f.name)
- }
- }
- }
- return nil
-}
-
-func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error {
- keyType := rv.Type().Key().Kind()
- if keyType != reflect.String && keyType != reflect.Interface {
- return fmt.Errorf("toml: cannot decode to a map with non-string key type (%s in %q)",
- keyType, rv.Type())
- }
-
- tmap, ok := mapping.(map[string]interface{})
- if !ok {
- if tmap == nil {
- return nil
- }
- return md.badtype("map", mapping)
- }
- if rv.IsNil() {
- rv.Set(reflect.MakeMap(rv.Type()))
- }
- for k, v := range tmap {
- md.decoded[md.context.add(k).String()] = struct{}{}
- md.context = append(md.context, k)
-
- rvval := reflect.Indirect(reflect.New(rv.Type().Elem()))
-
- err := md.unify(v, indirect(rvval))
- if err != nil {
- return err
- }
- md.context = md.context[0 : len(md.context)-1]
-
- rvkey := indirect(reflect.New(rv.Type().Key()))
-
- switch keyType {
- case reflect.Interface:
- rvkey.Set(reflect.ValueOf(k))
- case reflect.String:
- rvkey.SetString(k)
- }
-
- rv.SetMapIndex(rvkey, rvval)
- }
- return nil
-}
-
-func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error {
- datav := reflect.ValueOf(data)
- if datav.Kind() != reflect.Slice {
- if !datav.IsValid() {
- return nil
- }
- return md.badtype("slice", data)
- }
- if l := datav.Len(); l != rv.Len() {
- return md.e("expected array length %d; got TOML array of length %d", rv.Len(), l)
- }
- return md.unifySliceArray(datav, rv)
-}
-
-func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error {
- datav := reflect.ValueOf(data)
- if datav.Kind() != reflect.Slice {
- if !datav.IsValid() {
- return nil
- }
- return md.badtype("slice", data)
- }
- n := datav.Len()
- if rv.IsNil() || rv.Cap() < n {
- rv.Set(reflect.MakeSlice(rv.Type(), n, n))
- }
- rv.SetLen(n)
- return md.unifySliceArray(datav, rv)
-}
-
-func (md *MetaData) unifySliceArray(data, rv reflect.Value) error {
- l := data.Len()
- for i := 0; i < l; i++ {
- err := md.unify(data.Index(i).Interface(), indirect(rv.Index(i)))
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error {
- _, ok := rv.Interface().(json.Number)
- if ok {
- if i, ok := data.(int64); ok {
- rv.SetString(strconv.FormatInt(i, 10))
- } else if f, ok := data.(float64); ok {
- rv.SetString(strconv.FormatFloat(f, 'f', -1, 64))
- } else {
- return md.badtype("string", data)
- }
- return nil
- }
-
- if s, ok := data.(string); ok {
- rv.SetString(s)
- return nil
- }
- return md.badtype("string", data)
-}
-
-func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error {
- rvk := rv.Kind()
-
- if num, ok := data.(float64); ok {
- switch rvk {
- case reflect.Float32:
- if num < -math.MaxFloat32 || num > math.MaxFloat32 {
- return md.parseErr(errParseRange{i: num, size: rvk.String()})
- }
- fallthrough
- case reflect.Float64:
- rv.SetFloat(num)
- default:
- panic("bug")
- }
- return nil
- }
-
- if num, ok := data.(int64); ok {
- if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) ||
- (rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) {
- return md.parseErr(errParseRange{i: num, size: rvk.String()})
- }
- rv.SetFloat(float64(num))
- return nil
- }
-
- return md.badtype("float", data)
-}
-
-func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error {
- _, ok := rv.Interface().(time.Duration)
- if ok {
- // Parse as string duration, and fall back to regular integer parsing
- // (as nanosecond) if this is not a string.
- if s, ok := data.(string); ok {
- dur, err := time.ParseDuration(s)
- if err != nil {
- return md.parseErr(errParseDuration{s})
- }
- rv.SetInt(int64(dur))
- return nil
- }
- }
-
- num, ok := data.(int64)
- if !ok {
- return md.badtype("integer", data)
- }
-
- rvk := rv.Kind()
- switch {
- case rvk >= reflect.Int && rvk <= reflect.Int64:
- if (rvk == reflect.Int8 && (num < math.MinInt8 || num > math.MaxInt8)) ||
- (rvk == reflect.Int16 && (num < math.MinInt16 || num > math.MaxInt16)) ||
- (rvk == reflect.Int32 && (num < math.MinInt32 || num > math.MaxInt32)) {
- return md.parseErr(errParseRange{i: num, size: rvk.String()})
- }
- rv.SetInt(num)
- case rvk >= reflect.Uint && rvk <= reflect.Uint64:
- unum := uint64(num)
- if rvk == reflect.Uint8 && (num < 0 || unum > math.MaxUint8) ||
- rvk == reflect.Uint16 && (num < 0 || unum > math.MaxUint16) ||
- rvk == reflect.Uint32 && (num < 0 || unum > math.MaxUint32) {
- return md.parseErr(errParseRange{i: num, size: rvk.String()})
- }
- rv.SetUint(unum)
- default:
- panic("unreachable")
- }
- return nil
-}
-
-func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error {
- if b, ok := data.(bool); ok {
- rv.SetBool(b)
- return nil
- }
- return md.badtype("boolean", data)
-}
-
-func (md *MetaData) unifyAnything(data interface{}, rv reflect.Value) error {
- rv.Set(reflect.ValueOf(data))
- return nil
-}
-
-func (md *MetaData) unifyText(data interface{}, v encoding.TextUnmarshaler) error {
- var s string
- switch sdata := data.(type) {
- case Marshaler:
- text, err := sdata.MarshalTOML()
- if err != nil {
- return err
- }
- s = string(text)
- case encoding.TextMarshaler:
- text, err := sdata.MarshalText()
- if err != nil {
- return err
- }
- s = string(text)
- case fmt.Stringer:
- s = sdata.String()
- case string:
- s = sdata
- case bool:
- s = fmt.Sprintf("%v", sdata)
- case int64:
- s = fmt.Sprintf("%d", sdata)
- case float64:
- s = fmt.Sprintf("%f", sdata)
- default:
- return md.badtype("primitive (string-like)", data)
- }
- if err := v.UnmarshalText([]byte(s)); err != nil {
- return err
- }
- return nil
-}
-
-func (md *MetaData) badtype(dst string, data interface{}) error {
- return md.e("incompatible types: TOML value has type %T; destination has type %s", data, dst)
-}
-
-func (md *MetaData) parseErr(err error) error {
- k := md.context.String()
- return ParseError{
- LastKey: k,
- Position: md.keyInfo[k].pos,
- Line: md.keyInfo[k].pos.Line,
- err: err,
- input: string(md.data),
- }
-}
-
-func (md *MetaData) e(format string, args ...interface{}) error {
- f := "toml: "
- if len(md.context) > 0 {
- f = fmt.Sprintf("toml: (last key %q): ", md.context)
- p := md.keyInfo[md.context.String()].pos
- if p.Line > 0 {
- f = fmt.Sprintf("toml: line %d (last key %q): ", p.Line, md.context)
- }
- }
- return fmt.Errorf(f+format, args...)
-}
-
-// rvalue returns a reflect.Value of `v`. All pointers are resolved.
-func rvalue(v interface{}) reflect.Value {
- return indirect(reflect.ValueOf(v))
-}
-
-// indirect returns the value pointed to by a pointer.
-//
-// Pointers are followed until the value is not a pointer. New values are
-// allocated for each nil pointer.
-//
-// An exception to this rule is if the value satisfies an interface of interest
-// to us (like encoding.TextUnmarshaler).
-func indirect(v reflect.Value) reflect.Value {
- if v.Kind() != reflect.Ptr {
- if v.CanSet() {
- pv := v.Addr()
- pvi := pv.Interface()
- if _, ok := pvi.(encoding.TextUnmarshaler); ok {
- return pv
- }
- if _, ok := pvi.(Unmarshaler); ok {
- return pv
- }
- }
- return v
- }
- if v.IsNil() {
- v.Set(reflect.New(v.Type().Elem()))
- }
- return indirect(reflect.Indirect(v))
-}
-
-func isUnifiable(rv reflect.Value) bool {
- if rv.CanSet() {
- return true
- }
- rvi := rv.Interface()
- if _, ok := rvi.(encoding.TextUnmarshaler); ok {
- return true
- }
- if _, ok := rvi.(Unmarshaler); ok {
- return true
- }
- return false
-}
diff --git a/vendor/github.com/BurntSushi/toml/decode_go116.go b/vendor/github.com/BurntSushi/toml/decode_go116.go
deleted file mode 100644
index 086d0b6..0000000
--- a/vendor/github.com/BurntSushi/toml/decode_go116.go
+++ /dev/null
@@ -1,19 +0,0 @@
-//go:build go1.16
-// +build go1.16
-
-package toml
-
-import (
- "io/fs"
-)
-
-// DecodeFS reads the contents of a file from [fs.FS] and decodes it with
-// [Decode].
-func DecodeFS(fsys fs.FS, path string, v interface{}) (MetaData, error) {
- fp, err := fsys.Open(path)
- if err != nil {
- return MetaData{}, err
- }
- defer fp.Close()
- return NewDecoder(fp).Decode(v)
-}
diff --git a/vendor/github.com/BurntSushi/toml/deprecated.go b/vendor/github.com/BurntSushi/toml/deprecated.go
deleted file mode 100644
index b9e3097..0000000
--- a/vendor/github.com/BurntSushi/toml/deprecated.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package toml
-
-import (
- "encoding"
- "io"
-)
-
-// TextMarshaler is an alias for encoding.TextMarshaler.
-//
-// Deprecated: use encoding.TextMarshaler
-type TextMarshaler encoding.TextMarshaler
-
-// TextUnmarshaler is an alias for encoding.TextUnmarshaler.
-//
-// Deprecated: use encoding.TextUnmarshaler
-type TextUnmarshaler encoding.TextUnmarshaler
-
-// PrimitiveDecode is an alias for MetaData.PrimitiveDecode().
-//
-// Deprecated: use MetaData.PrimitiveDecode.
-func PrimitiveDecode(primValue Primitive, v interface{}) error {
- md := MetaData{decoded: make(map[string]struct{})}
- return md.unify(primValue.undecoded, rvalue(v))
-}
-
-// DecodeReader is an alias for NewDecoder(r).Decode(v).
-//
-// Deprecated: use NewDecoder(reader).Decode(&value).
-func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { return NewDecoder(r).Decode(v) }
diff --git a/vendor/github.com/BurntSushi/toml/doc.go b/vendor/github.com/BurntSushi/toml/doc.go
deleted file mode 100644
index 81a7c0f..0000000
--- a/vendor/github.com/BurntSushi/toml/doc.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// Package toml implements decoding and encoding of TOML files.
-//
-// This package supports TOML v1.0.0, as specified at https://toml.io
-//
-// There is also support for delaying decoding with the Primitive type, and
-// querying the set of keys in a TOML document with the MetaData type.
-//
-// The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator,
-// and can be used to verify if TOML document is valid. It can also be used to
-// print the type of each key.
-package toml
diff --git a/vendor/github.com/BurntSushi/toml/encode.go b/vendor/github.com/BurntSushi/toml/encode.go
deleted file mode 100644
index 9cd25d7..0000000
--- a/vendor/github.com/BurntSushi/toml/encode.go
+++ /dev/null
@@ -1,759 +0,0 @@
-package toml
-
-import (
- "bufio"
- "encoding"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "math"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "github.com/BurntSushi/toml/internal"
-)
-
-type tomlEncodeError struct{ error }
-
-var (
- errArrayNilElement = errors.New("toml: cannot encode array with nil element")
- errNonString = errors.New("toml: cannot encode a map with non-string key type")
- errNoKey = errors.New("toml: top-level values must be Go maps or structs")
- errAnything = errors.New("") // used in testing
-)
-
-var dblQuotedReplacer = strings.NewReplacer(
- "\"", "\\\"",
- "\\", "\\\\",
- "\x00", `\u0000`,
- "\x01", `\u0001`,
- "\x02", `\u0002`,
- "\x03", `\u0003`,
- "\x04", `\u0004`,
- "\x05", `\u0005`,
- "\x06", `\u0006`,
- "\x07", `\u0007`,
- "\b", `\b`,
- "\t", `\t`,
- "\n", `\n`,
- "\x0b", `\u000b`,
- "\f", `\f`,
- "\r", `\r`,
- "\x0e", `\u000e`,
- "\x0f", `\u000f`,
- "\x10", `\u0010`,
- "\x11", `\u0011`,
- "\x12", `\u0012`,
- "\x13", `\u0013`,
- "\x14", `\u0014`,
- "\x15", `\u0015`,
- "\x16", `\u0016`,
- "\x17", `\u0017`,
- "\x18", `\u0018`,
- "\x19", `\u0019`,
- "\x1a", `\u001a`,
- "\x1b", `\u001b`,
- "\x1c", `\u001c`,
- "\x1d", `\u001d`,
- "\x1e", `\u001e`,
- "\x1f", `\u001f`,
- "\x7f", `\u007f`,
-)
-
-var (
- marshalToml = reflect.TypeOf((*Marshaler)(nil)).Elem()
- marshalText = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
- timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
-)
-
-// Marshaler is the interface implemented by types that can marshal themselves
-// into valid TOML.
-type Marshaler interface {
- MarshalTOML() ([]byte, error)
-}
-
-// Encoder encodes a Go to a TOML document.
-//
-// The mapping between Go values and TOML values should be precisely the same as
-// for [Decode].
-//
-// time.Time is encoded as a RFC 3339 string, and time.Duration as its string
-// representation.
-//
-// The [Marshaler] and [encoding.TextMarshaler] interfaces are supported to
-// encoding the value as custom TOML.
-//
-// If you want to write arbitrary binary data then you will need to use
-// something like base64 since TOML does not have any binary types.
-//
-// When encoding TOML hashes (Go maps or structs), keys without any sub-hashes
-// are encoded first.
-//
-// Go maps will be sorted alphabetically by key for deterministic output.
-//
-// The toml struct tag can be used to provide the key name; if omitted the
-// struct field name will be used. If the "omitempty" option is present the
-// following value will be skipped:
-//
-// - arrays, slices, maps, and string with len of 0
-// - struct with all zero values
-// - bool false
-//
-// If omitzero is given all int and float types with a value of 0 will be
-// skipped.
-//
-// Encoding Go values without a corresponding TOML representation will return an
-// error. Examples of this includes maps with non-string keys, slices with nil
-// elements, embedded non-struct types, and nested slices containing maps or
-// structs. (e.g. [][]map[string]string is not allowed but []map[string]string
-// is okay, as is []map[string][]string).
-//
-// NOTE: only exported keys are encoded due to the use of reflection. Unexported
-// keys are silently discarded.
-type Encoder struct {
- // String to use for a single indentation level; default is two spaces.
- Indent string
-
- w *bufio.Writer
- hasWritten bool // written any output to w yet?
-}
-
-// NewEncoder create a new Encoder.
-func NewEncoder(w io.Writer) *Encoder {
- return &Encoder{
- w: bufio.NewWriter(w),
- Indent: " ",
- }
-}
-
-// Encode writes a TOML representation of the Go value to the [Encoder]'s writer.
-//
-// An error is returned if the value given cannot be encoded to a valid TOML
-// document.
-func (enc *Encoder) Encode(v interface{}) error {
- rv := eindirect(reflect.ValueOf(v))
- err := enc.safeEncode(Key([]string{}), rv)
- if err != nil {
- return err
- }
- return enc.w.Flush()
-}
-
-func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) {
- defer func() {
- if r := recover(); r != nil {
- if terr, ok := r.(tomlEncodeError); ok {
- err = terr.error
- return
- }
- panic(r)
- }
- }()
- enc.encode(key, rv)
- return nil
-}
-
-func (enc *Encoder) encode(key Key, rv reflect.Value) {
- // If we can marshal the type to text, then we use that. This prevents the
- // encoder for handling these types as generic structs (or whatever the
- // underlying type of a TextMarshaler is).
- switch {
- case isMarshaler(rv):
- enc.writeKeyValue(key, rv, false)
- return
- case rv.Type() == primitiveType: // TODO: #76 would make this superfluous after implemented.
- enc.encode(key, reflect.ValueOf(rv.Interface().(Primitive).undecoded))
- return
- }
-
- k := rv.Kind()
- switch k {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
- reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
- reflect.Uint64,
- reflect.Float32, reflect.Float64, reflect.String, reflect.Bool:
- enc.writeKeyValue(key, rv, false)
- case reflect.Array, reflect.Slice:
- if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) {
- enc.eArrayOfTables(key, rv)
- } else {
- enc.writeKeyValue(key, rv, false)
- }
- case reflect.Interface:
- if rv.IsNil() {
- return
- }
- enc.encode(key, rv.Elem())
- case reflect.Map:
- if rv.IsNil() {
- return
- }
- enc.eTable(key, rv)
- case reflect.Ptr:
- if rv.IsNil() {
- return
- }
- enc.encode(key, rv.Elem())
- case reflect.Struct:
- enc.eTable(key, rv)
- default:
- encPanic(fmt.Errorf("unsupported type for key '%s': %s", key, k))
- }
-}
-
-// eElement encodes any value that can be an array element.
-func (enc *Encoder) eElement(rv reflect.Value) {
- switch v := rv.Interface().(type) {
- case time.Time: // Using TextMarshaler adds extra quotes, which we don't want.
- format := time.RFC3339Nano
- switch v.Location() {
- case internal.LocalDatetime:
- format = "2006-01-02T15:04:05.999999999"
- case internal.LocalDate:
- format = "2006-01-02"
- case internal.LocalTime:
- format = "15:04:05.999999999"
- }
- switch v.Location() {
- default:
- enc.wf(v.Format(format))
- case internal.LocalDatetime, internal.LocalDate, internal.LocalTime:
- enc.wf(v.In(time.UTC).Format(format))
- }
- return
- case Marshaler:
- s, err := v.MarshalTOML()
- if err != nil {
- encPanic(err)
- }
- if s == nil {
- encPanic(errors.New("MarshalTOML returned nil and no error"))
- }
- enc.w.Write(s)
- return
- case encoding.TextMarshaler:
- s, err := v.MarshalText()
- if err != nil {
- encPanic(err)
- }
- if s == nil {
- encPanic(errors.New("MarshalText returned nil and no error"))
- }
- enc.writeQuoted(string(s))
- return
- case time.Duration:
- enc.writeQuoted(v.String())
- return
- case json.Number:
- n, _ := rv.Interface().(json.Number)
-
- if n == "" { /// Useful zero value.
- enc.w.WriteByte('0')
- return
- } else if v, err := n.Int64(); err == nil {
- enc.eElement(reflect.ValueOf(v))
- return
- } else if v, err := n.Float64(); err == nil {
- enc.eElement(reflect.ValueOf(v))
- return
- }
- encPanic(fmt.Errorf("unable to convert %q to int64 or float64", n))
- }
-
- switch rv.Kind() {
- case reflect.Ptr:
- enc.eElement(rv.Elem())
- return
- case reflect.String:
- enc.writeQuoted(rv.String())
- case reflect.Bool:
- enc.wf(strconv.FormatBool(rv.Bool()))
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- enc.wf(strconv.FormatInt(rv.Int(), 10))
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- enc.wf(strconv.FormatUint(rv.Uint(), 10))
- case reflect.Float32:
- f := rv.Float()
- if math.IsNaN(f) {
- enc.wf("nan")
- } else if math.IsInf(f, 0) {
- enc.wf("%cinf", map[bool]byte{true: '-', false: '+'}[math.Signbit(f)])
- } else {
- enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 32)))
- }
- case reflect.Float64:
- f := rv.Float()
- if math.IsNaN(f) {
- enc.wf("nan")
- } else if math.IsInf(f, 0) {
- enc.wf("%cinf", map[bool]byte{true: '-', false: '+'}[math.Signbit(f)])
- } else {
- enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 64)))
- }
- case reflect.Array, reflect.Slice:
- enc.eArrayOrSliceElement(rv)
- case reflect.Struct:
- enc.eStruct(nil, rv, true)
- case reflect.Map:
- enc.eMap(nil, rv, true)
- case reflect.Interface:
- enc.eElement(rv.Elem())
- default:
- encPanic(fmt.Errorf("unexpected type: %T", rv.Interface()))
- }
-}
-
-// By the TOML spec, all floats must have a decimal with at least one number on
-// either side.
-func floatAddDecimal(fstr string) string {
- if !strings.Contains(fstr, ".") {
- return fstr + ".0"
- }
- return fstr
-}
-
-func (enc *Encoder) writeQuoted(s string) {
- enc.wf("\"%s\"", dblQuotedReplacer.Replace(s))
-}
-
-func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) {
- length := rv.Len()
- enc.wf("[")
- for i := 0; i < length; i++ {
- elem := eindirect(rv.Index(i))
- enc.eElement(elem)
- if i != length-1 {
- enc.wf(", ")
- }
- }
- enc.wf("]")
-}
-
-func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) {
- if len(key) == 0 {
- encPanic(errNoKey)
- }
- for i := 0; i < rv.Len(); i++ {
- trv := eindirect(rv.Index(i))
- if isNil(trv) {
- continue
- }
- enc.newline()
- enc.wf("%s[[%s]]", enc.indentStr(key), key)
- enc.newline()
- enc.eMapOrStruct(key, trv, false)
- }
-}
-
-func (enc *Encoder) eTable(key Key, rv reflect.Value) {
- if len(key) == 1 {
- // Output an extra newline between top-level tables.
- // (The newline isn't written if nothing else has been written though.)
- enc.newline()
- }
- if len(key) > 0 {
- enc.wf("%s[%s]", enc.indentStr(key), key)
- enc.newline()
- }
- enc.eMapOrStruct(key, rv, false)
-}
-
-func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value, inline bool) {
- switch rv.Kind() {
- case reflect.Map:
- enc.eMap(key, rv, inline)
- case reflect.Struct:
- enc.eStruct(key, rv, inline)
- default:
- // Should never happen?
- panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String())
- }
-}
-
-func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) {
- rt := rv.Type()
- if rt.Key().Kind() != reflect.String {
- encPanic(errNonString)
- }
-
- // Sort keys so that we have deterministic output. And write keys directly
- // underneath this key first, before writing sub-structs or sub-maps.
- var mapKeysDirect, mapKeysSub []string
- for _, mapKey := range rv.MapKeys() {
- k := mapKey.String()
- if typeIsTable(tomlTypeOfGo(eindirect(rv.MapIndex(mapKey)))) {
- mapKeysSub = append(mapKeysSub, k)
- } else {
- mapKeysDirect = append(mapKeysDirect, k)
- }
- }
-
- var writeMapKeys = func(mapKeys []string, trailC bool) {
- sort.Strings(mapKeys)
- for i, mapKey := range mapKeys {
- val := eindirect(rv.MapIndex(reflect.ValueOf(mapKey)))
- if isNil(val) {
- continue
- }
-
- if inline {
- enc.writeKeyValue(Key{mapKey}, val, true)
- if trailC || i != len(mapKeys)-1 {
- enc.wf(", ")
- }
- } else {
- enc.encode(key.add(mapKey), val)
- }
- }
- }
-
- if inline {
- enc.wf("{")
- }
- writeMapKeys(mapKeysDirect, len(mapKeysSub) > 0)
- writeMapKeys(mapKeysSub, false)
- if inline {
- enc.wf("}")
- }
-}
-
-const is32Bit = (32 << (^uint(0) >> 63)) == 32
-
-func pointerTo(t reflect.Type) reflect.Type {
- if t.Kind() == reflect.Ptr {
- return pointerTo(t.Elem())
- }
- return t
-}
-
-func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
- // Write keys for fields directly under this key first, because if we write
- // a field that creates a new table then all keys under it will be in that
- // table (not the one we're writing here).
- //
- // Fields is a [][]int: for fieldsDirect this always has one entry (the
- // struct index). For fieldsSub it contains two entries: the parent field
- // index from tv, and the field indexes for the fields of the sub.
- var (
- rt = rv.Type()
- fieldsDirect, fieldsSub [][]int
- addFields func(rt reflect.Type, rv reflect.Value, start []int)
- )
- addFields = func(rt reflect.Type, rv reflect.Value, start []int) {
- for i := 0; i < rt.NumField(); i++ {
- f := rt.Field(i)
- isEmbed := f.Anonymous && pointerTo(f.Type).Kind() == reflect.Struct
- if f.PkgPath != "" && !isEmbed { /// Skip unexported fields.
- continue
- }
- opts := getOptions(f.Tag)
- if opts.skip {
- continue
- }
-
- frv := eindirect(rv.Field(i))
-
- if is32Bit {
- // Copy so it works correct on 32bit archs; not clear why this
- // is needed. See #314, and https://www.reddit.com/r/golang/comments/pnx8v4
- // This also works fine on 64bit, but 32bit archs are somewhat
- // rare and this is a wee bit faster.
- copyStart := make([]int, len(start))
- copy(copyStart, start)
- start = copyStart
- }
-
- // Treat anonymous struct fields with tag names as though they are
- // not anonymous, like encoding/json does.
- //
- // Non-struct anonymous fields use the normal encoding logic.
- if isEmbed {
- if getOptions(f.Tag).name == "" && frv.Kind() == reflect.Struct {
- addFields(frv.Type(), frv, append(start, f.Index...))
- continue
- }
- }
-
- if typeIsTable(tomlTypeOfGo(frv)) {
- fieldsSub = append(fieldsSub, append(start, f.Index...))
- } else {
- fieldsDirect = append(fieldsDirect, append(start, f.Index...))
- }
- }
- }
- addFields(rt, rv, nil)
-
- writeFields := func(fields [][]int) {
- for _, fieldIndex := range fields {
- fieldType := rt.FieldByIndex(fieldIndex)
- fieldVal := rv.FieldByIndex(fieldIndex)
-
- opts := getOptions(fieldType.Tag)
- if opts.skip {
- continue
- }
- if opts.omitempty && isEmpty(fieldVal) {
- continue
- }
-
- fieldVal = eindirect(fieldVal)
-
- if isNil(fieldVal) { /// Don't write anything for nil fields.
- continue
- }
-
- keyName := fieldType.Name
- if opts.name != "" {
- keyName = opts.name
- }
-
- if opts.omitzero && isZero(fieldVal) {
- continue
- }
-
- if inline {
- enc.writeKeyValue(Key{keyName}, fieldVal, true)
- if fieldIndex[0] != len(fields)-1 {
- enc.wf(", ")
- }
- } else {
- enc.encode(key.add(keyName), fieldVal)
- }
- }
- }
-
- if inline {
- enc.wf("{")
- }
- writeFields(fieldsDirect)
- writeFields(fieldsSub)
- if inline {
- enc.wf("}")
- }
-}
-
-// tomlTypeOfGo returns the TOML type name of the Go value's type.
-//
-// It is used to determine whether the types of array elements are mixed (which
-// is forbidden). If the Go value is nil, then it is illegal for it to be an
-// array element, and valueIsNil is returned as true.
-//
-// The type may be `nil`, which means no concrete TOML type could be found.
-func tomlTypeOfGo(rv reflect.Value) tomlType {
- if isNil(rv) || !rv.IsValid() {
- return nil
- }
-
- if rv.Kind() == reflect.Struct {
- if rv.Type() == timeType {
- return tomlDatetime
- }
- if isMarshaler(rv) {
- return tomlString
- }
- return tomlHash
- }
-
- if isMarshaler(rv) {
- return tomlString
- }
-
- switch rv.Kind() {
- case reflect.Bool:
- return tomlBool
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
- reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
- reflect.Uint64:
- return tomlInteger
- case reflect.Float32, reflect.Float64:
- return tomlFloat
- case reflect.Array, reflect.Slice:
- if isTableArray(rv) {
- return tomlArrayHash
- }
- return tomlArray
- case reflect.Ptr, reflect.Interface:
- return tomlTypeOfGo(rv.Elem())
- case reflect.String:
- return tomlString
- case reflect.Map:
- return tomlHash
- default:
- encPanic(errors.New("unsupported type: " + rv.Kind().String()))
- panic("unreachable")
- }
-}
-
-func isMarshaler(rv reflect.Value) bool {
- return rv.Type().Implements(marshalText) || rv.Type().Implements(marshalToml)
-}
-
-// isTableArray reports if all entries in the array or slice are a table.
-func isTableArray(arr reflect.Value) bool {
- if isNil(arr) || !arr.IsValid() || arr.Len() == 0 {
- return false
- }
-
- ret := true
- for i := 0; i < arr.Len(); i++ {
- tt := tomlTypeOfGo(eindirect(arr.Index(i)))
- // Don't allow nil.
- if tt == nil {
- encPanic(errArrayNilElement)
- }
-
- if ret && !typeEqual(tomlHash, tt) {
- ret = false
- }
- }
- return ret
-}
-
-type tagOptions struct {
- skip bool // "-"
- name string
- omitempty bool
- omitzero bool
-}
-
-func getOptions(tag reflect.StructTag) tagOptions {
- t := tag.Get("toml")
- if t == "-" {
- return tagOptions{skip: true}
- }
- var opts tagOptions
- parts := strings.Split(t, ",")
- opts.name = parts[0]
- for _, s := range parts[1:] {
- switch s {
- case "omitempty":
- opts.omitempty = true
- case "omitzero":
- opts.omitzero = true
- }
- }
- return opts
-}
-
-func isZero(rv reflect.Value) bool {
- switch rv.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return rv.Int() == 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return rv.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return rv.Float() == 0.0
- }
- return false
-}
-
-func isEmpty(rv reflect.Value) bool {
- switch rv.Kind() {
- case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
- return rv.Len() == 0
- case reflect.Struct:
- if rv.Type().Comparable() {
- return reflect.Zero(rv.Type()).Interface() == rv.Interface()
- }
- // Need to also check if all the fields are empty, otherwise something
- // like this with uncomparable types will always return true:
- //
- // type a struct{ field b }
- // type b struct{ s []string }
- // s := a{field: b{s: []string{"AAA"}}}
- for i := 0; i < rv.NumField(); i++ {
- if !isEmpty(rv.Field(i)) {
- return false
- }
- }
- return true
- case reflect.Bool:
- return !rv.Bool()
- case reflect.Ptr:
- return rv.IsNil()
- }
- return false
-}
-
-func (enc *Encoder) newline() {
- if enc.hasWritten {
- enc.wf("\n")
- }
-}
-
-// Write a key/value pair:
-//
-// key = <any value>
-//
-// This is also used for "k = v" in inline tables; so something like this will
-// be written in three calls:
-//
-// ┌───────────────────┐
-// │ ┌───┐ ┌────┐│
-// v v v v vv
-// key = {k = 1, k2 = 2}
-func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) {
- /// Marshaler used on top-level document; call eElement() to just call
- /// Marshal{TOML,Text}.
- if len(key) == 0 {
- enc.eElement(val)
- return
- }
- enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1))
- enc.eElement(val)
- if !inline {
- enc.newline()
- }
-}
-
-func (enc *Encoder) wf(format string, v ...interface{}) {
- _, err := fmt.Fprintf(enc.w, format, v...)
- if err != nil {
- encPanic(err)
- }
- enc.hasWritten = true
-}
-
-func (enc *Encoder) indentStr(key Key) string {
- return strings.Repeat(enc.Indent, len(key)-1)
-}
-
-func encPanic(err error) {
- panic(tomlEncodeError{err})
-}
-
-// Resolve any level of pointers to the actual value (e.g. **string → string).
-func eindirect(v reflect.Value) reflect.Value {
- if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface {
- if isMarshaler(v) {
- return v
- }
- if v.CanAddr() { /// Special case for marshalers; see #358.
- if pv := v.Addr(); isMarshaler(pv) {
- return pv
- }
- }
- return v
- }
-
- if v.IsNil() {
- return v
- }
-
- return eindirect(v.Elem())
-}
-
-func isNil(rv reflect.Value) bool {
- switch rv.Kind() {
- case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
- return rv.IsNil()
- default:
- return false
- }
-}
diff --git a/vendor/github.com/BurntSushi/toml/error.go b/vendor/github.com/BurntSushi/toml/error.go
deleted file mode 100644
index efd6886..0000000
--- a/vendor/github.com/BurntSushi/toml/error.go
+++ /dev/null
@@ -1,279 +0,0 @@
-package toml
-
-import (
- "fmt"
- "strings"
-)
-
-// ParseError is returned when there is an error parsing the TOML syntax such as
-// invalid syntax, duplicate keys, etc.
-//
-// In addition to the error message itself, you can also print detailed location
-// information with context by using [ErrorWithPosition]:
-//
-// toml: error: Key 'fruit' was already created and cannot be used as an array.
-//
-// At line 4, column 2-7:
-//
-// 2 | fruit = []
-// 3 |
-// 4 | [[fruit]] # Not allowed
-// ^^^^^
-//
-// [ErrorWithUsage] can be used to print the above with some more detailed usage
-// guidance:
-//
-// toml: error: newlines not allowed within inline tables
-//
-// At line 1, column 18:
-//
-// 1 | x = [{ key = 42 #
-// ^
-//
-// Error help:
-//
-// Inline tables must always be on a single line:
-//
-// table = {key = 42, second = 43}
-//
-// It is invalid to split them over multiple lines like so:
-//
-// # INVALID
-// table = {
-// key = 42,
-// second = 43
-// }
-//
-// Use regular for this:
-//
-// [table]
-// key = 42
-// second = 43
-type ParseError struct {
- Message string // Short technical message.
- Usage string // Longer message with usage guidance; may be blank.
- Position Position // Position of the error
- LastKey string // Last parsed key, may be blank.
-
- // Line the error occurred.
- //
- // Deprecated: use [Position].
- Line int
-
- err error
- input string
-}
-
-// Position of an error.
-type Position struct {
- Line int // Line number, starting at 1.
- Start int // Start of error, as byte offset starting at 0.
- Len int // Lenght in bytes.
-}
-
-func (pe ParseError) Error() string {
- msg := pe.Message
- if msg == "" { // Error from errorf()
- msg = pe.err.Error()
- }
-
- if pe.LastKey == "" {
- return fmt.Sprintf("toml: line %d: %s", pe.Position.Line, msg)
- }
- return fmt.Sprintf("toml: line %d (last key %q): %s",
- pe.Position.Line, pe.LastKey, msg)
-}
-
-// ErrorWithPosition returns the error with detailed location context.
-//
-// See the documentation on [ParseError].
-func (pe ParseError) ErrorWithPosition() string {
- if pe.input == "" { // Should never happen, but just in case.
- return pe.Error()
- }
-
- var (
- lines = strings.Split(pe.input, "\n")
- col = pe.column(lines)
- b = new(strings.Builder)
- )
-
- msg := pe.Message
- if msg == "" {
- msg = pe.err.Error()
- }
-
- // TODO: don't show control characters as literals? This may not show up
- // well everywhere.
-
- if pe.Position.Len == 1 {
- fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d:\n\n",
- msg, pe.Position.Line, col+1)
- } else {
- fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d-%d:\n\n",
- msg, pe.Position.Line, col, col+pe.Position.Len)
- }
- if pe.Position.Line > 2 {
- fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, lines[pe.Position.Line-3])
- }
- if pe.Position.Line > 1 {
- fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, lines[pe.Position.Line-2])
- }
- fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, lines[pe.Position.Line-1])
- fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", col), strings.Repeat("^", pe.Position.Len))
- return b.String()
-}
-
-// ErrorWithUsage returns the error with detailed location context and usage
-// guidance.
-//
-// See the documentation on [ParseError].
-func (pe ParseError) ErrorWithUsage() string {
- m := pe.ErrorWithPosition()
- if u, ok := pe.err.(interface{ Usage() string }); ok && u.Usage() != "" {
- lines := strings.Split(strings.TrimSpace(u.Usage()), "\n")
- for i := range lines {
- if lines[i] != "" {
- lines[i] = " " + lines[i]
- }
- }
- return m + "Error help:\n\n" + strings.Join(lines, "\n") + "\n"
- }
- return m
-}
-
-func (pe ParseError) column(lines []string) int {
- var pos, col int
- for i := range lines {
- ll := len(lines[i]) + 1 // +1 for the removed newline
- if pos+ll >= pe.Position.Start {
- col = pe.Position.Start - pos
- if col < 0 { // Should never happen, but just in case.
- col = 0
- }
- break
- }
- pos += ll
- }
-
- return col
-}
-
-type (
- errLexControl struct{ r rune }
- errLexEscape struct{ r rune }
- errLexUTF8 struct{ b byte }
- errLexInvalidNum struct{ v string }
- errLexInvalidDate struct{ v string }
- errLexInlineTableNL struct{}
- errLexStringNL struct{}
- errParseRange struct {
- i interface{} // int or float
- size string // "int64", "uint16", etc.
- }
- errParseDuration struct{ d string }
-)
-
-func (e errLexControl) Error() string {
- return fmt.Sprintf("TOML files cannot contain control characters: '0x%02x'", e.r)
-}
-func (e errLexControl) Usage() string { return "" }
-
-func (e errLexEscape) Error() string { return fmt.Sprintf(`invalid escape in string '\%c'`, e.r) }
-func (e errLexEscape) Usage() string { return usageEscape }
-func (e errLexUTF8) Error() string { return fmt.Sprintf("invalid UTF-8 byte: 0x%02x", e.b) }
-func (e errLexUTF8) Usage() string { return "" }
-func (e errLexInvalidNum) Error() string { return fmt.Sprintf("invalid number: %q", e.v) }
-func (e errLexInvalidNum) Usage() string { return "" }
-func (e errLexInvalidDate) Error() string { return fmt.Sprintf("invalid date: %q", e.v) }
-func (e errLexInvalidDate) Usage() string { return "" }
-func (e errLexInlineTableNL) Error() string { return "newlines not allowed within inline tables" }
-func (e errLexInlineTableNL) Usage() string { return usageInlineNewline }
-func (e errLexStringNL) Error() string { return "strings cannot contain newlines" }
-func (e errLexStringNL) Usage() string { return usageStringNewline }
-func (e errParseRange) Error() string { return fmt.Sprintf("%v is out of range for %s", e.i, e.size) }
-func (e errParseRange) Usage() string { return usageIntOverflow }
-func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) }
-func (e errParseDuration) Usage() string { return usageDuration }
-
-const usageEscape = `
-A '\' inside a "-delimited string is interpreted as an escape character.
-
-The following escape sequences are supported:
-\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX
-
-To prevent a '\' from being recognized as an escape character, use either:
-
-- a ' or '''-delimited string; escape characters aren't processed in them; or
-- write two backslashes to get a single backslash: '\\'.
-
-If you're trying to add a Windows path (e.g. "C:\Users\martin") then using '/'
-instead of '\' will usually also work: "C:/Users/martin".
-`
-
-const usageInlineNewline = `
-Inline tables must always be on a single line:
-
- table = {key = 42, second = 43}
-
-It is invalid to split them over multiple lines like so:
-
- # INVALID
- table = {
- key = 42,
- second = 43
- }
-
-Use regular for this:
-
- [table]
- key = 42
- second = 43
-`
-
-const usageStringNewline = `
-Strings must always be on a single line, and cannot span more than one line:
-
- # INVALID
- string = "Hello,
- world!"
-
-Instead use """ or ''' to split strings over multiple lines:
-
- string = """Hello,
- world!"""
-`
-
-const usageIntOverflow = `
-This number is too large; this may be an error in the TOML, but it can also be a
-bug in the program that uses too small of an integer.
-
-The maximum and minimum values are:
-
- size │ lowest │ highest
- ───────┼────────────────┼──────────
- int8 │ -128 │ 127
- int16 │ -32,768 │ 32,767
- int32 │ -2,147,483,648 │ 2,147,483,647
- int64 │ -9.2 × 10¹⁷ │ 9.2 × 10¹⁷
- uint8 │ 0 │ 255
- uint16 │ 0 │ 65535
- uint32 │ 0 │ 4294967295
- uint64 │ 0 │ 1.8 × 10¹⁸
-
-int refers to int32 on 32-bit systems and int64 on 64-bit systems.
-`
-
-const usageDuration = `
-A duration must be as "number<unit>", without any spaces. Valid units are:
-
- ns nanoseconds (billionth of a second)
- us, µs microseconds (millionth of a second)
- ms milliseconds (thousands of a second)
- s seconds
- m minutes
- h hours
-
-You can combine multiple units; for example "5m10s" for 5 minutes and 10
-seconds.
-`
diff --git a/vendor/github.com/BurntSushi/toml/internal/tz.go b/vendor/github.com/BurntSushi/toml/internal/tz.go
deleted file mode 100644
index 022f15b..0000000
--- a/vendor/github.com/BurntSushi/toml/internal/tz.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package internal
-
-import "time"
-
-// Timezones used for local datetime, date, and time TOML types.
-//
-// The exact way times and dates without a timezone should be interpreted is not
-// well-defined in the TOML specification and left to the implementation. These
-// defaults to current local timezone offset of the computer, but this can be
-// changed by changing these variables before decoding.
-//
-// TODO:
-// Ideally we'd like to offer people the ability to configure the used timezone
-// by setting Decoder.Timezone and Encoder.Timezone; however, this is a bit
-// tricky: the reason we use three different variables for this is to support
-// round-tripping – without these specific TZ names we wouldn't know which
-// format to use.
-//
-// There isn't a good way to encode this right now though, and passing this sort
-// of information also ties in to various related issues such as string format
-// encoding, encoding of comments, etc.
-//
-// So, for the time being, just put this in internal until we can write a good
-// comprehensive API for doing all of this.
-//
-// The reason they're exported is because they're referred from in e.g.
-// internal/tag.
-//
-// Note that this behaviour is valid according to the TOML spec as the exact
-// behaviour is left up to implementations.
-var (
- localOffset = func() int { _, o := time.Now().Zone(); return o }()
- LocalDatetime = time.FixedZone("datetime-local", localOffset)
- LocalDate = time.FixedZone("date-local", localOffset)
- LocalTime = time.FixedZone("time-local", localOffset)
-)
diff --git a/vendor/github.com/BurntSushi/toml/lex.go b/vendor/github.com/BurntSushi/toml/lex.go
deleted file mode 100644
index 3545a6a..0000000
--- a/vendor/github.com/BurntSushi/toml/lex.go
+++ /dev/null
@@ -1,1283 +0,0 @@
-package toml
-
-import (
- "fmt"
- "reflect"
- "runtime"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-type itemType int
-
-const (
- itemError itemType = iota
- itemNIL // used in the parser to indicate no type
- itemEOF
- itemText
- itemString
- itemRawString
- itemMultilineString
- itemRawMultilineString
- itemBool
- itemInteger
- itemFloat
- itemDatetime
- itemArray // the start of an array
- itemArrayEnd
- itemTableStart
- itemTableEnd
- itemArrayTableStart
- itemArrayTableEnd
- itemKeyStart
- itemKeyEnd
- itemCommentStart
- itemInlineTableStart
- itemInlineTableEnd
-)
-
-const eof = 0
-
-type stateFn func(lx *lexer) stateFn
-
-func (p Position) String() string {
- return fmt.Sprintf("at line %d; start %d; length %d", p.Line, p.Start, p.Len)
-}
-
-type lexer struct {
- input string
- start int
- pos int
- line int
- state stateFn
- items chan item
- tomlNext bool
-
- // Allow for backing up up to 4 runes. This is necessary because TOML
- // contains 3-rune tokens (""" and ''').
- prevWidths [4]int
- nprev int // how many of prevWidths are in use
- atEOF bool // If we emit an eof, we can still back up, but it is not OK to call next again.
-
- // A stack of state functions used to maintain context.
- //
- // The idea is to reuse parts of the state machine in various places. For
- // example, values can appear at the top level or within arbitrarily nested
- // arrays. The last state on the stack is used after a value has been lexed.
- // Similarly for comments.
- stack []stateFn
-}
-
-type item struct {
- typ itemType
- val string
- err error
- pos Position
-}
-
-func (lx *lexer) nextItem() item {
- for {
- select {
- case item := <-lx.items:
- return item
- default:
- lx.state = lx.state(lx)
- //fmt.Printf(" STATE %-24s current: %-10s stack: %s\n", lx.state, lx.current(), lx.stack)
- }
- }
-}
-
-func lex(input string, tomlNext bool) *lexer {
- lx := &lexer{
- input: input,
- state: lexTop,
- items: make(chan item, 10),
- stack: make([]stateFn, 0, 10),
- line: 1,
- tomlNext: tomlNext,
- }
- return lx
-}
-
-func (lx *lexer) push(state stateFn) {
- lx.stack = append(lx.stack, state)
-}
-
-func (lx *lexer) pop() stateFn {
- if len(lx.stack) == 0 {
- return lx.errorf("BUG in lexer: no states to pop")
- }
- last := lx.stack[len(lx.stack)-1]
- lx.stack = lx.stack[0 : len(lx.stack)-1]
- return last
-}
-
-func (lx *lexer) current() string {
- return lx.input[lx.start:lx.pos]
-}
-
-func (lx lexer) getPos() Position {
- p := Position{
- Line: lx.line,
- Start: lx.start,
- Len: lx.pos - lx.start,
- }
- if p.Len <= 0 {
- p.Len = 1
- }
- return p
-}
-
-func (lx *lexer) emit(typ itemType) {
- // Needed for multiline strings ending with an incomplete UTF-8 sequence.
- if lx.start > lx.pos {
- lx.error(errLexUTF8{lx.input[lx.pos]})
- return
- }
- lx.items <- item{typ: typ, pos: lx.getPos(), val: lx.current()}
- lx.start = lx.pos
-}
-
-func (lx *lexer) emitTrim(typ itemType) {
- lx.items <- item{typ: typ, pos: lx.getPos(), val: strings.TrimSpace(lx.current())}
- lx.start = lx.pos
-}
-
-func (lx *lexer) next() (r rune) {
- if lx.atEOF {
- panic("BUG in lexer: next called after EOF")
- }
- if lx.pos >= len(lx.input) {
- lx.atEOF = true
- return eof
- }
-
- if lx.input[lx.pos] == '\n' {
- lx.line++
- }
- lx.prevWidths[3] = lx.prevWidths[2]
- lx.prevWidths[2] = lx.prevWidths[1]
- lx.prevWidths[1] = lx.prevWidths[0]
- if lx.nprev < 4 {
- lx.nprev++
- }
-
- r, w := utf8.DecodeRuneInString(lx.input[lx.pos:])
- if r == utf8.RuneError {
- lx.error(errLexUTF8{lx.input[lx.pos]})
- return utf8.RuneError
- }
-
- // Note: don't use peek() here, as this calls next().
- if isControl(r) || (r == '\r' && (len(lx.input)-1 == lx.pos || lx.input[lx.pos+1] != '\n')) {
- lx.errorControlChar(r)
- return utf8.RuneError
- }
-
- lx.prevWidths[0] = w
- lx.pos += w
- return r
-}
-
-// ignore skips over the pending input before this point.
-func (lx *lexer) ignore() {
- lx.start = lx.pos
-}
-
-// backup steps back one rune. Can be called 4 times between calls to next.
-func (lx *lexer) backup() {
- if lx.atEOF {
- lx.atEOF = false
- return
- }
- if lx.nprev < 1 {
- panic("BUG in lexer: backed up too far")
- }
- w := lx.prevWidths[0]
- lx.prevWidths[0] = lx.prevWidths[1]
- lx.prevWidths[1] = lx.prevWidths[2]
- lx.prevWidths[2] = lx.prevWidths[3]
- lx.nprev--
-
- lx.pos -= w
- if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' {
- lx.line--
- }
-}
-
-// accept consumes the next rune if it's equal to `valid`.
-func (lx *lexer) accept(valid rune) bool {
- if lx.next() == valid {
- return true
- }
- lx.backup()
- return false
-}
-
-// peek returns but does not consume the next rune in the input.
-func (lx *lexer) peek() rune {
- r := lx.next()
- lx.backup()
- return r
-}
-
-// skip ignores all input that matches the given predicate.
-func (lx *lexer) skip(pred func(rune) bool) {
- for {
- r := lx.next()
- if pred(r) {
- continue
- }
- lx.backup()
- lx.ignore()
- return
- }
-}
-
-// error stops all lexing by emitting an error and returning `nil`.
-//
-// Note that any value that is a character is escaped if it's a special
-// character (newlines, tabs, etc.).
-func (lx *lexer) error(err error) stateFn {
- if lx.atEOF {
- return lx.errorPrevLine(err)
- }
- lx.items <- item{typ: itemError, pos: lx.getPos(), err: err}
- return nil
-}
-
-// errorfPrevline is like error(), but sets the position to the last column of
-// the previous line.
-//
-// This is so that unexpected EOF or NL errors don't show on a new blank line.
-func (lx *lexer) errorPrevLine(err error) stateFn {
- pos := lx.getPos()
- pos.Line--
- pos.Len = 1
- pos.Start = lx.pos - 1
- lx.items <- item{typ: itemError, pos: pos, err: err}
- return nil
-}
-
-// errorPos is like error(), but allows explicitly setting the position.
-func (lx *lexer) errorPos(start, length int, err error) stateFn {
- pos := lx.getPos()
- pos.Start = start
- pos.Len = length
- lx.items <- item{typ: itemError, pos: pos, err: err}
- return nil
-}
-
-// errorf is like error, and creates a new error.
-func (lx *lexer) errorf(format string, values ...interface{}) stateFn {
- if lx.atEOF {
- pos := lx.getPos()
- pos.Line--
- pos.Len = 1
- pos.Start = lx.pos - 1
- lx.items <- item{typ: itemError, pos: pos, err: fmt.Errorf(format, values...)}
- return nil
- }
- lx.items <- item{typ: itemError, pos: lx.getPos(), err: fmt.Errorf(format, values...)}
- return nil
-}
-
-func (lx *lexer) errorControlChar(cc rune) stateFn {
- return lx.errorPos(lx.pos-1, 1, errLexControl{cc})
-}
-
-// lexTop consumes elements at the top level of TOML data.
-func lexTop(lx *lexer) stateFn {
- r := lx.next()
- if isWhitespace(r) || isNL(r) {
- return lexSkip(lx, lexTop)
- }
- switch r {
- case '#':
- lx.push(lexTop)
- return lexCommentStart
- case '[':
- return lexTableStart
- case eof:
- if lx.pos > lx.start {
- return lx.errorf("unexpected EOF")
- }
- lx.emit(itemEOF)
- return nil
- }
-
- // At this point, the only valid item can be a key, so we back up
- // and let the key lexer do the rest.
- lx.backup()
- lx.push(lexTopEnd)
- return lexKeyStart
-}
-
-// lexTopEnd is entered whenever a top-level item has been consumed. (A value
-// or a table.) It must see only whitespace, and will turn back to lexTop
-// upon a newline. If it sees EOF, it will quit the lexer successfully.
-func lexTopEnd(lx *lexer) stateFn {
- r := lx.next()
- switch {
- case r == '#':
- // a comment will read to a newline for us.
- lx.push(lexTop)
- return lexCommentStart
- case isWhitespace(r):
- return lexTopEnd
- case isNL(r):
- lx.ignore()
- return lexTop
- case r == eof:
- lx.emit(itemEOF)
- return nil
- }
- return lx.errorf(
- "expected a top-level item to end with a newline, comment, or EOF, but got %q instead",
- r)
-}
-
-// lexTable lexes the beginning of a table. Namely, it makes sure that
-// it starts with a character other than '.' and ']'.
-// It assumes that '[' has already been consumed.
-// It also handles the case that this is an item in an array of tables.
-// e.g., '[[name]]'.
-func lexTableStart(lx *lexer) stateFn {
- if lx.peek() == '[' {
- lx.next()
- lx.emit(itemArrayTableStart)
- lx.push(lexArrayTableEnd)
- } else {
- lx.emit(itemTableStart)
- lx.push(lexTableEnd)
- }
- return lexTableNameStart
-}
-
-func lexTableEnd(lx *lexer) stateFn {
- lx.emit(itemTableEnd)
- return lexTopEnd
-}
-
-func lexArrayTableEnd(lx *lexer) stateFn {
- if r := lx.next(); r != ']' {
- return lx.errorf("expected end of table array name delimiter ']', but got %q instead", r)
- }
- lx.emit(itemArrayTableEnd)
- return lexTopEnd
-}
-
-func lexTableNameStart(lx *lexer) stateFn {
- lx.skip(isWhitespace)
- switch r := lx.peek(); {
- case r == ']' || r == eof:
- return lx.errorf("unexpected end of table name (table names cannot be empty)")
- case r == '.':
- return lx.errorf("unexpected table separator (table names cannot be empty)")
- case r == '"' || r == '\'':
- lx.ignore()
- lx.push(lexTableNameEnd)
- return lexQuotedName
- default:
- lx.push(lexTableNameEnd)
- return lexBareName
- }
-}
-
-// lexTableNameEnd reads the end of a piece of a table name, optionally
-// consuming whitespace.
-func lexTableNameEnd(lx *lexer) stateFn {
- lx.skip(isWhitespace)
- switch r := lx.next(); {
- case isWhitespace(r):
- return lexTableNameEnd
- case r == '.':
- lx.ignore()
- return lexTableNameStart
- case r == ']':
- return lx.pop()
- default:
- return lx.errorf("expected '.' or ']' to end table name, but got %q instead", r)
- }
-}
-
-// lexBareName lexes one part of a key or table.
-//
-// It assumes that at least one valid character for the table has already been
-// read.
-//
-// Lexes only one part, e.g. only 'a' inside 'a.b'.
-func lexBareName(lx *lexer) stateFn {
- r := lx.next()
- if isBareKeyChar(r, lx.tomlNext) {
- return lexBareName
- }
- lx.backup()
- lx.emit(itemText)
- return lx.pop()
-}
-
-// lexBareName lexes one part of a key or table.
-//
-// It assumes that at least one valid character for the table has already been
-// read.
-//
-// Lexes only one part, e.g. only '"a"' inside '"a".b'.
-func lexQuotedName(lx *lexer) stateFn {
- r := lx.next()
- switch {
- case isWhitespace(r):
- return lexSkip(lx, lexValue)
- case r == '"':
- lx.ignore() // ignore the '"'
- return lexString
- case r == '\'':
- lx.ignore() // ignore the "'"
- return lexRawString
- case r == eof:
- return lx.errorf("unexpected EOF; expected value")
- default:
- return lx.errorf("expected value but found %q instead", r)
- }
-}
-
-// lexKeyStart consumes all key parts until a '='.
-func lexKeyStart(lx *lexer) stateFn {
- lx.skip(isWhitespace)
- switch r := lx.peek(); {
- case r == '=' || r == eof:
- return lx.errorf("unexpected '=': key name appears blank")
- case r == '.':
- return lx.errorf("unexpected '.': keys cannot start with a '.'")
- case r == '"' || r == '\'':
- lx.ignore()
- fallthrough
- default: // Bare key
- lx.emit(itemKeyStart)
- return lexKeyNameStart
- }
-}
-
-func lexKeyNameStart(lx *lexer) stateFn {
- lx.skip(isWhitespace)
- switch r := lx.peek(); {
- case r == '=' || r == eof:
- return lx.errorf("unexpected '='")
- case r == '.':
- return lx.errorf("unexpected '.'")
- case r == '"' || r == '\'':
- lx.ignore()
- lx.push(lexKeyEnd)
- return lexQuotedName
- default:
- lx.push(lexKeyEnd)
- return lexBareName
- }
-}
-
-// lexKeyEnd consumes the end of a key and trims whitespace (up to the key
-// separator).
-func lexKeyEnd(lx *lexer) stateFn {
- lx.skip(isWhitespace)
- switch r := lx.next(); {
- case isWhitespace(r):
- return lexSkip(lx, lexKeyEnd)
- case r == eof:
- return lx.errorf("unexpected EOF; expected key separator '='")
- case r == '.':
- lx.ignore()
- return lexKeyNameStart
- case r == '=':
- lx.emit(itemKeyEnd)
- return lexSkip(lx, lexValue)
- default:
- return lx.errorf("expected '.' or '=', but got %q instead", r)
- }
-}
-
-// lexValue starts the consumption of a value anywhere a value is expected.
-// lexValue will ignore whitespace.
-// After a value is lexed, the last state on the next is popped and returned.
-func lexValue(lx *lexer) stateFn {
- // We allow whitespace to precede a value, but NOT newlines.
- // In array syntax, the array states are responsible for ignoring newlines.
- r := lx.next()
- switch {
- case isWhitespace(r):
- return lexSkip(lx, lexValue)
- case isDigit(r):
- lx.backup() // avoid an extra state and use the same as above
- return lexNumberOrDateStart
- }
- switch r {
- case '[':
- lx.ignore()
- lx.emit(itemArray)
- return lexArrayValue
- case '{':
- lx.ignore()
- lx.emit(itemInlineTableStart)
- return lexInlineTableValue
- case '"':
- if lx.accept('"') {
- if lx.accept('"') {
- lx.ignore() // Ignore """
- return lexMultilineString
- }
- lx.backup()
- }
- lx.ignore() // ignore the '"'
- return lexString
- case '\'':
- if lx.accept('\'') {
- if lx.accept('\'') {
- lx.ignore() // Ignore """
- return lexMultilineRawString
- }
- lx.backup()
- }
- lx.ignore() // ignore the "'"
- return lexRawString
- case '.': // special error case, be kind to users
- return lx.errorf("floats must start with a digit, not '.'")
- case 'i', 'n':
- if (lx.accept('n') && lx.accept('f')) || (lx.accept('a') && lx.accept('n')) {
- lx.emit(itemFloat)
- return lx.pop()
- }
- case '-', '+':
- return lexDecimalNumberStart
- }
- if unicode.IsLetter(r) {
- // Be permissive here; lexBool will give a nice error if the
- // user wrote something like
- // x = foo
- // (i.e. not 'true' or 'false' but is something else word-like.)
- lx.backup()
- return lexBool
- }
- if r == eof {
- return lx.errorf("unexpected EOF; expected value")
- }
- return lx.errorf("expected value but found %q instead", r)
-}
-
-// lexArrayValue consumes one value in an array. It assumes that '[' or ','
-// have already been consumed. All whitespace and newlines are ignored.
-func lexArrayValue(lx *lexer) stateFn {
- r := lx.next()
- switch {
- case isWhitespace(r) || isNL(r):
- return lexSkip(lx, lexArrayValue)
- case r == '#':
- lx.push(lexArrayValue)
- return lexCommentStart
- case r == ',':
- return lx.errorf("unexpected comma")
- case r == ']':
- return lexArrayEnd
- }
-
- lx.backup()
- lx.push(lexArrayValueEnd)
- return lexValue
-}
-
-// lexArrayValueEnd consumes everything between the end of an array value and
-// the next value (or the end of the array): it ignores whitespace and newlines
-// and expects either a ',' or a ']'.
-func lexArrayValueEnd(lx *lexer) stateFn {
- switch r := lx.next(); {
- case isWhitespace(r) || isNL(r):
- return lexSkip(lx, lexArrayValueEnd)
- case r == '#':
- lx.push(lexArrayValueEnd)
- return lexCommentStart
- case r == ',':
- lx.ignore()
- return lexArrayValue // move on to the next value
- case r == ']':
- return lexArrayEnd
- default:
- return lx.errorf("expected a comma (',') or array terminator (']'), but got %s", runeOrEOF(r))
- }
-}
-
-// lexArrayEnd finishes the lexing of an array.
-// It assumes that a ']' has just been consumed.
-func lexArrayEnd(lx *lexer) stateFn {
- lx.ignore()
- lx.emit(itemArrayEnd)
- return lx.pop()
-}
-
-// lexInlineTableValue consumes one key/value pair in an inline table.
-// It assumes that '{' or ',' have already been consumed. Whitespace is ignored.
-func lexInlineTableValue(lx *lexer) stateFn {
- r := lx.next()
- switch {
- case isWhitespace(r):
- return lexSkip(lx, lexInlineTableValue)
- case isNL(r):
- if lx.tomlNext {
- return lexSkip(lx, lexInlineTableValue)
- }
- return lx.errorPrevLine(errLexInlineTableNL{})
- case r == '#':
- lx.push(lexInlineTableValue)
- return lexCommentStart
- case r == ',':
- return lx.errorf("unexpected comma")
- case r == '}':
- return lexInlineTableEnd
- }
- lx.backup()
- lx.push(lexInlineTableValueEnd)
- return lexKeyStart
-}
-
-// lexInlineTableValueEnd consumes everything between the end of an inline table
-// key/value pair and the next pair (or the end of the table):
-// it ignores whitespace and expects either a ',' or a '}'.
-func lexInlineTableValueEnd(lx *lexer) stateFn {
- switch r := lx.next(); {
- case isWhitespace(r):
- return lexSkip(lx, lexInlineTableValueEnd)
- case isNL(r):
- if lx.tomlNext {
- return lexSkip(lx, lexInlineTableValueEnd)
- }
- return lx.errorPrevLine(errLexInlineTableNL{})
- case r == '#':
- lx.push(lexInlineTableValueEnd)
- return lexCommentStart
- case r == ',':
- lx.ignore()
- lx.skip(isWhitespace)
- if lx.peek() == '}' {
- if lx.tomlNext {
- return lexInlineTableValueEnd
- }
- return lx.errorf("trailing comma not allowed in inline tables")
- }
- return lexInlineTableValue
- case r == '}':
- return lexInlineTableEnd
- default:
- return lx.errorf("expected a comma or an inline table terminator '}', but got %s instead", runeOrEOF(r))
- }
-}
-
-func runeOrEOF(r rune) string {
- if r == eof {
- return "end of file"
- }
- return "'" + string(r) + "'"
-}
-
-// lexInlineTableEnd finishes the lexing of an inline table.
-// It assumes that a '}' has just been consumed.
-func lexInlineTableEnd(lx *lexer) stateFn {
- lx.ignore()
- lx.emit(itemInlineTableEnd)
- return lx.pop()
-}
-
-// lexString consumes the inner contents of a string. It assumes that the
-// beginning '"' has already been consumed and ignored.
-func lexString(lx *lexer) stateFn {
- r := lx.next()
- switch {
- case r == eof:
- return lx.errorf(`unexpected EOF; expected '"'`)
- case isNL(r):
- return lx.errorPrevLine(errLexStringNL{})
- case r == '\\':
- lx.push(lexString)
- return lexStringEscape
- case r == '"':
- lx.backup()
- lx.emit(itemString)
- lx.next()
- lx.ignore()
- return lx.pop()
- }
- return lexString
-}
-
-// lexMultilineString consumes the inner contents of a string. It assumes that
-// the beginning '"""' has already been consumed and ignored.
-func lexMultilineString(lx *lexer) stateFn {
- r := lx.next()
- switch r {
- default:
- return lexMultilineString
- case eof:
- return lx.errorf(`unexpected EOF; expected '"""'`)
- case '\\':
- return lexMultilineStringEscape
- case '"':
- /// Found " → try to read two more "".
- if lx.accept('"') {
- if lx.accept('"') {
- /// Peek ahead: the string can contain " and "", including at the
- /// end: """str"""""
- /// 6 or more at the end, however, is an error.
- if lx.peek() == '"' {
- /// Check if we already lexed 5 's; if so we have 6 now, and
- /// that's just too many man!
- ///
- /// Second check is for the edge case:
- ///
- /// two quotes allowed.
- /// vv
- /// """lol \""""""
- /// ^^ ^^^---- closing three
- /// escaped
- ///
- /// But ugly, but it works
- if strings.HasSuffix(lx.current(), `"""""`) && !strings.HasSuffix(lx.current(), `\"""""`) {
- return lx.errorf(`unexpected '""""""'`)
- }
- lx.backup()
- lx.backup()
- return lexMultilineString
- }
-
- lx.backup() /// backup: don't include the """ in the item.
- lx.backup()
- lx.backup()
- lx.emit(itemMultilineString)
- lx.next() /// Read over ''' again and discard it.
- lx.next()
- lx.next()
- lx.ignore()
- return lx.pop()
- }
- lx.backup()
- }
- return lexMultilineString
- }
-}
-
-// lexRawString consumes a raw string. Nothing can be escaped in such a string.
-// It assumes that the beginning "'" has already been consumed and ignored.
-func lexRawString(lx *lexer) stateFn {
- r := lx.next()
- switch {
- default:
- return lexRawString
- case r == eof:
- return lx.errorf(`unexpected EOF; expected "'"`)
- case isNL(r):
- return lx.errorPrevLine(errLexStringNL{})
- case r == '\'':
- lx.backup()
- lx.emit(itemRawString)
- lx.next()
- lx.ignore()
- return lx.pop()
- }
-}
-
-// lexMultilineRawString consumes a raw string. Nothing can be escaped in such a
-// string. It assumes that the beginning triple-' has already been consumed and
-// ignored.
-func lexMultilineRawString(lx *lexer) stateFn {
- r := lx.next()
- switch r {
- default:
- return lexMultilineRawString
- case eof:
- return lx.errorf(`unexpected EOF; expected "'''"`)
- case '\'':
- /// Found ' → try to read two more ''.
- if lx.accept('\'') {
- if lx.accept('\'') {
- /// Peek ahead: the string can contain ' and '', including at the
- /// end: '''str'''''
- /// 6 or more at the end, however, is an error.
- if lx.peek() == '\'' {
- /// Check if we already lexed 5 's; if so we have 6 now, and
- /// that's just too many man!
- if strings.HasSuffix(lx.current(), "'''''") {
- return lx.errorf(`unexpected "''''''"`)
- }
- lx.backup()
- lx.backup()
- return lexMultilineRawString
- }
-
- lx.backup() /// backup: don't include the ''' in the item.
- lx.backup()
- lx.backup()
- lx.emit(itemRawMultilineString)
- lx.next() /// Read over ''' again and discard it.
- lx.next()
- lx.next()
- lx.ignore()
- return lx.pop()
- }
- lx.backup()
- }
- return lexMultilineRawString
- }
-}
-
-// lexMultilineStringEscape consumes an escaped character. It assumes that the
-// preceding '\\' has already been consumed.
-func lexMultilineStringEscape(lx *lexer) stateFn {
- if isNL(lx.next()) { /// \ escaping newline.
- return lexMultilineString
- }
- lx.backup()
- lx.push(lexMultilineString)
- return lexStringEscape(lx)
-}
-
-func lexStringEscape(lx *lexer) stateFn {
- r := lx.next()
- switch r {
- case 'e':
- if !lx.tomlNext {
- return lx.error(errLexEscape{r})
- }
- fallthrough
- case 'b':
- fallthrough
- case 't':
- fallthrough
- case 'n':
- fallthrough
- case 'f':
- fallthrough
- case 'r':
- fallthrough
- case '"':
- fallthrough
- case ' ', '\t':
- // Inside """ .. """ strings you can use \ to escape newlines, and any
- // amount of whitespace can be between the \ and \n.
- fallthrough
- case '\\':
- return lx.pop()
- case 'x':
- if !lx.tomlNext {
- return lx.error(errLexEscape{r})
- }
- return lexHexEscape
- case 'u':
- return lexShortUnicodeEscape
- case 'U':
- return lexLongUnicodeEscape
- }
- return lx.error(errLexEscape{r})
-}
-
-func lexHexEscape(lx *lexer) stateFn {
- var r rune
- for i := 0; i < 2; i++ {
- r = lx.next()
- if !isHexadecimal(r) {
- return lx.errorf(
- `expected two hexadecimal digits after '\x', but got %q instead`,
- lx.current())
- }
- }
- return lx.pop()
-}
-
-func lexShortUnicodeEscape(lx *lexer) stateFn {
- var r rune
- for i := 0; i < 4; i++ {
- r = lx.next()
- if !isHexadecimal(r) {
- return lx.errorf(
- `expected four hexadecimal digits after '\u', but got %q instead`,
- lx.current())
- }
- }
- return lx.pop()
-}
-
-func lexLongUnicodeEscape(lx *lexer) stateFn {
- var r rune
- for i := 0; i < 8; i++ {
- r = lx.next()
- if !isHexadecimal(r) {
- return lx.errorf(
- `expected eight hexadecimal digits after '\U', but got %q instead`,
- lx.current())
- }
- }
- return lx.pop()
-}
-
-// lexNumberOrDateStart processes the first character of a value which begins
-// with a digit. It exists to catch values starting with '0', so that
-// lexBaseNumberOrDate can differentiate base prefixed integers from other
-// types.
-func lexNumberOrDateStart(lx *lexer) stateFn {
- r := lx.next()
- switch r {
- case '0':
- return lexBaseNumberOrDate
- }
-
- if !isDigit(r) {
- // The only way to reach this state is if the value starts
- // with a digit, so specifically treat anything else as an
- // error.
- return lx.errorf("expected a digit but got %q", r)
- }
-
- return lexNumberOrDate
-}
-
-// lexNumberOrDate consumes either an integer, float or datetime.
-func lexNumberOrDate(lx *lexer) stateFn {
- r := lx.next()
- if isDigit(r) {
- return lexNumberOrDate
- }
- switch r {
- case '-', ':':
- return lexDatetime
- case '_':
- return lexDecimalNumber
- case '.', 'e', 'E':
- return lexFloat
- }
-
- lx.backup()
- lx.emit(itemInteger)
- return lx.pop()
-}
-
-// lexDatetime consumes a Datetime, to a first approximation.
-// The parser validates that it matches one of the accepted formats.
-func lexDatetime(lx *lexer) stateFn {
- r := lx.next()
- if isDigit(r) {
- return lexDatetime
- }
- switch r {
- case '-', ':', 'T', 't', ' ', '.', 'Z', 'z', '+':
- return lexDatetime
- }
-
- lx.backup()
- lx.emitTrim(itemDatetime)
- return lx.pop()
-}
-
-// lexHexInteger consumes a hexadecimal integer after seeing the '0x' prefix.
-func lexHexInteger(lx *lexer) stateFn {
- r := lx.next()
- if isHexadecimal(r) {
- return lexHexInteger
- }
- switch r {
- case '_':
- return lexHexInteger
- }
-
- lx.backup()
- lx.emit(itemInteger)
- return lx.pop()
-}
-
-// lexOctalInteger consumes an octal integer after seeing the '0o' prefix.
-func lexOctalInteger(lx *lexer) stateFn {
- r := lx.next()
- if isOctal(r) {
- return lexOctalInteger
- }
- switch r {
- case '_':
- return lexOctalInteger
- }
-
- lx.backup()
- lx.emit(itemInteger)
- return lx.pop()
-}
-
-// lexBinaryInteger consumes a binary integer after seeing the '0b' prefix.
-func lexBinaryInteger(lx *lexer) stateFn {
- r := lx.next()
- if isBinary(r) {
- return lexBinaryInteger
- }
- switch r {
- case '_':
- return lexBinaryInteger
- }
-
- lx.backup()
- lx.emit(itemInteger)
- return lx.pop()
-}
-
-// lexDecimalNumber consumes a decimal float or integer.
-func lexDecimalNumber(lx *lexer) stateFn {
- r := lx.next()
- if isDigit(r) {
- return lexDecimalNumber
- }
- switch r {
- case '.', 'e', 'E':
- return lexFloat
- case '_':
- return lexDecimalNumber
- }
-
- lx.backup()
- lx.emit(itemInteger)
- return lx.pop()
-}
-
-// lexDecimalNumber consumes the first digit of a number beginning with a sign.
-// It assumes the sign has already been consumed. Values which start with a sign
-// are only allowed to be decimal integers or floats.
-//
-// The special "nan" and "inf" values are also recognized.
-func lexDecimalNumberStart(lx *lexer) stateFn {
- r := lx.next()
-
- // Special error cases to give users better error messages
- switch r {
- case 'i':
- if !lx.accept('n') || !lx.accept('f') {
- return lx.errorf("invalid float: '%s'", lx.current())
- }
- lx.emit(itemFloat)
- return lx.pop()
- case 'n':
- if !lx.accept('a') || !lx.accept('n') {
- return lx.errorf("invalid float: '%s'", lx.current())
- }
- lx.emit(itemFloat)
- return lx.pop()
- case '0':
- p := lx.peek()
- switch p {
- case 'b', 'o', 'x':
- return lx.errorf("cannot use sign with non-decimal numbers: '%s%c'", lx.current(), p)
- }
- case '.':
- return lx.errorf("floats must start with a digit, not '.'")
- }
-
- if isDigit(r) {
- return lexDecimalNumber
- }
-
- return lx.errorf("expected a digit but got %q", r)
-}
-
-// lexBaseNumberOrDate differentiates between the possible values which
-// start with '0'. It assumes that before reaching this state, the initial '0'
-// has been consumed.
-func lexBaseNumberOrDate(lx *lexer) stateFn {
- r := lx.next()
- // Note: All datetimes start with at least two digits, so we don't
- // handle date characters (':', '-', etc.) here.
- if isDigit(r) {
- return lexNumberOrDate
- }
- switch r {
- case '_':
- // Can only be decimal, because there can't be an underscore
- // between the '0' and the base designator, and dates can't
- // contain underscores.
- return lexDecimalNumber
- case '.', 'e', 'E':
- return lexFloat
- case 'b':
- r = lx.peek()
- if !isBinary(r) {
- lx.errorf("not a binary number: '%s%c'", lx.current(), r)
- }
- return lexBinaryInteger
- case 'o':
- r = lx.peek()
- if !isOctal(r) {
- lx.errorf("not an octal number: '%s%c'", lx.current(), r)
- }
- return lexOctalInteger
- case 'x':
- r = lx.peek()
- if !isHexadecimal(r) {
- lx.errorf("not a hexidecimal number: '%s%c'", lx.current(), r)
- }
- return lexHexInteger
- }
-
- lx.backup()
- lx.emit(itemInteger)
- return lx.pop()
-}
-
-// lexFloat consumes the elements of a float. It allows any sequence of
-// float-like characters, so floats emitted by the lexer are only a first
-// approximation and must be validated by the parser.
-func lexFloat(lx *lexer) stateFn {
- r := lx.next()
- if isDigit(r) {
- return lexFloat
- }
- switch r {
- case '_', '.', '-', '+', 'e', 'E':
- return lexFloat
- }
-
- lx.backup()
- lx.emit(itemFloat)
- return lx.pop()
-}
-
-// lexBool consumes a bool string: 'true' or 'false.
-func lexBool(lx *lexer) stateFn {
- var rs []rune
- for {
- r := lx.next()
- if !unicode.IsLetter(r) {
- lx.backup()
- break
- }
- rs = append(rs, r)
- }
- s := string(rs)
- switch s {
- case "true", "false":
- lx.emit(itemBool)
- return lx.pop()
- }
- return lx.errorf("expected value but found %q instead", s)
-}
-
-// lexCommentStart begins the lexing of a comment. It will emit
-// itemCommentStart and consume no characters, passing control to lexComment.
-func lexCommentStart(lx *lexer) stateFn {
- lx.ignore()
- lx.emit(itemCommentStart)
- return lexComment
-}
-
-// lexComment lexes an entire comment. It assumes that '#' has been consumed.
-// It will consume *up to* the first newline character, and pass control
-// back to the last state on the stack.
-func lexComment(lx *lexer) stateFn {
- switch r := lx.next(); {
- case isNL(r) || r == eof:
- lx.backup()
- lx.emit(itemText)
- return lx.pop()
- default:
- return lexComment
- }
-}
-
-// lexSkip ignores all slurped input and moves on to the next state.
-func lexSkip(lx *lexer, nextState stateFn) stateFn {
- lx.ignore()
- return nextState
-}
-
-func (s stateFn) String() string {
- name := runtime.FuncForPC(reflect.ValueOf(s).Pointer()).Name()
- if i := strings.LastIndexByte(name, '.'); i > -1 {
- name = name[i+1:]
- }
- if s == nil {
- name = "<nil>"
- }
- return name + "()"
-}
-
-func (itype itemType) String() string {
- switch itype {
- case itemError:
- return "Error"
- case itemNIL:
- return "NIL"
- case itemEOF:
- return "EOF"
- case itemText:
- return "Text"
- case itemString, itemRawString, itemMultilineString, itemRawMultilineString:
- return "String"
- case itemBool:
- return "Bool"
- case itemInteger:
- return "Integer"
- case itemFloat:
- return "Float"
- case itemDatetime:
- return "DateTime"
- case itemTableStart:
- return "TableStart"
- case itemTableEnd:
- return "TableEnd"
- case itemKeyStart:
- return "KeyStart"
- case itemKeyEnd:
- return "KeyEnd"
- case itemArray:
- return "Array"
- case itemArrayEnd:
- return "ArrayEnd"
- case itemCommentStart:
- return "CommentStart"
- case itemInlineTableStart:
- return "InlineTableStart"
- case itemInlineTableEnd:
- return "InlineTableEnd"
- }
- panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype)))
-}
-
-func (item item) String() string {
- return fmt.Sprintf("(%s, %s)", item.typ.String(), item.val)
-}
-
-func isWhitespace(r rune) bool { return r == '\t' || r == ' ' }
-func isNL(r rune) bool { return r == '\n' || r == '\r' }
-func isControl(r rune) bool { // Control characters except \t, \r, \n
- switch r {
- case '\t', '\r', '\n':
- return false
- default:
- return (r >= 0x00 && r <= 0x1f) || r == 0x7f
- }
-}
-func isDigit(r rune) bool { return r >= '0' && r <= '9' }
-func isBinary(r rune) bool { return r == '0' || r == '1' }
-func isOctal(r rune) bool { return r >= '0' && r <= '7' }
-func isHexadecimal(r rune) bool {
- return (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')
-}
-
-func isBareKeyChar(r rune, tomlNext bool) bool {
- if tomlNext {
- return (r >= 'A' && r <= 'Z') ||
- (r >= 'a' && r <= 'z') ||
- (r >= '0' && r <= '9') ||
- r == '_' || r == '-' ||
- r == 0xb2 || r == 0xb3 || r == 0xb9 || (r >= 0xbc && r <= 0xbe) ||
- (r >= 0xc0 && r <= 0xd6) || (r >= 0xd8 && r <= 0xf6) || (r >= 0xf8 && r <= 0x037d) ||
- (r >= 0x037f && r <= 0x1fff) ||
- (r >= 0x200c && r <= 0x200d) || (r >= 0x203f && r <= 0x2040) ||
- (r >= 0x2070 && r <= 0x218f) || (r >= 0x2460 && r <= 0x24ff) ||
- (r >= 0x2c00 && r <= 0x2fef) || (r >= 0x3001 && r <= 0xd7ff) ||
- (r >= 0xf900 && r <= 0xfdcf) || (r >= 0xfdf0 && r <= 0xfffd) ||
- (r >= 0x10000 && r <= 0xeffff)
- }
-
- return (r >= 'A' && r <= 'Z') ||
- (r >= 'a' && r <= 'z') ||
- (r >= '0' && r <= '9') ||
- r == '_' || r == '-'
-}
diff --git a/vendor/github.com/BurntSushi/toml/meta.go b/vendor/github.com/BurntSushi/toml/meta.go
deleted file mode 100644
index 2e78b24..0000000
--- a/vendor/github.com/BurntSushi/toml/meta.go
+++ /dev/null
@@ -1,121 +0,0 @@
-package toml
-
-import (
- "strings"
-)
-
-// MetaData allows access to meta information about TOML data that's not
-// accessible otherwise.
-//
-// It allows checking if a key is defined in the TOML data, whether any keys
-// were undecoded, and the TOML type of a key.
-type MetaData struct {
- context Key // Used only during decoding.
-
- keyInfo map[string]keyInfo
- mapping map[string]interface{}
- keys []Key
- decoded map[string]struct{}
- data []byte // Input file; for errors.
-}
-
-// IsDefined reports if the key exists in the TOML data.
-//
-// The key should be specified hierarchically, for example to access the TOML
-// key "a.b.c" you would use IsDefined("a", "b", "c"). Keys are case sensitive.
-//
-// Returns false for an empty key.
-func (md *MetaData) IsDefined(key ...string) bool {
- if len(key) == 0 {
- return false
- }
-
- var (
- hash map[string]interface{}
- ok bool
- hashOrVal interface{} = md.mapping
- )
- for _, k := range key {
- if hash, ok = hashOrVal.(map[string]interface{}); !ok {
- return false
- }
- if hashOrVal, ok = hash[k]; !ok {
- return false
- }
- }
- return true
-}
-
-// Type returns a string representation of the type of the key specified.
-//
-// Type will return the empty string if given an empty key or a key that does
-// not exist. Keys are case sensitive.
-func (md *MetaData) Type(key ...string) string {
- if ki, ok := md.keyInfo[Key(key).String()]; ok {
- return ki.tomlType.typeString()
- }
- return ""
-}
-
-// Keys returns a slice of every key in the TOML data, including key groups.
-//
-// Each key is itself a slice, where the first element is the top of the
-// hierarchy and the last is the most specific. The list will have the same
-// order as the keys appeared in the TOML data.
-//
-// All keys returned are non-empty.
-func (md *MetaData) Keys() []Key {
- return md.keys
-}
-
-// Undecoded returns all keys that have not been decoded in the order in which
-// they appear in the original TOML document.
-//
-// This includes keys that haven't been decoded because of a [Primitive] value.
-// Once the Primitive value is decoded, the keys will be considered decoded.
-//
-// Also note that decoding into an empty interface will result in no decoding,
-// and so no keys will be considered decoded.
-//
-// In this sense, the Undecoded keys correspond to keys in the TOML document
-// that do not have a concrete type in your representation.
-func (md *MetaData) Undecoded() []Key {
- undecoded := make([]Key, 0, len(md.keys))
- for _, key := range md.keys {
- if _, ok := md.decoded[key.String()]; !ok {
- undecoded = append(undecoded, key)
- }
- }
- return undecoded
-}
-
-// Key represents any TOML key, including key groups. Use [MetaData.Keys] to get
-// values of this type.
-type Key []string
-
-func (k Key) String() string {
- ss := make([]string, len(k))
- for i := range k {
- ss[i] = k.maybeQuoted(i)
- }
- return strings.Join(ss, ".")
-}
-
-func (k Key) maybeQuoted(i int) string {
- if k[i] == "" {
- return `""`
- }
- for _, c := range k[i] {
- if !isBareKeyChar(c, false) {
- return `"` + dblQuotedReplacer.Replace(k[i]) + `"`
- }
- }
- return k[i]
-}
-
-func (k Key) add(piece string) Key {
- newKey := make(Key, len(k)+1)
- copy(newKey, k)
- newKey[len(k)] = piece
- return newKey
-}
diff --git a/vendor/github.com/BurntSushi/toml/parse.go b/vendor/github.com/BurntSushi/toml/parse.go
deleted file mode 100644
index 9c19153..0000000
--- a/vendor/github.com/BurntSushi/toml/parse.go
+++ /dev/null
@@ -1,811 +0,0 @@
-package toml
-
-import (
- "fmt"
- "os"
- "strconv"
- "strings"
- "time"
- "unicode/utf8"
-
- "github.com/BurntSushi/toml/internal"
-)
-
-type parser struct {
- lx *lexer
- context Key // Full key for the current hash in scope.
- currentKey string // Base key name for everything except hashes.
- pos Position // Current position in the TOML file.
- tomlNext bool
-
- ordered []Key // List of keys in the order that they appear in the TOML data.
-
- keyInfo map[string]keyInfo // Map keyname → info about the TOML key.
- mapping map[string]interface{} // Map keyname → key value.
- implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names").
-}
-
-type keyInfo struct {
- pos Position
- tomlType tomlType
-}
-
-func parse(data string) (p *parser, err error) {
- _, tomlNext := os.LookupEnv("BURNTSUSHI_TOML_110")
-
- defer func() {
- if r := recover(); r != nil {
- if pErr, ok := r.(ParseError); ok {
- pErr.input = data
- err = pErr
- return
- }
- panic(r)
- }
- }()
-
- // Read over BOM; do this here as the lexer calls utf8.DecodeRuneInString()
- // which mangles stuff. UTF-16 BOM isn't strictly valid, but some tools add
- // it anyway.
- if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { // UTF-16
- data = data[2:]
- } else if strings.HasPrefix(data, "\xef\xbb\xbf") { // UTF-8
- data = data[3:]
- }
-
- // Examine first few bytes for NULL bytes; this probably means it's a UTF-16
- // file (second byte in surrogate pair being NULL). Again, do this here to
- // avoid having to deal with UTF-8/16 stuff in the lexer.
- ex := 6
- if len(data) < 6 {
- ex = len(data)
- }
- if i := strings.IndexRune(data[:ex], 0); i > -1 {
- return nil, ParseError{
- Message: "files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8",
- Position: Position{Line: 1, Start: i, Len: 1},
- Line: 1,
- input: data,
- }
- }
-
- p = &parser{
- keyInfo: make(map[string]keyInfo),
- mapping: make(map[string]interface{}),
- lx: lex(data, tomlNext),
- ordered: make([]Key, 0),
- implicits: make(map[string]struct{}),
- tomlNext: tomlNext,
- }
- for {
- item := p.next()
- if item.typ == itemEOF {
- break
- }
- p.topLevel(item)
- }
-
- return p, nil
-}
-
-func (p *parser) panicErr(it item, err error) {
- panic(ParseError{
- err: err,
- Position: it.pos,
- Line: it.pos.Len,
- LastKey: p.current(),
- })
-}
-
-func (p *parser) panicItemf(it item, format string, v ...interface{}) {
- panic(ParseError{
- Message: fmt.Sprintf(format, v...),
- Position: it.pos,
- Line: it.pos.Len,
- LastKey: p.current(),
- })
-}
-
-func (p *parser) panicf(format string, v ...interface{}) {
- panic(ParseError{
- Message: fmt.Sprintf(format, v...),
- Position: p.pos,
- Line: p.pos.Line,
- LastKey: p.current(),
- })
-}
-
-func (p *parser) next() item {
- it := p.lx.nextItem()
- //fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.pos.Line, it.val)
- if it.typ == itemError {
- if it.err != nil {
- panic(ParseError{
- Position: it.pos,
- Line: it.pos.Line,
- LastKey: p.current(),
- err: it.err,
- })
- }
-
- p.panicItemf(it, "%s", it.val)
- }
- return it
-}
-
-func (p *parser) nextPos() item {
- it := p.next()
- p.pos = it.pos
- return it
-}
-
-func (p *parser) bug(format string, v ...interface{}) {
- panic(fmt.Sprintf("BUG: "+format+"\n\n", v...))
-}
-
-func (p *parser) expect(typ itemType) item {
- it := p.next()
- p.assertEqual(typ, it.typ)
- return it
-}
-
-func (p *parser) assertEqual(expected, got itemType) {
- if expected != got {
- p.bug("Expected '%s' but got '%s'.", expected, got)
- }
-}
-
-func (p *parser) topLevel(item item) {
- switch item.typ {
- case itemCommentStart: // # ..
- p.expect(itemText)
- case itemTableStart: // [ .. ]
- name := p.nextPos()
-
- var key Key
- for ; name.typ != itemTableEnd && name.typ != itemEOF; name = p.next() {
- key = append(key, p.keyString(name))
- }
- p.assertEqual(itemTableEnd, name.typ)
-
- p.addContext(key, false)
- p.setType("", tomlHash, item.pos)
- p.ordered = append(p.ordered, key)
- case itemArrayTableStart: // [[ .. ]]
- name := p.nextPos()
-
- var key Key
- for ; name.typ != itemArrayTableEnd && name.typ != itemEOF; name = p.next() {
- key = append(key, p.keyString(name))
- }
- p.assertEqual(itemArrayTableEnd, name.typ)
-
- p.addContext(key, true)
- p.setType("", tomlArrayHash, item.pos)
- p.ordered = append(p.ordered, key)
- case itemKeyStart: // key = ..
- outerContext := p.context
- /// Read all the key parts (e.g. 'a' and 'b' in 'a.b')
- k := p.nextPos()
- var key Key
- for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() {
- key = append(key, p.keyString(k))
- }
- p.assertEqual(itemKeyEnd, k.typ)
-
- /// The current key is the last part.
- p.currentKey = key[len(key)-1]
-
- /// All the other parts (if any) are the context; need to set each part
- /// as implicit.
- context := key[:len(key)-1]
- for i := range context {
- p.addImplicitContext(append(p.context, context[i:i+1]...))
- }
- p.ordered = append(p.ordered, p.context.add(p.currentKey))
-
- /// Set value.
- vItem := p.next()
- val, typ := p.value(vItem, false)
- p.set(p.currentKey, val, typ, vItem.pos)
-
- /// Remove the context we added (preserving any context from [tbl] lines).
- p.context = outerContext
- p.currentKey = ""
- default:
- p.bug("Unexpected type at top level: %s", item.typ)
- }
-}
-
-// Gets a string for a key (or part of a key in a table name).
-func (p *parser) keyString(it item) string {
- switch it.typ {
- case itemText:
- return it.val
- case itemString, itemMultilineString,
- itemRawString, itemRawMultilineString:
- s, _ := p.value(it, false)
- return s.(string)
- default:
- p.bug("Unexpected key type: %s", it.typ)
- }
- panic("unreachable")
-}
-
-var datetimeRepl = strings.NewReplacer(
- "z", "Z",
- "t", "T",
- " ", "T")
-
-// value translates an expected value from the lexer into a Go value wrapped
-// as an empty interface.
-func (p *parser) value(it item, parentIsArray bool) (interface{}, tomlType) {
- switch it.typ {
- case itemString:
- return p.replaceEscapes(it, it.val), p.typeOfPrimitive(it)
- case itemMultilineString:
- return p.replaceEscapes(it, p.stripEscapedNewlines(stripFirstNewline(it.val))), p.typeOfPrimitive(it)
- case itemRawString:
- return it.val, p.typeOfPrimitive(it)
- case itemRawMultilineString:
- return stripFirstNewline(it.val), p.typeOfPrimitive(it)
- case itemInteger:
- return p.valueInteger(it)
- case itemFloat:
- return p.valueFloat(it)
- case itemBool:
- switch it.val {
- case "true":
- return true, p.typeOfPrimitive(it)
- case "false":
- return false, p.typeOfPrimitive(it)
- default:
- p.bug("Expected boolean value, but got '%s'.", it.val)
- }
- case itemDatetime:
- return p.valueDatetime(it)
- case itemArray:
- return p.valueArray(it)
- case itemInlineTableStart:
- return p.valueInlineTable(it, parentIsArray)
- default:
- p.bug("Unexpected value type: %s", it.typ)
- }
- panic("unreachable")
-}
-
-func (p *parser) valueInteger(it item) (interface{}, tomlType) {
- if !numUnderscoresOK(it.val) {
- p.panicItemf(it, "Invalid integer %q: underscores must be surrounded by digits", it.val)
- }
- if numHasLeadingZero(it.val) {
- p.panicItemf(it, "Invalid integer %q: cannot have leading zeroes", it.val)
- }
-
- num, err := strconv.ParseInt(it.val, 0, 64)
- if err != nil {
- // Distinguish integer values. Normally, it'd be a bug if the lexer
- // provides an invalid integer, but it's possible that the number is
- // out of range of valid values (which the lexer cannot determine).
- // So mark the former as a bug but the latter as a legitimate user
- // error.
- if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
- p.panicErr(it, errParseRange{i: it.val, size: "int64"})
- } else {
- p.bug("Expected integer value, but got '%s'.", it.val)
- }
- }
- return num, p.typeOfPrimitive(it)
-}
-
-func (p *parser) valueFloat(it item) (interface{}, tomlType) {
- parts := strings.FieldsFunc(it.val, func(r rune) bool {
- switch r {
- case '.', 'e', 'E':
- return true
- }
- return false
- })
- for _, part := range parts {
- if !numUnderscoresOK(part) {
- p.panicItemf(it, "Invalid float %q: underscores must be surrounded by digits", it.val)
- }
- }
- if len(parts) > 0 && numHasLeadingZero(parts[0]) {
- p.panicItemf(it, "Invalid float %q: cannot have leading zeroes", it.val)
- }
- if !numPeriodsOK(it.val) {
- // As a special case, numbers like '123.' or '1.e2',
- // which are valid as far as Go/strconv are concerned,
- // must be rejected because TOML says that a fractional
- // part consists of '.' followed by 1+ digits.
- p.panicItemf(it, "Invalid float %q: '.' must be followed by one or more digits", it.val)
- }
- val := strings.Replace(it.val, "_", "", -1)
- if val == "+nan" || val == "-nan" { // Go doesn't support this, but TOML spec does.
- val = "nan"
- }
- num, err := strconv.ParseFloat(val, 64)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
- p.panicErr(it, errParseRange{i: it.val, size: "float64"})
- } else {
- p.panicItemf(it, "Invalid float value: %q", it.val)
- }
- }
- return num, p.typeOfPrimitive(it)
-}
-
-var dtTypes = []struct {
- fmt string
- zone *time.Location
- next bool
-}{
- {time.RFC3339Nano, time.Local, false},
- {"2006-01-02T15:04:05.999999999", internal.LocalDatetime, false},
- {"2006-01-02", internal.LocalDate, false},
- {"15:04:05.999999999", internal.LocalTime, false},
-
- // tomlNext
- {"2006-01-02T15:04Z07:00", time.Local, true},
- {"2006-01-02T15:04", internal.LocalDatetime, true},
- {"15:04", internal.LocalTime, true},
-}
-
-func (p *parser) valueDatetime(it item) (interface{}, tomlType) {
- it.val = datetimeRepl.Replace(it.val)
- var (
- t time.Time
- ok bool
- err error
- )
- for _, dt := range dtTypes {
- if dt.next && !p.tomlNext {
- continue
- }
- t, err = time.ParseInLocation(dt.fmt, it.val, dt.zone)
- if err == nil {
- ok = true
- break
- }
- }
- if !ok {
- p.panicItemf(it, "Invalid TOML Datetime: %q.", it.val)
- }
- return t, p.typeOfPrimitive(it)
-}
-
-func (p *parser) valueArray(it item) (interface{}, tomlType) {
- p.setType(p.currentKey, tomlArray, it.pos)
-
- var (
- types []tomlType
-
- // Initialize to a non-nil empty slice. This makes it consistent with
- // how S = [] decodes into a non-nil slice inside something like struct
- // { S []string }. See #338
- array = []interface{}{}
- )
- for it = p.next(); it.typ != itemArrayEnd; it = p.next() {
- if it.typ == itemCommentStart {
- p.expect(itemText)
- continue
- }
-
- val, typ := p.value(it, true)
- array = append(array, val)
- types = append(types, typ)
-
- // XXX: types isn't used here, we need it to record the accurate type
- // information.
- //
- // Not entirely sure how to best store this; could use "key[0]",
- // "key[1]" notation, or maybe store it on the Array type?
- _ = types
- }
- return array, tomlArray
-}
-
-func (p *parser) valueInlineTable(it item, parentIsArray bool) (interface{}, tomlType) {
- var (
- hash = make(map[string]interface{})
- outerContext = p.context
- outerKey = p.currentKey
- )
-
- p.context = append(p.context, p.currentKey)
- prevContext := p.context
- p.currentKey = ""
-
- p.addImplicit(p.context)
- p.addContext(p.context, parentIsArray)
-
- /// Loop over all table key/value pairs.
- for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() {
- if it.typ == itemCommentStart {
- p.expect(itemText)
- continue
- }
-
- /// Read all key parts.
- k := p.nextPos()
- var key Key
- for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() {
- key = append(key, p.keyString(k))
- }
- p.assertEqual(itemKeyEnd, k.typ)
-
- /// The current key is the last part.
- p.currentKey = key[len(key)-1]
-
- /// All the other parts (if any) are the context; need to set each part
- /// as implicit.
- context := key[:len(key)-1]
- for i := range context {
- p.addImplicitContext(append(p.context, context[i:i+1]...))
- }
- p.ordered = append(p.ordered, p.context.add(p.currentKey))
-
- /// Set the value.
- val, typ := p.value(p.next(), false)
- p.set(p.currentKey, val, typ, it.pos)
- hash[p.currentKey] = val
-
- /// Restore context.
- p.context = prevContext
- }
- p.context = outerContext
- p.currentKey = outerKey
- return hash, tomlHash
-}
-
-// numHasLeadingZero checks if this number has leading zeroes, allowing for '0',
-// +/- signs, and base prefixes.
-func numHasLeadingZero(s string) bool {
- if len(s) > 1 && s[0] == '0' && !(s[1] == 'b' || s[1] == 'o' || s[1] == 'x') { // Allow 0b, 0o, 0x
- return true
- }
- if len(s) > 2 && (s[0] == '-' || s[0] == '+') && s[1] == '0' {
- return true
- }
- return false
-}
-
-// numUnderscoresOK checks whether each underscore in s is surrounded by
-// characters that are not underscores.
-func numUnderscoresOK(s string) bool {
- switch s {
- case "nan", "+nan", "-nan", "inf", "-inf", "+inf":
- return true
- }
- accept := false
- for _, r := range s {
- if r == '_' {
- if !accept {
- return false
- }
- }
-
- // isHexadecimal is a superset of all the permissable characters
- // surrounding an underscore.
- accept = isHexadecimal(r)
- }
- return accept
-}
-
-// numPeriodsOK checks whether every period in s is followed by a digit.
-func numPeriodsOK(s string) bool {
- period := false
- for _, r := range s {
- if period && !isDigit(r) {
- return false
- }
- period = r == '.'
- }
- return !period
-}
-
-// Set the current context of the parser, where the context is either a hash or
-// an array of hashes, depending on the value of the `array` parameter.
-//
-// Establishing the context also makes sure that the key isn't a duplicate, and
-// will create implicit hashes automatically.
-func (p *parser) addContext(key Key, array bool) {
- var ok bool
-
- // Always start at the top level and drill down for our context.
- hashContext := p.mapping
- keyContext := make(Key, 0)
-
- // We only need implicit hashes for key[0:-1]
- for _, k := range key[0 : len(key)-1] {
- _, ok = hashContext[k]
- keyContext = append(keyContext, k)
-
- // No key? Make an implicit hash and move on.
- if !ok {
- p.addImplicit(keyContext)
- hashContext[k] = make(map[string]interface{})
- }
-
- // If the hash context is actually an array of tables, then set
- // the hash context to the last element in that array.
- //
- // Otherwise, it better be a table, since this MUST be a key group (by
- // virtue of it not being the last element in a key).
- switch t := hashContext[k].(type) {
- case []map[string]interface{}:
- hashContext = t[len(t)-1]
- case map[string]interface{}:
- hashContext = t
- default:
- p.panicf("Key '%s' was already created as a hash.", keyContext)
- }
- }
-
- p.context = keyContext
- if array {
- // If this is the first element for this array, then allocate a new
- // list of tables for it.
- k := key[len(key)-1]
- if _, ok := hashContext[k]; !ok {
- hashContext[k] = make([]map[string]interface{}, 0, 4)
- }
-
- // Add a new table. But make sure the key hasn't already been used
- // for something else.
- if hash, ok := hashContext[k].([]map[string]interface{}); ok {
- hashContext[k] = append(hash, make(map[string]interface{}))
- } else {
- p.panicf("Key '%s' was already created and cannot be used as an array.", key)
- }
- } else {
- p.setValue(key[len(key)-1], make(map[string]interface{}))
- }
- p.context = append(p.context, key[len(key)-1])
-}
-
-// set calls setValue and setType.
-func (p *parser) set(key string, val interface{}, typ tomlType, pos Position) {
- p.setValue(key, val)
- p.setType(key, typ, pos)
-}
-
-// setValue sets the given key to the given value in the current context.
-// It will make sure that the key hasn't already been defined, account for
-// implicit key groups.
-func (p *parser) setValue(key string, value interface{}) {
- var (
- tmpHash interface{}
- ok bool
- hash = p.mapping
- keyContext Key
- )
- for _, k := range p.context {
- keyContext = append(keyContext, k)
- if tmpHash, ok = hash[k]; !ok {
- p.bug("Context for key '%s' has not been established.", keyContext)
- }
- switch t := tmpHash.(type) {
- case []map[string]interface{}:
- // The context is a table of hashes. Pick the most recent table
- // defined as the current hash.
- hash = t[len(t)-1]
- case map[string]interface{}:
- hash = t
- default:
- p.panicf("Key '%s' has already been defined.", keyContext)
- }
- }
- keyContext = append(keyContext, key)
-
- if _, ok := hash[key]; ok {
- // Normally redefining keys isn't allowed, but the key could have been
- // defined implicitly and it's allowed to be redefined concretely. (See
- // the `valid/implicit-and-explicit-after.toml` in toml-test)
- //
- // But we have to make sure to stop marking it as an implicit. (So that
- // another redefinition provokes an error.)
- //
- // Note that since it has already been defined (as a hash), we don't
- // want to overwrite it. So our business is done.
- if p.isArray(keyContext) {
- p.removeImplicit(keyContext)
- hash[key] = value
- return
- }
- if p.isImplicit(keyContext) {
- p.removeImplicit(keyContext)
- return
- }
-
- // Otherwise, we have a concrete key trying to override a previous
- // key, which is *always* wrong.
- p.panicf("Key '%s' has already been defined.", keyContext)
- }
-
- hash[key] = value
-}
-
-// setType sets the type of a particular value at a given key. It should be
-// called immediately AFTER setValue.
-//
-// Note that if `key` is empty, then the type given will be applied to the
-// current context (which is either a table or an array of tables).
-func (p *parser) setType(key string, typ tomlType, pos Position) {
- keyContext := make(Key, 0, len(p.context)+1)
- keyContext = append(keyContext, p.context...)
- if len(key) > 0 { // allow type setting for hashes
- keyContext = append(keyContext, key)
- }
- // Special case to make empty keys ("" = 1) work.
- // Without it it will set "" rather than `""`.
- // TODO: why is this needed? And why is this only needed here?
- if len(keyContext) == 0 {
- keyContext = Key{""}
- }
- p.keyInfo[keyContext.String()] = keyInfo{tomlType: typ, pos: pos}
-}
-
-// Implicit keys need to be created when tables are implied in "a.b.c.d = 1" and
-// "[a.b.c]" (the "a", "b", and "c" hashes are never created explicitly).
-func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} }
-func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) }
-func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok }
-func (p *parser) isArray(key Key) bool { return p.keyInfo[key.String()].tomlType == tomlArray }
-func (p *parser) addImplicitContext(key Key) { p.addImplicit(key); p.addContext(key, false) }
-
-// current returns the full key name of the current context.
-func (p *parser) current() string {
- if len(p.currentKey) == 0 {
- return p.context.String()
- }
- if len(p.context) == 0 {
- return p.currentKey
- }
- return fmt.Sprintf("%s.%s", p.context, p.currentKey)
-}
-
-func stripFirstNewline(s string) string {
- if len(s) > 0 && s[0] == '\n' {
- return s[1:]
- }
- if len(s) > 1 && s[0] == '\r' && s[1] == '\n' {
- return s[2:]
- }
- return s
-}
-
-// stripEscapedNewlines removes whitespace after line-ending backslashes in
-// multiline strings.
-//
-// A line-ending backslash is an unescaped \ followed only by whitespace until
-// the next newline. After a line-ending backslash, all whitespace is removed
-// until the next non-whitespace character.
-func (p *parser) stripEscapedNewlines(s string) string {
- var b strings.Builder
- var i int
- for {
- ix := strings.Index(s[i:], `\`)
- if ix < 0 {
- b.WriteString(s)
- return b.String()
- }
- i += ix
-
- if len(s) > i+1 && s[i+1] == '\\' {
- // Escaped backslash.
- i += 2
- continue
- }
- // Scan until the next non-whitespace.
- j := i + 1
- whitespaceLoop:
- for ; j < len(s); j++ {
- switch s[j] {
- case ' ', '\t', '\r', '\n':
- default:
- break whitespaceLoop
- }
- }
- if j == i+1 {
- // Not a whitespace escape.
- i++
- continue
- }
- if !strings.Contains(s[i:j], "\n") {
- // This is not a line-ending backslash.
- // (It's a bad escape sequence, but we can let
- // replaceEscapes catch it.)
- i++
- continue
- }
- b.WriteString(s[:i])
- s = s[j:]
- i = 0
- }
-}
-
-func (p *parser) replaceEscapes(it item, str string) string {
- replaced := make([]rune, 0, len(str))
- s := []byte(str)
- r := 0
- for r < len(s) {
- if s[r] != '\\' {
- c, size := utf8.DecodeRune(s[r:])
- r += size
- replaced = append(replaced, c)
- continue
- }
- r += 1
- if r >= len(s) {
- p.bug("Escape sequence at end of string.")
- return ""
- }
- switch s[r] {
- default:
- p.bug("Expected valid escape code after \\, but got %q.", s[r])
- case ' ', '\t':
- p.panicItemf(it, "invalid escape: '\\%c'", s[r])
- case 'b':
- replaced = append(replaced, rune(0x0008))
- r += 1
- case 't':
- replaced = append(replaced, rune(0x0009))
- r += 1
- case 'n':
- replaced = append(replaced, rune(0x000A))
- r += 1
- case 'f':
- replaced = append(replaced, rune(0x000C))
- r += 1
- case 'r':
- replaced = append(replaced, rune(0x000D))
- r += 1
- case 'e':
- if p.tomlNext {
- replaced = append(replaced, rune(0x001B))
- r += 1
- }
- case '"':
- replaced = append(replaced, rune(0x0022))
- r += 1
- case '\\':
- replaced = append(replaced, rune(0x005C))
- r += 1
- case 'x':
- if p.tomlNext {
- escaped := p.asciiEscapeToUnicode(it, s[r+1:r+3])
- replaced = append(replaced, escaped)
- r += 3
- }
- case 'u':
- // At this point, we know we have a Unicode escape of the form
- // `uXXXX` at [r, r+5). (Because the lexer guarantees this
- // for us.)
- escaped := p.asciiEscapeToUnicode(it, s[r+1:r+5])
- replaced = append(replaced, escaped)
- r += 5
- case 'U':
- // At this point, we know we have a Unicode escape of the form
- // `uXXXX` at [r, r+9). (Because the lexer guarantees this
- // for us.)
- escaped := p.asciiEscapeToUnicode(it, s[r+1:r+9])
- replaced = append(replaced, escaped)
- r += 9
- }
- }
- return string(replaced)
-}
-
-func (p *parser) asciiEscapeToUnicode(it item, bs []byte) rune {
- s := string(bs)
- hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32)
- if err != nil {
- p.bug("Could not parse '%s' as a hexadecimal number, but the lexer claims it's OK: %s", s, err)
- }
- if !utf8.ValidRune(rune(hex)) {
- p.panicItemf(it, "Escaped character '\\u%s' is not valid UTF-8.", s)
- }
- return rune(hex)
-}
diff --git a/vendor/github.com/BurntSushi/toml/type_fields.go b/vendor/github.com/BurntSushi/toml/type_fields.go
deleted file mode 100644
index 254ca82..0000000
--- a/vendor/github.com/BurntSushi/toml/type_fields.go
+++ /dev/null
@@ -1,242 +0,0 @@
-package toml
-
-// Struct field handling is adapted from code in encoding/json:
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the Go distribution.
-
-import (
- "reflect"
- "sort"
- "sync"
-)
-
-// A field represents a single field found in a struct.
-type field struct {
- name string // the name of the field (`toml` tag included)
- tag bool // whether field has a `toml` tag
- index []int // represents the depth of an anonymous field
- typ reflect.Type // the type of the field
-}
-
-// byName sorts field by name, breaking ties with depth,
-// then breaking ties with "name came from toml tag", then
-// breaking ties with index sequence.
-type byName []field
-
-func (x byName) Len() int { return len(x) }
-
-func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
-
-func (x byName) Less(i, j int) bool {
- if x[i].name != x[j].name {
- return x[i].name < x[j].name
- }
- if len(x[i].index) != len(x[j].index) {
- return len(x[i].index) < len(x[j].index)
- }
- if x[i].tag != x[j].tag {
- return x[i].tag
- }
- return byIndex(x).Less(i, j)
-}
-
-// byIndex sorts field by index sequence.
-type byIndex []field
-
-func (x byIndex) Len() int { return len(x) }
-
-func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
-
-func (x byIndex) Less(i, j int) bool {
- for k, xik := range x[i].index {
- if k >= len(x[j].index) {
- return false
- }
- if xik != x[j].index[k] {
- return xik < x[j].index[k]
- }
- }
- return len(x[i].index) < len(x[j].index)
-}
-
-// typeFields returns a list of fields that TOML should recognize for the given
-// type. The algorithm is breadth-first search over the set of structs to
-// include - the top struct and then any reachable anonymous structs.
-func typeFields(t reflect.Type) []field {
- // Anonymous fields to explore at the current level and the next.
- current := []field{}
- next := []field{{typ: t}}
-
- // Count of queued names for current level and the next.
- var count map[reflect.Type]int
- var nextCount map[reflect.Type]int
-
- // Types already visited at an earlier level.
- visited := map[reflect.Type]bool{}
-
- // Fields found.
- var fields []field
-
- for len(next) > 0 {
- current, next = next, current[:0]
- count, nextCount = nextCount, map[reflect.Type]int{}
-
- for _, f := range current {
- if visited[f.typ] {
- continue
- }
- visited[f.typ] = true
-
- // Scan f.typ for fields to include.
- for i := 0; i < f.typ.NumField(); i++ {
- sf := f.typ.Field(i)
- if sf.PkgPath != "" && !sf.Anonymous { // unexported
- continue
- }
- opts := getOptions(sf.Tag)
- if opts.skip {
- continue
- }
- index := make([]int, len(f.index)+1)
- copy(index, f.index)
- index[len(f.index)] = i
-
- ft := sf.Type
- if ft.Name() == "" && ft.Kind() == reflect.Ptr {
- // Follow pointer.
- ft = ft.Elem()
- }
-
- // Record found field and index sequence.
- if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
- tagged := opts.name != ""
- name := opts.name
- if name == "" {
- name = sf.Name
- }
- fields = append(fields, field{name, tagged, index, ft})
- if count[f.typ] > 1 {
- // If there were multiple instances, add a second,
- // so that the annihilation code will see a duplicate.
- // It only cares about the distinction between 1 or 2,
- // so don't bother generating any more copies.
- fields = append(fields, fields[len(fields)-1])
- }
- continue
- }
-
- // Record new anonymous struct to explore in next round.
- nextCount[ft]++
- if nextCount[ft] == 1 {
- f := field{name: ft.Name(), index: index, typ: ft}
- next = append(next, f)
- }
- }
- }
- }
-
- sort.Sort(byName(fields))
-
- // Delete all fields that are hidden by the Go rules for embedded fields,
- // except that fields with TOML tags are promoted.
-
- // The fields are sorted in primary order of name, secondary order
- // of field index length. Loop over names; for each name, delete
- // hidden fields by choosing the one dominant field that survives.
- out := fields[:0]
- for advance, i := 0, 0; i < len(fields); i += advance {
- // One iteration per name.
- // Find the sequence of fields with the name of this first field.
- fi := fields[i]
- name := fi.name
- for advance = 1; i+advance < len(fields); advance++ {
- fj := fields[i+advance]
- if fj.name != name {
- break
- }
- }
- if advance == 1 { // Only one field with this name
- out = append(out, fi)
- continue
- }
- dominant, ok := dominantField(fields[i : i+advance])
- if ok {
- out = append(out, dominant)
- }
- }
-
- fields = out
- sort.Sort(byIndex(fields))
-
- return fields
-}
-
-// dominantField looks through the fields, all of which are known to
-// have the same name, to find the single field that dominates the
-// others using Go's embedding rules, modified by the presence of
-// TOML tags. If there are multiple top-level fields, the boolean
-// will be false: This condition is an error in Go and we skip all
-// the fields.
-func dominantField(fields []field) (field, bool) {
- // The fields are sorted in increasing index-length order. The winner
- // must therefore be one with the shortest index length. Drop all
- // longer entries, which is easy: just truncate the slice.
- length := len(fields[0].index)
- tagged := -1 // Index of first tagged field.
- for i, f := range fields {
- if len(f.index) > length {
- fields = fields[:i]
- break
- }
- if f.tag {
- if tagged >= 0 {
- // Multiple tagged fields at the same level: conflict.
- // Return no field.
- return field{}, false
- }
- tagged = i
- }
- }
- if tagged >= 0 {
- return fields[tagged], true
- }
- // All remaining fields have the same length. If there's more than one,
- // we have a conflict (two fields named "X" at the same level) and we
- // return no field.
- if len(fields) > 1 {
- return field{}, false
- }
- return fields[0], true
-}
-
-var fieldCache struct {
- sync.RWMutex
- m map[reflect.Type][]field
-}
-
-// cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
-func cachedTypeFields(t reflect.Type) []field {
- fieldCache.RLock()
- f := fieldCache.m[t]
- fieldCache.RUnlock()
- if f != nil {
- return f
- }
-
- // Compute fields without lock.
- // Might duplicate effort but won't hold other computations back.
- f = typeFields(t)
- if f == nil {
- f = []field{}
- }
-
- fieldCache.Lock()
- if fieldCache.m == nil {
- fieldCache.m = map[reflect.Type][]field{}
- }
- fieldCache.m[t] = f
- fieldCache.Unlock()
- return f
-}
diff --git a/vendor/github.com/BurntSushi/toml/type_toml.go b/vendor/github.com/BurntSushi/toml/type_toml.go
deleted file mode 100644
index 4e90d77..0000000
--- a/vendor/github.com/BurntSushi/toml/type_toml.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package toml
-
-// tomlType represents any Go type that corresponds to a TOML type.
-// While the first draft of the TOML spec has a simplistic type system that
-// probably doesn't need this level of sophistication, we seem to be militating
-// toward adding real composite types.
-type tomlType interface {
- typeString() string
-}
-
-// typeEqual accepts any two types and returns true if they are equal.
-func typeEqual(t1, t2 tomlType) bool {
- if t1 == nil || t2 == nil {
- return false
- }
- return t1.typeString() == t2.typeString()
-}
-
-func typeIsTable(t tomlType) bool {
- return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash)
-}
-
-type tomlBaseType string
-
-func (btype tomlBaseType) typeString() string {
- return string(btype)
-}
-
-func (btype tomlBaseType) String() string {
- return btype.typeString()
-}
-
-var (
- tomlInteger tomlBaseType = "Integer"
- tomlFloat tomlBaseType = "Float"
- tomlDatetime tomlBaseType = "Datetime"
- tomlString tomlBaseType = "String"
- tomlBool tomlBaseType = "Bool"
- tomlArray tomlBaseType = "Array"
- tomlHash tomlBaseType = "Hash"
- tomlArrayHash tomlBaseType = "ArrayHash"
-)
-
-// typeOfPrimitive returns a tomlType of any primitive value in TOML.
-// Primitive values are: Integer, Float, Datetime, String and Bool.
-//
-// Passing a lexer item other than the following will cause a BUG message
-// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime.
-func (p *parser) typeOfPrimitive(lexItem item) tomlType {
- switch lexItem.typ {
- case itemInteger:
- return tomlInteger
- case itemFloat:
- return tomlFloat
- case itemDatetime:
- return tomlDatetime
- case itemString:
- return tomlString
- case itemMultilineString:
- return tomlString
- case itemRawString:
- return tomlString
- case itemRawMultilineString:
- return tomlString
- case itemBool:
- return tomlBool
- }
- p.bug("Cannot infer primitive type of lex item '%s'.", lexItem)
- panic("unreachable")
-}
diff --git a/vendor/github.com/google/go-cmp/LICENSE b/vendor/github.com/google/go-cmp/LICENSE
deleted file mode 100644
index 32017f8..0000000
--- a/vendor/github.com/google/go-cmp/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2017 The Go Authors. 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.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-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
-OWNER 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/google/go-cmp/cmp/compare.go b/vendor/github.com/google/go-cmp/cmp/compare.go
deleted file mode 100644
index 087320d..0000000
--- a/vendor/github.com/google/go-cmp/cmp/compare.go
+++ /dev/null
@@ -1,669 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package cmp determines equality of values.
-//
-// This package is intended to be a more powerful and safer alternative to
-// reflect.DeepEqual for comparing whether two values are semantically equal.
-// It is intended to only be used in tests, as performance is not a goal and
-// it may panic if it cannot compare the values. Its propensity towards
-// panicking means that its unsuitable for production environments where a
-// spurious panic may be fatal.
-//
-// The primary features of cmp are:
-//
-// - When the default behavior of equality does not suit the test's needs,
-// custom equality functions can override the equality operation.
-// For example, an equality function may report floats as equal so long as
-// they are within some tolerance of each other.
-//
-// - Types with an Equal method may use that method to determine equality.
-// This allows package authors to determine the equality operation
-// for the types that they define.
-//
-// - If no custom equality functions are used and no Equal method is defined,
-// equality is determined by recursively comparing the primitive kinds on
-// both values, much like reflect.DeepEqual. Unlike reflect.DeepEqual,
-// unexported fields are not compared by default; they result in panics
-// unless suppressed by using an Ignore option (see cmpopts.IgnoreUnexported)
-// or explicitly compared using the Exporter option.
-package cmp
-
-import (
- "fmt"
- "reflect"
- "strings"
-
- "github.com/google/go-cmp/cmp/internal/diff"
- "github.com/google/go-cmp/cmp/internal/function"
- "github.com/google/go-cmp/cmp/internal/value"
-)
-
-// TODO(≥go1.18): Use any instead of interface{}.
-
-// Equal reports whether x and y are equal by recursively applying the
-// following rules in the given order to x and y and all of their sub-values:
-//
-// - Let S be the set of all Ignore, Transformer, and Comparer options that
-// remain after applying all path filters, value filters, and type filters.
-// If at least one Ignore exists in S, then the comparison is ignored.
-// If the number of Transformer and Comparer options in S is non-zero,
-// then Equal panics because it is ambiguous which option to use.
-// If S contains a single Transformer, then use that to transform
-// the current values and recursively call Equal on the output values.
-// If S contains a single Comparer, then use that to compare the current values.
-// Otherwise, evaluation proceeds to the next rule.
-//
-// - If the values have an Equal method of the form "(T) Equal(T) bool" or
-// "(T) Equal(I) bool" where T is assignable to I, then use the result of
-// x.Equal(y) even if x or y is nil. Otherwise, no such method exists and
-// evaluation proceeds to the next rule.
-//
-// - Lastly, try to compare x and y based on their basic kinds.
-// Simple kinds like booleans, integers, floats, complex numbers, strings,
-// and channels are compared using the equivalent of the == operator in Go.
-// Functions are only equal if they are both nil, otherwise they are unequal.
-//
-// Structs are equal if recursively calling Equal on all fields report equal.
-// If a struct contains unexported fields, Equal panics unless an Ignore option
-// (e.g., cmpopts.IgnoreUnexported) ignores that field or the Exporter option
-// explicitly permits comparing the unexported field.
-//
-// Slices are equal if they are both nil or both non-nil, where recursively
-// calling Equal on all non-ignored slice or array elements report equal.
-// Empty non-nil slices and nil slices are not equal; to equate empty slices,
-// consider using cmpopts.EquateEmpty.
-//
-// Maps are equal if they are both nil or both non-nil, where recursively
-// calling Equal on all non-ignored map entries report equal.
-// Map keys are equal according to the == operator.
-// To use custom comparisons for map keys, consider using cmpopts.SortMaps.
-// Empty non-nil maps and nil maps are not equal; to equate empty maps,
-// consider using cmpopts.EquateEmpty.
-//
-// Pointers and interfaces are equal if they are both nil or both non-nil,
-// where they have the same underlying concrete type and recursively
-// calling Equal on the underlying values reports equal.
-//
-// Before recursing into a pointer, slice element, or map, the current path
-// is checked to detect whether the address has already been visited.
-// If there is a cycle, then the pointed at values are considered equal
-// only if both addresses were previously visited in the same path step.
-func Equal(x, y interface{}, opts ...Option) bool {
- s := newState(opts)
- s.compareAny(rootStep(x, y))
- return s.result.Equal()
-}
-
-// Diff returns a human-readable report of the differences between two values:
-// y - x. It returns an empty string if and only if Equal returns true for the
-// same input values and options.
-//
-// The output is displayed as a literal in pseudo-Go syntax.
-// At the start of each line, a "-" prefix indicates an element removed from x,
-// a "+" prefix to indicates an element added from y, and the lack of a prefix
-// indicates an element common to both x and y. If possible, the output
-// uses fmt.Stringer.String or error.Error methods to produce more humanly
-// readable outputs. In such cases, the string is prefixed with either an
-// 's' or 'e' character, respectively, to indicate that the method was called.
-//
-// Do not depend on this output being stable. If you need the ability to
-// programmatically interpret the difference, consider using a custom Reporter.
-func Diff(x, y interface{}, opts ...Option) string {
- s := newState(opts)
-
- // Optimization: If there are no other reporters, we can optimize for the
- // common case where the result is equal (and thus no reported difference).
- // This avoids the expensive construction of a difference tree.
- if len(s.reporters) == 0 {
- s.compareAny(rootStep(x, y))
- if s.result.Equal() {
- return ""
- }
- s.result = diff.Result{} // Reset results
- }
-
- r := new(defaultReporter)
- s.reporters = append(s.reporters, reporter{r})
- s.compareAny(rootStep(x, y))
- d := r.String()
- if (d == "") != s.result.Equal() {
- panic("inconsistent difference and equality results")
- }
- return d
-}
-
-// rootStep constructs the first path step. If x and y have differing types,
-// then they are stored within an empty interface type.
-func rootStep(x, y interface{}) PathStep {
- vx := reflect.ValueOf(x)
- vy := reflect.ValueOf(y)
-
- // If the inputs are different types, auto-wrap them in an empty interface
- // so that they have the same parent type.
- var t reflect.Type
- if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() {
- t = anyType
- if vx.IsValid() {
- vvx := reflect.New(t).Elem()
- vvx.Set(vx)
- vx = vvx
- }
- if vy.IsValid() {
- vvy := reflect.New(t).Elem()
- vvy.Set(vy)
- vy = vvy
- }
- } else {
- t = vx.Type()
- }
-
- return &pathStep{t, vx, vy}
-}
-
-type state struct {
- // These fields represent the "comparison state".
- // Calling statelessCompare must not result in observable changes to these.
- result diff.Result // The current result of comparison
- curPath Path // The current path in the value tree
- curPtrs pointerPath // The current set of visited pointers
- reporters []reporter // Optional reporters
-
- // recChecker checks for infinite cycles applying the same set of
- // transformers upon the output of itself.
- recChecker recChecker
-
- // dynChecker triggers pseudo-random checks for option correctness.
- // It is safe for statelessCompare to mutate this value.
- dynChecker dynChecker
-
- // These fields, once set by processOption, will not change.
- exporters []exporter // List of exporters for structs with unexported fields
- opts Options // List of all fundamental and filter options
-}
-
-func newState(opts []Option) *state {
- // Always ensure a validator option exists to validate the inputs.
- s := &state{opts: Options{validator{}}}
- s.curPtrs.Init()
- s.processOption(Options(opts))
- return s
-}
-
-func (s *state) processOption(opt Option) {
- switch opt := opt.(type) {
- case nil:
- case Options:
- for _, o := range opt {
- s.processOption(o)
- }
- case coreOption:
- type filtered interface {
- isFiltered() bool
- }
- if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() {
- panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt))
- }
- s.opts = append(s.opts, opt)
- case exporter:
- s.exporters = append(s.exporters, opt)
- case reporter:
- s.reporters = append(s.reporters, opt)
- default:
- panic(fmt.Sprintf("unknown option %T", opt))
- }
-}
-
-// statelessCompare compares two values and returns the result.
-// This function is stateless in that it does not alter the current result,
-// or output to any registered reporters.
-func (s *state) statelessCompare(step PathStep) diff.Result {
- // We do not save and restore curPath and curPtrs because all of the
- // compareX methods should properly push and pop from them.
- // It is an implementation bug if the contents of the paths differ from
- // when calling this function to when returning from it.
-
- oldResult, oldReporters := s.result, s.reporters
- s.result = diff.Result{} // Reset result
- s.reporters = nil // Remove reporters to avoid spurious printouts
- s.compareAny(step)
- res := s.result
- s.result, s.reporters = oldResult, oldReporters
- return res
-}
-
-func (s *state) compareAny(step PathStep) {
- // Update the path stack.
- s.curPath.push(step)
- defer s.curPath.pop()
- for _, r := range s.reporters {
- r.PushStep(step)
- defer r.PopStep()
- }
- s.recChecker.Check(s.curPath)
-
- // Cycle-detection for slice elements (see NOTE in compareSlice).
- t := step.Type()
- vx, vy := step.Values()
- if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() {
- px, py := vx.Addr(), vy.Addr()
- if eq, visited := s.curPtrs.Push(px, py); visited {
- s.report(eq, reportByCycle)
- return
- }
- defer s.curPtrs.Pop(px, py)
- }
-
- // Rule 1: Check whether an option applies on this node in the value tree.
- if s.tryOptions(t, vx, vy) {
- return
- }
-
- // Rule 2: Check whether the type has a valid Equal method.
- if s.tryMethod(t, vx, vy) {
- return
- }
-
- // Rule 3: Compare based on the underlying kind.
- switch t.Kind() {
- case reflect.Bool:
- s.report(vx.Bool() == vy.Bool(), 0)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- s.report(vx.Int() == vy.Int(), 0)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- s.report(vx.Uint() == vy.Uint(), 0)
- case reflect.Float32, reflect.Float64:
- s.report(vx.Float() == vy.Float(), 0)
- case reflect.Complex64, reflect.Complex128:
- s.report(vx.Complex() == vy.Complex(), 0)
- case reflect.String:
- s.report(vx.String() == vy.String(), 0)
- case reflect.Chan, reflect.UnsafePointer:
- s.report(vx.Pointer() == vy.Pointer(), 0)
- case reflect.Func:
- s.report(vx.IsNil() && vy.IsNil(), 0)
- case reflect.Struct:
- s.compareStruct(t, vx, vy)
- case reflect.Slice, reflect.Array:
- s.compareSlice(t, vx, vy)
- case reflect.Map:
- s.compareMap(t, vx, vy)
- case reflect.Ptr:
- s.comparePtr(t, vx, vy)
- case reflect.Interface:
- s.compareInterface(t, vx, vy)
- default:
- panic(fmt.Sprintf("%v kind not handled", t.Kind()))
- }
-}
-
-func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool {
- // Evaluate all filters and apply the remaining options.
- if opt := s.opts.filter(s, t, vx, vy); opt != nil {
- opt.apply(s, vx, vy)
- return true
- }
- return false
-}
-
-func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool {
- // Check if this type even has an Equal method.
- m, ok := t.MethodByName("Equal")
- if !ok || !function.IsType(m.Type, function.EqualAssignable) {
- return false
- }
-
- eq := s.callTTBFunc(m.Func, vx, vy)
- s.report(eq, reportByMethod)
- return true
-}
-
-func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value {
- if !s.dynChecker.Next() {
- return f.Call([]reflect.Value{v})[0]
- }
-
- // Run the function twice and ensure that we get the same results back.
- // We run in goroutines so that the race detector (if enabled) can detect
- // unsafe mutations to the input.
- c := make(chan reflect.Value)
- go detectRaces(c, f, v)
- got := <-c
- want := f.Call([]reflect.Value{v})[0]
- if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() {
- // To avoid false-positives with non-reflexive equality operations,
- // we sanity check whether a value is equal to itself.
- if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() {
- return want
- }
- panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f)))
- }
- return want
-}
-
-func (s *state) callTTBFunc(f, x, y reflect.Value) bool {
- if !s.dynChecker.Next() {
- return f.Call([]reflect.Value{x, y})[0].Bool()
- }
-
- // Swapping the input arguments is sufficient to check that
- // f is symmetric and deterministic.
- // We run in goroutines so that the race detector (if enabled) can detect
- // unsafe mutations to the input.
- c := make(chan reflect.Value)
- go detectRaces(c, f, y, x)
- got := <-c
- want := f.Call([]reflect.Value{x, y})[0].Bool()
- if !got.IsValid() || got.Bool() != want {
- panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f)))
- }
- return want
-}
-
-func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) {
- var ret reflect.Value
- defer func() {
- recover() // Ignore panics, let the other call to f panic instead
- c <- ret
- }()
- ret = f.Call(vs)[0]
-}
-
-func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) {
- var addr bool
- var vax, vay reflect.Value // Addressable versions of vx and vy
-
- var mayForce, mayForceInit bool
- step := StructField{&structField{}}
- for i := 0; i < t.NumField(); i++ {
- step.typ = t.Field(i).Type
- step.vx = vx.Field(i)
- step.vy = vy.Field(i)
- step.name = t.Field(i).Name
- step.idx = i
- step.unexported = !isExported(step.name)
- if step.unexported {
- if step.name == "_" {
- continue
- }
- // Defer checking of unexported fields until later to give an
- // Ignore a chance to ignore the field.
- if !vax.IsValid() || !vay.IsValid() {
- // For retrieveUnexportedField to work, the parent struct must
- // be addressable. Create a new copy of the values if
- // necessary to make them addressable.
- addr = vx.CanAddr() || vy.CanAddr()
- vax = makeAddressable(vx)
- vay = makeAddressable(vy)
- }
- if !mayForceInit {
- for _, xf := range s.exporters {
- mayForce = mayForce || xf(t)
- }
- mayForceInit = true
- }
- step.mayForce = mayForce
- step.paddr = addr
- step.pvx = vax
- step.pvy = vay
- step.field = t.Field(i)
- }
- s.compareAny(step)
- }
-}
-
-func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) {
- isSlice := t.Kind() == reflect.Slice
- if isSlice && (vx.IsNil() || vy.IsNil()) {
- s.report(vx.IsNil() && vy.IsNil(), 0)
- return
- }
-
- // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer
- // since slices represents a list of pointers, rather than a single pointer.
- // The pointer checking logic must be handled on a per-element basis
- // in compareAny.
- //
- // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting
- // pointer P, a length N, and a capacity C. Supposing each slice element has
- // a memory size of M, then the slice is equivalent to the list of pointers:
- // [P+i*M for i in range(N)]
- //
- // For example, v[:0] and v[:1] are slices with the same starting pointer,
- // but they are clearly different values. Using the slice pointer alone
- // violates the assumption that equal pointers implies equal values.
-
- step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}}
- withIndexes := func(ix, iy int) SliceIndex {
- if ix >= 0 {
- step.vx, step.xkey = vx.Index(ix), ix
- } else {
- step.vx, step.xkey = reflect.Value{}, -1
- }
- if iy >= 0 {
- step.vy, step.ykey = vy.Index(iy), iy
- } else {
- step.vy, step.ykey = reflect.Value{}, -1
- }
- return step
- }
-
- // Ignore options are able to ignore missing elements in a slice.
- // However, detecting these reliably requires an optimal differencing
- // algorithm, for which diff.Difference is not.
- //
- // Instead, we first iterate through both slices to detect which elements
- // would be ignored if standing alone. The index of non-discarded elements
- // are stored in a separate slice, which diffing is then performed on.
- var indexesX, indexesY []int
- var ignoredX, ignoredY []bool
- for ix := 0; ix < vx.Len(); ix++ {
- ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0
- if !ignored {
- indexesX = append(indexesX, ix)
- }
- ignoredX = append(ignoredX, ignored)
- }
- for iy := 0; iy < vy.Len(); iy++ {
- ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0
- if !ignored {
- indexesY = append(indexesY, iy)
- }
- ignoredY = append(ignoredY, ignored)
- }
-
- // Compute an edit-script for slices vx and vy (excluding ignored elements).
- edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result {
- return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy]))
- })
-
- // Replay the ignore-scripts and the edit-script.
- var ix, iy int
- for ix < vx.Len() || iy < vy.Len() {
- var e diff.EditType
- switch {
- case ix < len(ignoredX) && ignoredX[ix]:
- e = diff.UniqueX
- case iy < len(ignoredY) && ignoredY[iy]:
- e = diff.UniqueY
- default:
- e, edits = edits[0], edits[1:]
- }
- switch e {
- case diff.UniqueX:
- s.compareAny(withIndexes(ix, -1))
- ix++
- case diff.UniqueY:
- s.compareAny(withIndexes(-1, iy))
- iy++
- default:
- s.compareAny(withIndexes(ix, iy))
- ix++
- iy++
- }
- }
-}
-
-func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) {
- if vx.IsNil() || vy.IsNil() {
- s.report(vx.IsNil() && vy.IsNil(), 0)
- return
- }
-
- // Cycle-detection for maps.
- if eq, visited := s.curPtrs.Push(vx, vy); visited {
- s.report(eq, reportByCycle)
- return
- }
- defer s.curPtrs.Pop(vx, vy)
-
- // We combine and sort the two map keys so that we can perform the
- // comparisons in a deterministic order.
- step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}}
- for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) {
- step.vx = vx.MapIndex(k)
- step.vy = vy.MapIndex(k)
- step.key = k
- if !step.vx.IsValid() && !step.vy.IsValid() {
- // It is possible for both vx and vy to be invalid if the
- // key contained a NaN value in it.
- //
- // Even with the ability to retrieve NaN keys in Go 1.12,
- // there still isn't a sensible way to compare the values since
- // a NaN key may map to multiple unordered values.
- // The most reasonable way to compare NaNs would be to compare the
- // set of values. However, this is impossible to do efficiently
- // since set equality is provably an O(n^2) operation given only
- // an Equal function. If we had a Less function or Hash function,
- // this could be done in O(n*log(n)) or O(n), respectively.
- //
- // Rather than adding complex logic to deal with NaNs, make it
- // the user's responsibility to compare such obscure maps.
- const help = "consider providing a Comparer to compare the map"
- panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help))
- }
- s.compareAny(step)
- }
-}
-
-func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) {
- if vx.IsNil() || vy.IsNil() {
- s.report(vx.IsNil() && vy.IsNil(), 0)
- return
- }
-
- // Cycle-detection for pointers.
- if eq, visited := s.curPtrs.Push(vx, vy); visited {
- s.report(eq, reportByCycle)
- return
- }
- defer s.curPtrs.Pop(vx, vy)
-
- vx, vy = vx.Elem(), vy.Elem()
- s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}})
-}
-
-func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) {
- if vx.IsNil() || vy.IsNil() {
- s.report(vx.IsNil() && vy.IsNil(), 0)
- return
- }
- vx, vy = vx.Elem(), vy.Elem()
- if vx.Type() != vy.Type() {
- s.report(false, 0)
- return
- }
- s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}})
-}
-
-func (s *state) report(eq bool, rf resultFlags) {
- if rf&reportByIgnore == 0 {
- if eq {
- s.result.NumSame++
- rf |= reportEqual
- } else {
- s.result.NumDiff++
- rf |= reportUnequal
- }
- }
- for _, r := range s.reporters {
- r.Report(Result{flags: rf})
- }
-}
-
-// recChecker tracks the state needed to periodically perform checks that
-// user provided transformers are not stuck in an infinitely recursive cycle.
-type recChecker struct{ next int }
-
-// Check scans the Path for any recursive transformers and panics when any
-// recursive transformers are detected. Note that the presence of a
-// recursive Transformer does not necessarily imply an infinite cycle.
-// As such, this check only activates after some minimal number of path steps.
-func (rc *recChecker) Check(p Path) {
- const minLen = 1 << 16
- if rc.next == 0 {
- rc.next = minLen
- }
- if len(p) < rc.next {
- return
- }
- rc.next <<= 1
-
- // Check whether the same transformer has appeared at least twice.
- var ss []string
- m := map[Option]int{}
- for _, ps := range p {
- if t, ok := ps.(Transform); ok {
- t := t.Option()
- if m[t] == 1 { // Transformer was used exactly once before
- tf := t.(*transformer).fnc.Type()
- ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))
- }
- m[t]++
- }
- }
- if len(ss) > 0 {
- const warning = "recursive set of Transformers detected"
- const help = "consider using cmpopts.AcyclicTransformer"
- set := strings.Join(ss, "\n\t")
- panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))
- }
-}
-
-// dynChecker tracks the state needed to periodically perform checks that
-// user provided functions are symmetric and deterministic.
-// The zero value is safe for immediate use.
-type dynChecker struct{ curr, next int }
-
-// Next increments the state and reports whether a check should be performed.
-//
-// Checks occur every Nth function call, where N is a triangular number:
-//
-// 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ...
-//
-// See https://en.wikipedia.org/wiki/Triangular_number
-//
-// This sequence ensures that the cost of checks drops significantly as
-// the number of functions calls grows larger.
-func (dc *dynChecker) Next() bool {
- ok := dc.curr == dc.next
- if ok {
- dc.curr = 0
- dc.next++
- }
- dc.curr++
- return ok
-}
-
-// makeAddressable returns a value that is always addressable.
-// It returns the input verbatim if it is already addressable,
-// otherwise it creates a new value and returns an addressable copy.
-func makeAddressable(v reflect.Value) reflect.Value {
- if v.CanAddr() {
- return v
- }
- vc := reflect.New(v.Type()).Elem()
- vc.Set(v)
- return vc
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/export_panic.go b/vendor/github.com/google/go-cmp/cmp/export_panic.go
deleted file mode 100644
index ae851fe..0000000
--- a/vendor/github.com/google/go-cmp/cmp/export_panic.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//go:build purego
-// +build purego
-
-package cmp
-
-import "reflect"
-
-const supportExporters = false
-
-func retrieveUnexportedField(reflect.Value, reflect.StructField, bool) reflect.Value {
- panic("no support for forcibly accessing unexported fields")
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go b/vendor/github.com/google/go-cmp/cmp/export_unsafe.go
deleted file mode 100644
index e2c0f74..0000000
--- a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//go:build !purego
-// +build !purego
-
-package cmp
-
-import (
- "reflect"
- "unsafe"
-)
-
-const supportExporters = true
-
-// retrieveUnexportedField uses unsafe to forcibly retrieve any field from
-// a struct such that the value has read-write permissions.
-//
-// The parent struct, v, must be addressable, while f must be a StructField
-// describing the field to retrieve. If addr is false,
-// then the returned value will be shallowed copied to be non-addressable.
-func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value {
- ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem()
- if !addr {
- // A field is addressable if and only if the struct is addressable.
- // If the original parent value was not addressable, shallow copy the
- // value to make it non-addressable to avoid leaking an implementation
- // detail of how forcibly exporting a field works.
- if ve.Kind() == reflect.Interface && ve.IsNil() {
- return reflect.Zero(f.Type)
- }
- return reflect.ValueOf(ve.Interface()).Convert(f.Type)
- }
- return ve
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go
deleted file mode 100644
index 36062a6..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//go:build !cmp_debug
-// +build !cmp_debug
-
-package diff
-
-var debug debugger
-
-type debugger struct{}
-
-func (debugger) Begin(_, _ int, f EqualFunc, _, _ *EditScript) EqualFunc {
- return f
-}
-func (debugger) Update() {}
-func (debugger) Finish() {}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go
deleted file mode 100644
index a3b97a1..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//go:build cmp_debug
-// +build cmp_debug
-
-package diff
-
-import (
- "fmt"
- "strings"
- "sync"
- "time"
-)
-
-// The algorithm can be seen running in real-time by enabling debugging:
-// go test -tags=cmp_debug -v
-//
-// Example output:
-// === RUN TestDifference/#34
-// ┌───────────────────────────────┐
-// │ \ · · · · · · · · · · · · · · │
-// │ · # · · · · · · · · · · · · · │
-// │ · \ · · · · · · · · · · · · · │
-// │ · · \ · · · · · · · · · · · · │
-// │ · · · X # · · · · · · · · · · │
-// │ · · · # \ · · · · · · · · · · │
-// │ · · · · · # # · · · · · · · · │
-// │ · · · · · # \ · · · · · · · · │
-// │ · · · · · · · \ · · · · · · · │
-// │ · · · · · · · · \ · · · · · · │
-// │ · · · · · · · · · \ · · · · · │
-// │ · · · · · · · · · · \ · · # · │
-// │ · · · · · · · · · · · \ # # · │
-// │ · · · · · · · · · · · # # # · │
-// │ · · · · · · · · · · # # # # · │
-// │ · · · · · · · · · # # # # # · │
-// │ · · · · · · · · · · · · · · \ │
-// └───────────────────────────────┘
-// [.Y..M.XY......YXYXY.|]
-//
-// The grid represents the edit-graph where the horizontal axis represents
-// list X and the vertical axis represents list Y. The start of the two lists
-// is the top-left, while the ends are the bottom-right. The '·' represents
-// an unexplored node in the graph. The '\' indicates that the two symbols
-// from list X and Y are equal. The 'X' indicates that two symbols are similar
-// (but not exactly equal) to each other. The '#' indicates that the two symbols
-// are different (and not similar). The algorithm traverses this graph trying to
-// make the paths starting in the top-left and the bottom-right connect.
-//
-// The series of '.', 'X', 'Y', and 'M' characters at the bottom represents
-// the currently established path from the forward and reverse searches,
-// separated by a '|' character.
-
-const (
- updateDelay = 100 * time.Millisecond
- finishDelay = 500 * time.Millisecond
- ansiTerminal = true // ANSI escape codes used to move terminal cursor
-)
-
-var debug debugger
-
-type debugger struct {
- sync.Mutex
- p1, p2 EditScript
- fwdPath, revPath *EditScript
- grid []byte
- lines int
-}
-
-func (dbg *debugger) Begin(nx, ny int, f EqualFunc, p1, p2 *EditScript) EqualFunc {
- dbg.Lock()
- dbg.fwdPath, dbg.revPath = p1, p2
- top := "┌─" + strings.Repeat("──", nx) + "┐\n"
- row := "│ " + strings.Repeat("· ", nx) + "│\n"
- btm := "└─" + strings.Repeat("──", nx) + "┘\n"
- dbg.grid = []byte(top + strings.Repeat(row, ny) + btm)
- dbg.lines = strings.Count(dbg.String(), "\n")
- fmt.Print(dbg)
-
- // Wrap the EqualFunc so that we can intercept each result.
- return func(ix, iy int) (r Result) {
- cell := dbg.grid[len(top)+iy*len(row):][len("│ ")+len("· ")*ix:][:len("·")]
- for i := range cell {
- cell[i] = 0 // Zero out the multiple bytes of UTF-8 middle-dot
- }
- switch r = f(ix, iy); {
- case r.Equal():
- cell[0] = '\\'
- case r.Similar():
- cell[0] = 'X'
- default:
- cell[0] = '#'
- }
- return
- }
-}
-
-func (dbg *debugger) Update() {
- dbg.print(updateDelay)
-}
-
-func (dbg *debugger) Finish() {
- dbg.print(finishDelay)
- dbg.Unlock()
-}
-
-func (dbg *debugger) String() string {
- dbg.p1, dbg.p2 = *dbg.fwdPath, dbg.p2[:0]
- for i := len(*dbg.revPath) - 1; i >= 0; i-- {
- dbg.p2 = append(dbg.p2, (*dbg.revPath)[i])
- }
- return fmt.Sprintf("%s[%v|%v]\n\n", dbg.grid, dbg.p1, dbg.p2)
-}
-
-func (dbg *debugger) print(d time.Duration) {
- if ansiTerminal {
- fmt.Printf("\x1b[%dA", dbg.lines) // Reset terminal cursor
- }
- fmt.Print(dbg)
- time.Sleep(d)
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go
deleted file mode 100644
index a248e54..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go
+++ /dev/null
@@ -1,402 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package diff implements an algorithm for producing edit-scripts.
-// The edit-script is a sequence of operations needed to transform one list
-// of symbols into another (or vice-versa). The edits allowed are insertions,
-// deletions, and modifications. The summation of all edits is called the
-// Levenshtein distance as this problem is well-known in computer science.
-//
-// This package prioritizes performance over accuracy. That is, the run time
-// is more important than obtaining a minimal Levenshtein distance.
-package diff
-
-import (
- "math/rand"
- "time"
-
- "github.com/google/go-cmp/cmp/internal/flags"
-)
-
-// EditType represents a single operation within an edit-script.
-type EditType uint8
-
-const (
- // Identity indicates that a symbol pair is identical in both list X and Y.
- Identity EditType = iota
- // UniqueX indicates that a symbol only exists in X and not Y.
- UniqueX
- // UniqueY indicates that a symbol only exists in Y and not X.
- UniqueY
- // Modified indicates that a symbol pair is a modification of each other.
- Modified
-)
-
-// EditScript represents the series of differences between two lists.
-type EditScript []EditType
-
-// String returns a human-readable string representing the edit-script where
-// Identity, UniqueX, UniqueY, and Modified are represented by the
-// '.', 'X', 'Y', and 'M' characters, respectively.
-func (es EditScript) String() string {
- b := make([]byte, len(es))
- for i, e := range es {
- switch e {
- case Identity:
- b[i] = '.'
- case UniqueX:
- b[i] = 'X'
- case UniqueY:
- b[i] = 'Y'
- case Modified:
- b[i] = 'M'
- default:
- panic("invalid edit-type")
- }
- }
- return string(b)
-}
-
-// stats returns a histogram of the number of each type of edit operation.
-func (es EditScript) stats() (s struct{ NI, NX, NY, NM int }) {
- for _, e := range es {
- switch e {
- case Identity:
- s.NI++
- case UniqueX:
- s.NX++
- case UniqueY:
- s.NY++
- case Modified:
- s.NM++
- default:
- panic("invalid edit-type")
- }
- }
- return
-}
-
-// Dist is the Levenshtein distance and is guaranteed to be 0 if and only if
-// lists X and Y are equal.
-func (es EditScript) Dist() int { return len(es) - es.stats().NI }
-
-// LenX is the length of the X list.
-func (es EditScript) LenX() int { return len(es) - es.stats().NY }
-
-// LenY is the length of the Y list.
-func (es EditScript) LenY() int { return len(es) - es.stats().NX }
-
-// EqualFunc reports whether the symbols at indexes ix and iy are equal.
-// When called by Difference, the index is guaranteed to be within nx and ny.
-type EqualFunc func(ix int, iy int) Result
-
-// Result is the result of comparison.
-// NumSame is the number of sub-elements that are equal.
-// NumDiff is the number of sub-elements that are not equal.
-type Result struct{ NumSame, NumDiff int }
-
-// BoolResult returns a Result that is either Equal or not Equal.
-func BoolResult(b bool) Result {
- if b {
- return Result{NumSame: 1} // Equal, Similar
- } else {
- return Result{NumDiff: 2} // Not Equal, not Similar
- }
-}
-
-// Equal indicates whether the symbols are equal. Two symbols are equal
-// if and only if NumDiff == 0. If Equal, then they are also Similar.
-func (r Result) Equal() bool { return r.NumDiff == 0 }
-
-// Similar indicates whether two symbols are similar and may be represented
-// by using the Modified type. As a special case, we consider binary comparisons
-// (i.e., those that return Result{1, 0} or Result{0, 1}) to be similar.
-//
-// The exact ratio of NumSame to NumDiff to determine similarity may change.
-func (r Result) Similar() bool {
- // Use NumSame+1 to offset NumSame so that binary comparisons are similar.
- return r.NumSame+1 >= r.NumDiff
-}
-
-var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0
-
-// Difference reports whether two lists of lengths nx and ny are equal
-// given the definition of equality provided as f.
-//
-// This function returns an edit-script, which is a sequence of operations
-// needed to convert one list into the other. The following invariants for
-// the edit-script are maintained:
-// - eq == (es.Dist()==0)
-// - nx == es.LenX()
-// - ny == es.LenY()
-//
-// This algorithm is not guaranteed to be an optimal solution (i.e., one that
-// produces an edit-script with a minimal Levenshtein distance). This algorithm
-// favors performance over optimality. The exact output is not guaranteed to
-// be stable and may change over time.
-func Difference(nx, ny int, f EqualFunc) (es EditScript) {
- // This algorithm is based on traversing what is known as an "edit-graph".
- // See Figure 1 from "An O(ND) Difference Algorithm and Its Variations"
- // by Eugene W. Myers. Since D can be as large as N itself, this is
- // effectively O(N^2). Unlike the algorithm from that paper, we are not
- // interested in the optimal path, but at least some "decent" path.
- //
- // For example, let X and Y be lists of symbols:
- // X = [A B C A B B A]
- // Y = [C B A B A C]
- //
- // The edit-graph can be drawn as the following:
- // A B C A B B A
- // ┌─────────────┐
- // C │_|_|\|_|_|_|_│ 0
- // B │_|\|_|_|\|\|_│ 1
- // A │\|_|_|\|_|_|\│ 2
- // B │_|\|_|_|\|\|_│ 3
- // A │\|_|_|\|_|_|\│ 4
- // C │ | |\| | | | │ 5
- // └─────────────┘ 6
- // 0 1 2 3 4 5 6 7
- //
- // List X is written along the horizontal axis, while list Y is written
- // along the vertical axis. At any point on this grid, if the symbol in
- // list X matches the corresponding symbol in list Y, then a '\' is drawn.
- // The goal of any minimal edit-script algorithm is to find a path from the
- // top-left corner to the bottom-right corner, while traveling through the
- // fewest horizontal or vertical edges.
- // A horizontal edge is equivalent to inserting a symbol from list X.
- // A vertical edge is equivalent to inserting a symbol from list Y.
- // A diagonal edge is equivalent to a matching symbol between both X and Y.
-
- // Invariants:
- // - 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx
- // - 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny
- //
- // In general:
- // - fwdFrontier.X < revFrontier.X
- // - fwdFrontier.Y < revFrontier.Y
- //
- // Unless, it is time for the algorithm to terminate.
- fwdPath := path{+1, point{0, 0}, make(EditScript, 0, (nx+ny)/2)}
- revPath := path{-1, point{nx, ny}, make(EditScript, 0)}
- fwdFrontier := fwdPath.point // Forward search frontier
- revFrontier := revPath.point // Reverse search frontier
-
- // Search budget bounds the cost of searching for better paths.
- // The longest sequence of non-matching symbols that can be tolerated is
- // approximately the square-root of the search budget.
- searchBudget := 4 * (nx + ny) // O(n)
-
- // Running the tests with the "cmp_debug" build tag prints a visualization
- // of the algorithm running in real-time. This is educational for
- // understanding how the algorithm works. See debug_enable.go.
- f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es)
-
- // The algorithm below is a greedy, meet-in-the-middle algorithm for
- // computing sub-optimal edit-scripts between two lists.
- //
- // The algorithm is approximately as follows:
- // - Searching for differences switches back-and-forth between
- // a search that starts at the beginning (the top-left corner), and
- // a search that starts at the end (the bottom-right corner).
- // The goal of the search is connect with the search
- // from the opposite corner.
- // - As we search, we build a path in a greedy manner,
- // where the first match seen is added to the path (this is sub-optimal,
- // but provides a decent result in practice). When matches are found,
- // we try the next pair of symbols in the lists and follow all matches
- // as far as possible.
- // - When searching for matches, we search along a diagonal going through
- // through the "frontier" point. If no matches are found,
- // we advance the frontier towards the opposite corner.
- // - This algorithm terminates when either the X coordinates or the
- // Y coordinates of the forward and reverse frontier points ever intersect.
-
- // This algorithm is correct even if searching only in the forward direction
- // or in the reverse direction. We do both because it is commonly observed
- // that two lists commonly differ because elements were added to the front
- // or end of the other list.
- //
- // Non-deterministically start with either the forward or reverse direction
- // to introduce some deliberate instability so that we have the flexibility
- // to change this algorithm in the future.
- if flags.Deterministic || randBool {
- goto forwardSearch
- } else {
- goto reverseSearch
- }
-
-forwardSearch:
- {
- // Forward search from the beginning.
- if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {
- goto finishSearch
- }
- for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {
- // Search in a diagonal pattern for a match.
- z := zigzag(i)
- p := point{fwdFrontier.X + z, fwdFrontier.Y - z}
- switch {
- case p.X >= revPath.X || p.Y < fwdPath.Y:
- stop1 = true // Hit top-right corner
- case p.Y >= revPath.Y || p.X < fwdPath.X:
- stop2 = true // Hit bottom-left corner
- case f(p.X, p.Y).Equal():
- // Match found, so connect the path to this point.
- fwdPath.connect(p, f)
- fwdPath.append(Identity)
- // Follow sequence of matches as far as possible.
- for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {
- if !f(fwdPath.X, fwdPath.Y).Equal() {
- break
- }
- fwdPath.append(Identity)
- }
- fwdFrontier = fwdPath.point
- stop1, stop2 = true, true
- default:
- searchBudget-- // Match not found
- }
- debug.Update()
- }
- // Advance the frontier towards reverse point.
- if revPath.X-fwdFrontier.X >= revPath.Y-fwdFrontier.Y {
- fwdFrontier.X++
- } else {
- fwdFrontier.Y++
- }
- goto reverseSearch
- }
-
-reverseSearch:
- {
- // Reverse search from the end.
- if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {
- goto finishSearch
- }
- for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {
- // Search in a diagonal pattern for a match.
- z := zigzag(i)
- p := point{revFrontier.X - z, revFrontier.Y + z}
- switch {
- case fwdPath.X >= p.X || revPath.Y < p.Y:
- stop1 = true // Hit bottom-left corner
- case fwdPath.Y >= p.Y || revPath.X < p.X:
- stop2 = true // Hit top-right corner
- case f(p.X-1, p.Y-1).Equal():
- // Match found, so connect the path to this point.
- revPath.connect(p, f)
- revPath.append(Identity)
- // Follow sequence of matches as far as possible.
- for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {
- if !f(revPath.X-1, revPath.Y-1).Equal() {
- break
- }
- revPath.append(Identity)
- }
- revFrontier = revPath.point
- stop1, stop2 = true, true
- default:
- searchBudget-- // Match not found
- }
- debug.Update()
- }
- // Advance the frontier towards forward point.
- if revFrontier.X-fwdPath.X >= revFrontier.Y-fwdPath.Y {
- revFrontier.X--
- } else {
- revFrontier.Y--
- }
- goto forwardSearch
- }
-
-finishSearch:
- // Join the forward and reverse paths and then append the reverse path.
- fwdPath.connect(revPath.point, f)
- for i := len(revPath.es) - 1; i >= 0; i-- {
- t := revPath.es[i]
- revPath.es = revPath.es[:i]
- fwdPath.append(t)
- }
- debug.Finish()
- return fwdPath.es
-}
-
-type path struct {
- dir int // +1 if forward, -1 if reverse
- point // Leading point of the EditScript path
- es EditScript
-}
-
-// connect appends any necessary Identity, Modified, UniqueX, or UniqueY types
-// to the edit-script to connect p.point to dst.
-func (p *path) connect(dst point, f EqualFunc) {
- if p.dir > 0 {
- // Connect in forward direction.
- for dst.X > p.X && dst.Y > p.Y {
- switch r := f(p.X, p.Y); {
- case r.Equal():
- p.append(Identity)
- case r.Similar():
- p.append(Modified)
- case dst.X-p.X >= dst.Y-p.Y:
- p.append(UniqueX)
- default:
- p.append(UniqueY)
- }
- }
- for dst.X > p.X {
- p.append(UniqueX)
- }
- for dst.Y > p.Y {
- p.append(UniqueY)
- }
- } else {
- // Connect in reverse direction.
- for p.X > dst.X && p.Y > dst.Y {
- switch r := f(p.X-1, p.Y-1); {
- case r.Equal():
- p.append(Identity)
- case r.Similar():
- p.append(Modified)
- case p.Y-dst.Y >= p.X-dst.X:
- p.append(UniqueY)
- default:
- p.append(UniqueX)
- }
- }
- for p.X > dst.X {
- p.append(UniqueX)
- }
- for p.Y > dst.Y {
- p.append(UniqueY)
- }
- }
-}
-
-func (p *path) append(t EditType) {
- p.es = append(p.es, t)
- switch t {
- case Identity, Modified:
- p.add(p.dir, p.dir)
- case UniqueX:
- p.add(p.dir, 0)
- case UniqueY:
- p.add(0, p.dir)
- }
- debug.Update()
-}
-
-type point struct{ X, Y int }
-
-func (p *point) add(dx, dy int) { p.X += dx; p.Y += dy }
-
-// zigzag maps a consecutive sequence of integers to a zig-zag sequence.
-//
-// [0 1 2 3 4 5 ...] => [0 -1 +1 -2 +2 ...]
-func zigzag(x int) int {
- if x&1 != 0 {
- x = ^x
- }
- return x >> 1
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go b/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go
deleted file mode 100644
index d8e459c..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2019, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package flags
-
-// Deterministic controls whether the output of Diff should be deterministic.
-// This is only used for testing.
-var Deterministic bool
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/function/func.go b/vendor/github.com/google/go-cmp/cmp/internal/function/func.go
deleted file mode 100644
index d127d43..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/function/func.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package function provides functionality for identifying function types.
-package function
-
-import (
- "reflect"
- "regexp"
- "runtime"
- "strings"
-)
-
-type funcType int
-
-const (
- _ funcType = iota
-
- tbFunc // func(T) bool
- ttbFunc // func(T, T) bool
- trbFunc // func(T, R) bool
- tibFunc // func(T, I) bool
- trFunc // func(T) R
-
- Equal = ttbFunc // func(T, T) bool
- EqualAssignable = tibFunc // func(T, I) bool; encapsulates func(T, T) bool
- Transformer = trFunc // func(T) R
- ValueFilter = ttbFunc // func(T, T) bool
- Less = ttbFunc // func(T, T) bool
- ValuePredicate = tbFunc // func(T) bool
- KeyValuePredicate = trbFunc // func(T, R) bool
-)
-
-var boolType = reflect.TypeOf(true)
-
-// IsType reports whether the reflect.Type is of the specified function type.
-func IsType(t reflect.Type, ft funcType) bool {
- if t == nil || t.Kind() != reflect.Func || t.IsVariadic() {
- return false
- }
- ni, no := t.NumIn(), t.NumOut()
- switch ft {
- case tbFunc: // func(T) bool
- if ni == 1 && no == 1 && t.Out(0) == boolType {
- return true
- }
- case ttbFunc: // func(T, T) bool
- if ni == 2 && no == 1 && t.In(0) == t.In(1) && t.Out(0) == boolType {
- return true
- }
- case trbFunc: // func(T, R) bool
- if ni == 2 && no == 1 && t.Out(0) == boolType {
- return true
- }
- case tibFunc: // func(T, I) bool
- if ni == 2 && no == 1 && t.In(0).AssignableTo(t.In(1)) && t.Out(0) == boolType {
- return true
- }
- case trFunc: // func(T) R
- if ni == 1 && no == 1 {
- return true
- }
- }
- return false
-}
-
-var lastIdentRx = regexp.MustCompile(`[_\p{L}][_\p{L}\p{N}]*$`)
-
-// NameOf returns the name of the function value.
-func NameOf(v reflect.Value) string {
- fnc := runtime.FuncForPC(v.Pointer())
- if fnc == nil {
- return "<unknown>"
- }
- fullName := fnc.Name() // e.g., "long/path/name/mypkg.(*MyType).(long/path/name/mypkg.myMethod)-fm"
-
- // Method closures have a "-fm" suffix.
- fullName = strings.TrimSuffix(fullName, "-fm")
-
- var name string
- for len(fullName) > 0 {
- inParen := strings.HasSuffix(fullName, ")")
- fullName = strings.TrimSuffix(fullName, ")")
-
- s := lastIdentRx.FindString(fullName)
- if s == "" {
- break
- }
- name = s + "." + name
- fullName = strings.TrimSuffix(fullName, s)
-
- if i := strings.LastIndexByte(fullName, '('); inParen && i >= 0 {
- fullName = fullName[:i]
- }
- fullName = strings.TrimSuffix(fullName, ".")
- }
- return strings.TrimSuffix(name, ".")
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/name.go b/vendor/github.com/google/go-cmp/cmp/internal/value/name.go
deleted file mode 100644
index 7b498bb..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/value/name.go
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright 2020, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package value
-
-import (
- "reflect"
- "strconv"
-)
-
-var anyType = reflect.TypeOf((*interface{})(nil)).Elem()
-
-// TypeString is nearly identical to reflect.Type.String,
-// but has an additional option to specify that full type names be used.
-func TypeString(t reflect.Type, qualified bool) string {
- return string(appendTypeName(nil, t, qualified, false))
-}
-
-func appendTypeName(b []byte, t reflect.Type, qualified, elideFunc bool) []byte {
- // BUG: Go reflection provides no way to disambiguate two named types
- // of the same name and within the same package,
- // but declared within the namespace of different functions.
-
- // Use the "any" alias instead of "interface{}" for better readability.
- if t == anyType {
- return append(b, "any"...)
- }
-
- // Named type.
- if t.Name() != "" {
- if qualified && t.PkgPath() != "" {
- b = append(b, '"')
- b = append(b, t.PkgPath()...)
- b = append(b, '"')
- b = append(b, '.')
- b = append(b, t.Name()...)
- } else {
- b = append(b, t.String()...)
- }
- return b
- }
-
- // Unnamed type.
- switch k := t.Kind(); k {
- case reflect.Bool, reflect.String, reflect.UnsafePointer,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
- reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
- b = append(b, k.String()...)
- case reflect.Chan:
- if t.ChanDir() == reflect.RecvDir {
- b = append(b, "<-"...)
- }
- b = append(b, "chan"...)
- if t.ChanDir() == reflect.SendDir {
- b = append(b, "<-"...)
- }
- b = append(b, ' ')
- b = appendTypeName(b, t.Elem(), qualified, false)
- case reflect.Func:
- if !elideFunc {
- b = append(b, "func"...)
- }
- b = append(b, '(')
- for i := 0; i < t.NumIn(); i++ {
- if i > 0 {
- b = append(b, ", "...)
- }
- if i == t.NumIn()-1 && t.IsVariadic() {
- b = append(b, "..."...)
- b = appendTypeName(b, t.In(i).Elem(), qualified, false)
- } else {
- b = appendTypeName(b, t.In(i), qualified, false)
- }
- }
- b = append(b, ')')
- switch t.NumOut() {
- case 0:
- // Do nothing
- case 1:
- b = append(b, ' ')
- b = appendTypeName(b, t.Out(0), qualified, false)
- default:
- b = append(b, " ("...)
- for i := 0; i < t.NumOut(); i++ {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = appendTypeName(b, t.Out(i), qualified, false)
- }
- b = append(b, ')')
- }
- case reflect.Struct:
- b = append(b, "struct{ "...)
- for i := 0; i < t.NumField(); i++ {
- if i > 0 {
- b = append(b, "; "...)
- }
- sf := t.Field(i)
- if !sf.Anonymous {
- if qualified && sf.PkgPath != "" {
- b = append(b, '"')
- b = append(b, sf.PkgPath...)
- b = append(b, '"')
- b = append(b, '.')
- }
- b = append(b, sf.Name...)
- b = append(b, ' ')
- }
- b = appendTypeName(b, sf.Type, qualified, false)
- if sf.Tag != "" {
- b = append(b, ' ')
- b = strconv.AppendQuote(b, string(sf.Tag))
- }
- }
- if b[len(b)-1] == ' ' {
- b = b[:len(b)-1]
- } else {
- b = append(b, ' ')
- }
- b = append(b, '}')
- case reflect.Slice, reflect.Array:
- b = append(b, '[')
- if k == reflect.Array {
- b = strconv.AppendUint(b, uint64(t.Len()), 10)
- }
- b = append(b, ']')
- b = appendTypeName(b, t.Elem(), qualified, false)
- case reflect.Map:
- b = append(b, "map["...)
- b = appendTypeName(b, t.Key(), qualified, false)
- b = append(b, ']')
- b = appendTypeName(b, t.Elem(), qualified, false)
- case reflect.Ptr:
- b = append(b, '*')
- b = appendTypeName(b, t.Elem(), qualified, false)
- case reflect.Interface:
- b = append(b, "interface{ "...)
- for i := 0; i < t.NumMethod(); i++ {
- if i > 0 {
- b = append(b, "; "...)
- }
- m := t.Method(i)
- if qualified && m.PkgPath != "" {
- b = append(b, '"')
- b = append(b, m.PkgPath...)
- b = append(b, '"')
- b = append(b, '.')
- }
- b = append(b, m.Name...)
- b = appendTypeName(b, m.Type, qualified, true)
- }
- if b[len(b)-1] == ' ' {
- b = b[:len(b)-1]
- } else {
- b = append(b, ' ')
- }
- b = append(b, '}')
- default:
- panic("invalid kind: " + k.String())
- }
- return b
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go
deleted file mode 100644
index 1a71bfc..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2018, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//go:build purego
-// +build purego
-
-package value
-
-import "reflect"
-
-// Pointer is an opaque typed pointer and is guaranteed to be comparable.
-type Pointer struct {
- p uintptr
- t reflect.Type
-}
-
-// PointerOf returns a Pointer from v, which must be a
-// reflect.Ptr, reflect.Slice, or reflect.Map.
-func PointerOf(v reflect.Value) Pointer {
- // NOTE: Storing a pointer as an uintptr is technically incorrect as it
- // assumes that the GC implementation does not use a moving collector.
- return Pointer{v.Pointer(), v.Type()}
-}
-
-// IsNil reports whether the pointer is nil.
-func (p Pointer) IsNil() bool {
- return p.p == 0
-}
-
-// Uintptr returns the pointer as a uintptr.
-func (p Pointer) Uintptr() uintptr {
- return p.p
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go
deleted file mode 100644
index 16e6860..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2018, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//go:build !purego
-// +build !purego
-
-package value
-
-import (
- "reflect"
- "unsafe"
-)
-
-// Pointer is an opaque typed pointer and is guaranteed to be comparable.
-type Pointer struct {
- p unsafe.Pointer
- t reflect.Type
-}
-
-// PointerOf returns a Pointer from v, which must be a
-// reflect.Ptr, reflect.Slice, or reflect.Map.
-func PointerOf(v reflect.Value) Pointer {
- // The proper representation of a pointer is unsafe.Pointer,
- // which is necessary if the GC ever uses a moving collector.
- return Pointer{unsafe.Pointer(v.Pointer()), v.Type()}
-}
-
-// IsNil reports whether the pointer is nil.
-func (p Pointer) IsNil() bool {
- return p.p == nil
-}
-
-// Uintptr returns the pointer as a uintptr.
-func (p Pointer) Uintptr() uintptr {
- return uintptr(p.p)
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go b/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go
deleted file mode 100644
index 98533b0..0000000
--- a/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package value
-
-import (
- "fmt"
- "math"
- "reflect"
- "sort"
-)
-
-// SortKeys sorts a list of map keys, deduplicating keys if necessary.
-// The type of each value must be comparable.
-func SortKeys(vs []reflect.Value) []reflect.Value {
- if len(vs) == 0 {
- return vs
- }
-
- // Sort the map keys.
- sort.SliceStable(vs, func(i, j int) bool { return isLess(vs[i], vs[j]) })
-
- // Deduplicate keys (fails for NaNs).
- vs2 := vs[:1]
- for _, v := range vs[1:] {
- if isLess(vs2[len(vs2)-1], v) {
- vs2 = append(vs2, v)
- }
- }
- return vs2
-}
-
-// isLess is a generic function for sorting arbitrary map keys.
-// The inputs must be of the same type and must be comparable.
-func isLess(x, y reflect.Value) bool {
- switch x.Type().Kind() {
- case reflect.Bool:
- return !x.Bool() && y.Bool()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return x.Int() < y.Int()
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return x.Uint() < y.Uint()
- case reflect.Float32, reflect.Float64:
- // NOTE: This does not sort -0 as less than +0
- // since Go maps treat -0 and +0 as equal keys.
- fx, fy := x.Float(), y.Float()
- return fx < fy || math.IsNaN(fx) && !math.IsNaN(fy)
- case reflect.Complex64, reflect.Complex128:
- cx, cy := x.Complex(), y.Complex()
- rx, ix, ry, iy := real(cx), imag(cx), real(cy), imag(cy)
- if rx == ry || (math.IsNaN(rx) && math.IsNaN(ry)) {
- return ix < iy || math.IsNaN(ix) && !math.IsNaN(iy)
- }
- return rx < ry || math.IsNaN(rx) && !math.IsNaN(ry)
- case reflect.Ptr, reflect.UnsafePointer, reflect.Chan:
- return x.Pointer() < y.Pointer()
- case reflect.String:
- return x.String() < y.String()
- case reflect.Array:
- for i := 0; i < x.Len(); i++ {
- if isLess(x.Index(i), y.Index(i)) {
- return true
- }
- if isLess(y.Index(i), x.Index(i)) {
- return false
- }
- }
- return false
- case reflect.Struct:
- for i := 0; i < x.NumField(); i++ {
- if isLess(x.Field(i), y.Field(i)) {
- return true
- }
- if isLess(y.Field(i), x.Field(i)) {
- return false
- }
- }
- return false
- case reflect.Interface:
- vx, vy := x.Elem(), y.Elem()
- if !vx.IsValid() || !vy.IsValid() {
- return !vx.IsValid() && vy.IsValid()
- }
- tx, ty := vx.Type(), vy.Type()
- if tx == ty {
- return isLess(x.Elem(), y.Elem())
- }
- if tx.Kind() != ty.Kind() {
- return vx.Kind() < vy.Kind()
- }
- if tx.String() != ty.String() {
- return tx.String() < ty.String()
- }
- if tx.PkgPath() != ty.PkgPath() {
- return tx.PkgPath() < ty.PkgPath()
- }
- // This can happen in rare situations, so we fallback to just comparing
- // the unique pointer for a reflect.Type. This guarantees deterministic
- // ordering within a program, but it is obviously not stable.
- return reflect.ValueOf(vx.Type()).Pointer() < reflect.ValueOf(vy.Type()).Pointer()
- default:
- // Must be Func, Map, or Slice; which are not comparable.
- panic(fmt.Sprintf("%T is not comparable", x.Type()))
- }
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/options.go b/vendor/github.com/google/go-cmp/cmp/options.go
deleted file mode 100644
index 1f9ca9c..0000000
--- a/vendor/github.com/google/go-cmp/cmp/options.go
+++ /dev/null
@@ -1,554 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import (
- "fmt"
- "reflect"
- "regexp"
- "strings"
-
- "github.com/google/go-cmp/cmp/internal/function"
-)
-
-// Option configures for specific behavior of Equal and Diff. In particular,
-// the fundamental Option functions (Ignore, Transformer, and Comparer),
-// configure how equality is determined.
-//
-// The fundamental options may be composed with filters (FilterPath and
-// FilterValues) to control the scope over which they are applied.
-//
-// The cmp/cmpopts package provides helper functions for creating options that
-// may be used with Equal and Diff.
-type Option interface {
- // filter applies all filters and returns the option that remains.
- // Each option may only read s.curPath and call s.callTTBFunc.
- //
- // An Options is returned only if multiple comparers or transformers
- // can apply simultaneously and will only contain values of those types
- // or sub-Options containing values of those types.
- filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption
-}
-
-// applicableOption represents the following types:
-//
-// Fundamental: ignore | validator | *comparer | *transformer
-// Grouping: Options
-type applicableOption interface {
- Option
-
- // apply executes the option, which may mutate s or panic.
- apply(s *state, vx, vy reflect.Value)
-}
-
-// coreOption represents the following types:
-//
-// Fundamental: ignore | validator | *comparer | *transformer
-// Filters: *pathFilter | *valuesFilter
-type coreOption interface {
- Option
- isCore()
-}
-
-type core struct{}
-
-func (core) isCore() {}
-
-// Options is a list of Option values that also satisfies the Option interface.
-// Helper comparison packages may return an Options value when packing multiple
-// Option values into a single Option. When this package processes an Options,
-// it will be implicitly expanded into a flat list.
-//
-// Applying a filter on an Options is equivalent to applying that same filter
-// on all individual options held within.
-type Options []Option
-
-func (opts Options) filter(s *state, t reflect.Type, vx, vy reflect.Value) (out applicableOption) {
- for _, opt := range opts {
- switch opt := opt.filter(s, t, vx, vy); opt.(type) {
- case ignore:
- return ignore{} // Only ignore can short-circuit evaluation
- case validator:
- out = validator{} // Takes precedence over comparer or transformer
- case *comparer, *transformer, Options:
- switch out.(type) {
- case nil:
- out = opt
- case validator:
- // Keep validator
- case *comparer, *transformer, Options:
- out = Options{out, opt} // Conflicting comparers or transformers
- }
- }
- }
- return out
-}
-
-func (opts Options) apply(s *state, _, _ reflect.Value) {
- const warning = "ambiguous set of applicable options"
- const help = "consider using filters to ensure at most one Comparer or Transformer may apply"
- var ss []string
- for _, opt := range flattenOptions(nil, opts) {
- ss = append(ss, fmt.Sprint(opt))
- }
- set := strings.Join(ss, "\n\t")
- panic(fmt.Sprintf("%s at %#v:\n\t%s\n%s", warning, s.curPath, set, help))
-}
-
-func (opts Options) String() string {
- var ss []string
- for _, opt := range opts {
- ss = append(ss, fmt.Sprint(opt))
- }
- return fmt.Sprintf("Options{%s}", strings.Join(ss, ", "))
-}
-
-// FilterPath returns a new Option where opt is only evaluated if filter f
-// returns true for the current Path in the value tree.
-//
-// This filter is called even if a slice element or map entry is missing and
-// provides an opportunity to ignore such cases. The filter function must be
-// symmetric such that the filter result is identical regardless of whether the
-// missing value is from x or y.
-//
-// The option passed in may be an Ignore, Transformer, Comparer, Options, or
-// a previously filtered Option.
-func FilterPath(f func(Path) bool, opt Option) Option {
- if f == nil {
- panic("invalid path filter function")
- }
- if opt := normalizeOption(opt); opt != nil {
- return &pathFilter{fnc: f, opt: opt}
- }
- return nil
-}
-
-type pathFilter struct {
- core
- fnc func(Path) bool
- opt Option
-}
-
-func (f pathFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption {
- if f.fnc(s.curPath) {
- return f.opt.filter(s, t, vx, vy)
- }
- return nil
-}
-
-func (f pathFilter) String() string {
- return fmt.Sprintf("FilterPath(%s, %v)", function.NameOf(reflect.ValueOf(f.fnc)), f.opt)
-}
-
-// FilterValues returns a new Option where opt is only evaluated if filter f,
-// which is a function of the form "func(T, T) bool", returns true for the
-// current pair of values being compared. If either value is invalid or
-// the type of the values is not assignable to T, then this filter implicitly
-// returns false.
-//
-// The filter function must be
-// symmetric (i.e., agnostic to the order of the inputs) and
-// deterministic (i.e., produces the same result when given the same inputs).
-// If T is an interface, it is possible that f is called with two values with
-// different concrete types that both implement T.
-//
-// The option passed in may be an Ignore, Transformer, Comparer, Options, or
-// a previously filtered Option.
-func FilterValues(f interface{}, opt Option) Option {
- v := reflect.ValueOf(f)
- if !function.IsType(v.Type(), function.ValueFilter) || v.IsNil() {
- panic(fmt.Sprintf("invalid values filter function: %T", f))
- }
- if opt := normalizeOption(opt); opt != nil {
- vf := &valuesFilter{fnc: v, opt: opt}
- if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
- vf.typ = ti
- }
- return vf
- }
- return nil
-}
-
-type valuesFilter struct {
- core
- typ reflect.Type // T
- fnc reflect.Value // func(T, T) bool
- opt Option
-}
-
-func (f valuesFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption {
- if !vx.IsValid() || !vx.CanInterface() || !vy.IsValid() || !vy.CanInterface() {
- return nil
- }
- if (f.typ == nil || t.AssignableTo(f.typ)) && s.callTTBFunc(f.fnc, vx, vy) {
- return f.opt.filter(s, t, vx, vy)
- }
- return nil
-}
-
-func (f valuesFilter) String() string {
- return fmt.Sprintf("FilterValues(%s, %v)", function.NameOf(f.fnc), f.opt)
-}
-
-// Ignore is an Option that causes all comparisons to be ignored.
-// This value is intended to be combined with FilterPath or FilterValues.
-// It is an error to pass an unfiltered Ignore option to Equal.
-func Ignore() Option { return ignore{} }
-
-type ignore struct{ core }
-
-func (ignore) isFiltered() bool { return false }
-func (ignore) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { return ignore{} }
-func (ignore) apply(s *state, _, _ reflect.Value) { s.report(true, reportByIgnore) }
-func (ignore) String() string { return "Ignore()" }
-
-// validator is a sentinel Option type to indicate that some options could not
-// be evaluated due to unexported fields, missing slice elements, or
-// missing map entries. Both values are validator only for unexported fields.
-type validator struct{ core }
-
-func (validator) filter(_ *state, _ reflect.Type, vx, vy reflect.Value) applicableOption {
- if !vx.IsValid() || !vy.IsValid() {
- return validator{}
- }
- if !vx.CanInterface() || !vy.CanInterface() {
- return validator{}
- }
- return nil
-}
-func (validator) apply(s *state, vx, vy reflect.Value) {
- // Implies missing slice element or map entry.
- if !vx.IsValid() || !vy.IsValid() {
- s.report(vx.IsValid() == vy.IsValid(), 0)
- return
- }
-
- // Unable to Interface implies unexported field without visibility access.
- if !vx.CanInterface() || !vy.CanInterface() {
- help := "consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported"
- var name string
- if t := s.curPath.Index(-2).Type(); t.Name() != "" {
- // Named type with unexported fields.
- name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType
- if _, ok := reflect.New(t).Interface().(error); ok {
- help = "consider using cmpopts.EquateErrors to compare error values"
- }
- } else {
- // Unnamed type with unexported fields. Derive PkgPath from field.
- var pkgPath string
- for i := 0; i < t.NumField() && pkgPath == ""; i++ {
- pkgPath = t.Field(i).PkgPath
- }
- name = fmt.Sprintf("%q.(%v)", pkgPath, t.String()) // e.g., "path/to/package".(struct { a int })
- }
- panic(fmt.Sprintf("cannot handle unexported field at %#v:\n\t%v\n%s", s.curPath, name, help))
- }
-
- panic("not reachable")
-}
-
-// identRx represents a valid identifier according to the Go specification.
-const identRx = `[_\p{L}][_\p{L}\p{N}]*`
-
-var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`)
-
-// Transformer returns an Option that applies a transformation function that
-// converts values of a certain type into that of another.
-//
-// The transformer f must be a function "func(T) R" that converts values of
-// type T to those of type R and is implicitly filtered to input values
-// assignable to T. The transformer must not mutate T in any way.
-//
-// To help prevent some cases of infinite recursive cycles applying the
-// same transform to the output of itself (e.g., in the case where the
-// input and output types are the same), an implicit filter is added such that
-// a transformer is applicable only if that exact transformer is not already
-// in the tail of the Path since the last non-Transform step.
-// For situations where the implicit filter is still insufficient,
-// consider using cmpopts.AcyclicTransformer, which adds a filter
-// to prevent the transformer from being recursively applied upon itself.
-//
-// The name is a user provided label that is used as the Transform.Name in the
-// transformation PathStep (and eventually shown in the Diff output).
-// The name must be a valid identifier or qualified identifier in Go syntax.
-// If empty, an arbitrary name is used.
-func Transformer(name string, f interface{}) Option {
- v := reflect.ValueOf(f)
- if !function.IsType(v.Type(), function.Transformer) || v.IsNil() {
- panic(fmt.Sprintf("invalid transformer function: %T", f))
- }
- if name == "" {
- name = function.NameOf(v)
- if !identsRx.MatchString(name) {
- name = "λ" // Lambda-symbol as placeholder name
- }
- } else if !identsRx.MatchString(name) {
- panic(fmt.Sprintf("invalid name: %q", name))
- }
- tr := &transformer{name: name, fnc: reflect.ValueOf(f)}
- if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
- tr.typ = ti
- }
- return tr
-}
-
-type transformer struct {
- core
- name string
- typ reflect.Type // T
- fnc reflect.Value // func(T) R
-}
-
-func (tr *transformer) isFiltered() bool { return tr.typ != nil }
-
-func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption {
- for i := len(s.curPath) - 1; i >= 0; i-- {
- if t, ok := s.curPath[i].(Transform); !ok {
- break // Hit most recent non-Transform step
- } else if tr == t.trans {
- return nil // Cannot directly use same Transform
- }
- }
- if tr.typ == nil || t.AssignableTo(tr.typ) {
- return tr
- }
- return nil
-}
-
-func (tr *transformer) apply(s *state, vx, vy reflect.Value) {
- step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}}
- vvx := s.callTRFunc(tr.fnc, vx, step)
- vvy := s.callTRFunc(tr.fnc, vy, step)
- step.vx, step.vy = vvx, vvy
- s.compareAny(step)
-}
-
-func (tr transformer) String() string {
- return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc))
-}
-
-// Comparer returns an Option that determines whether two values are equal
-// to each other.
-//
-// The comparer f must be a function "func(T, T) bool" and is implicitly
-// filtered to input values assignable to T. If T is an interface, it is
-// possible that f is called with two values of different concrete types that
-// both implement T.
-//
-// The equality function must be:
-// - Symmetric: equal(x, y) == equal(y, x)
-// - Deterministic: equal(x, y) == equal(x, y)
-// - Pure: equal(x, y) does not modify x or y
-func Comparer(f interface{}) Option {
- v := reflect.ValueOf(f)
- if !function.IsType(v.Type(), function.Equal) || v.IsNil() {
- panic(fmt.Sprintf("invalid comparer function: %T", f))
- }
- cm := &comparer{fnc: v}
- if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
- cm.typ = ti
- }
- return cm
-}
-
-type comparer struct {
- core
- typ reflect.Type // T
- fnc reflect.Value // func(T, T) bool
-}
-
-func (cm *comparer) isFiltered() bool { return cm.typ != nil }
-
-func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption {
- if cm.typ == nil || t.AssignableTo(cm.typ) {
- return cm
- }
- return nil
-}
-
-func (cm *comparer) apply(s *state, vx, vy reflect.Value) {
- eq := s.callTTBFunc(cm.fnc, vx, vy)
- s.report(eq, reportByFunc)
-}
-
-func (cm comparer) String() string {
- return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc))
-}
-
-// Exporter returns an Option that specifies whether Equal is allowed to
-// introspect into the unexported fields of certain struct types.
-//
-// Users of this option must understand that comparing on unexported fields
-// from external packages is not safe since changes in the internal
-// implementation of some external package may cause the result of Equal
-// to unexpectedly change. However, it may be valid to use this option on types
-// defined in an internal package where the semantic meaning of an unexported
-// field is in the control of the user.
-//
-// In many cases, a custom Comparer should be used instead that defines
-// equality as a function of the public API of a type rather than the underlying
-// unexported implementation.
-//
-// For example, the reflect.Type documentation defines equality to be determined
-// by the == operator on the interface (essentially performing a shallow pointer
-// comparison) and most attempts to compare *regexp.Regexp types are interested
-// in only checking that the regular expression strings are equal.
-// Both of these are accomplished using Comparers:
-//
-// Comparer(func(x, y reflect.Type) bool { return x == y })
-// Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() })
-//
-// In other cases, the cmpopts.IgnoreUnexported option can be used to ignore
-// all unexported fields on specified struct types.
-func Exporter(f func(reflect.Type) bool) Option {
- if !supportExporters {
- panic("Exporter is not supported on purego builds")
- }
- return exporter(f)
-}
-
-type exporter func(reflect.Type) bool
-
-func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
- panic("not implemented")
-}
-
-// AllowUnexported returns an Options that allows Equal to forcibly introspect
-// unexported fields of the specified struct types.
-//
-// See Exporter for the proper use of this option.
-func AllowUnexported(types ...interface{}) Option {
- m := make(map[reflect.Type]bool)
- for _, typ := range types {
- t := reflect.TypeOf(typ)
- if t.Kind() != reflect.Struct {
- panic(fmt.Sprintf("invalid struct type: %T", typ))
- }
- m[t] = true
- }
- return exporter(func(t reflect.Type) bool { return m[t] })
-}
-
-// Result represents the comparison result for a single node and
-// is provided by cmp when calling Report (see Reporter).
-type Result struct {
- _ [0]func() // Make Result incomparable
- flags resultFlags
-}
-
-// Equal reports whether the node was determined to be equal or not.
-// As a special case, ignored nodes are considered equal.
-func (r Result) Equal() bool {
- return r.flags&(reportEqual|reportByIgnore) != 0
-}
-
-// ByIgnore reports whether the node is equal because it was ignored.
-// This never reports true if Equal reports false.
-func (r Result) ByIgnore() bool {
- return r.flags&reportByIgnore != 0
-}
-
-// ByMethod reports whether the Equal method determined equality.
-func (r Result) ByMethod() bool {
- return r.flags&reportByMethod != 0
-}
-
-// ByFunc reports whether a Comparer function determined equality.
-func (r Result) ByFunc() bool {
- return r.flags&reportByFunc != 0
-}
-
-// ByCycle reports whether a reference cycle was detected.
-func (r Result) ByCycle() bool {
- return r.flags&reportByCycle != 0
-}
-
-type resultFlags uint
-
-const (
- _ resultFlags = (1 << iota) / 2
-
- reportEqual
- reportUnequal
- reportByIgnore
- reportByMethod
- reportByFunc
- reportByCycle
-)
-
-// Reporter is an Option that can be passed to Equal. When Equal traverses
-// the value trees, it calls PushStep as it descends into each node in the
-// tree and PopStep as it ascend out of the node. The leaves of the tree are
-// either compared (determined to be equal or not equal) or ignored and reported
-// as such by calling the Report method.
-func Reporter(r interface {
- // PushStep is called when a tree-traversal operation is performed.
- // The PathStep itself is only valid until the step is popped.
- // The PathStep.Values are valid for the duration of the entire traversal
- // and must not be mutated.
- //
- // Equal always calls PushStep at the start to provide an operation-less
- // PathStep used to report the root values.
- //
- // Within a slice, the exact set of inserted, removed, or modified elements
- // is unspecified and may change in future implementations.
- // The entries of a map are iterated through in an unspecified order.
- PushStep(PathStep)
-
- // Report is called exactly once on leaf nodes to report whether the
- // comparison identified the node as equal, unequal, or ignored.
- // A leaf node is one that is immediately preceded by and followed by
- // a pair of PushStep and PopStep calls.
- Report(Result)
-
- // PopStep ascends back up the value tree.
- // There is always a matching pop call for every push call.
- PopStep()
-}) Option {
- return reporter{r}
-}
-
-type reporter struct{ reporterIface }
-type reporterIface interface {
- PushStep(PathStep)
- Report(Result)
- PopStep()
-}
-
-func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
- panic("not implemented")
-}
-
-// normalizeOption normalizes the input options such that all Options groups
-// are flattened and groups with a single element are reduced to that element.
-// Only coreOptions and Options containing coreOptions are allowed.
-func normalizeOption(src Option) Option {
- switch opts := flattenOptions(nil, Options{src}); len(opts) {
- case 0:
- return nil
- case 1:
- return opts[0]
- default:
- return opts
- }
-}
-
-// flattenOptions copies all options in src to dst as a flat list.
-// Only coreOptions and Options containing coreOptions are allowed.
-func flattenOptions(dst, src Options) Options {
- for _, opt := range src {
- switch opt := opt.(type) {
- case nil:
- continue
- case Options:
- dst = flattenOptions(dst, opt)
- case coreOption:
- dst = append(dst, opt)
- default:
- panic(fmt.Sprintf("invalid option type: %T", opt))
- }
- }
- return dst
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/path.go b/vendor/github.com/google/go-cmp/cmp/path.go
deleted file mode 100644
index a0a5885..0000000
--- a/vendor/github.com/google/go-cmp/cmp/path.go
+++ /dev/null
@@ -1,380 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import (
- "fmt"
- "reflect"
- "strings"
- "unicode"
- "unicode/utf8"
-
- "github.com/google/go-cmp/cmp/internal/value"
-)
-
-// Path is a list of PathSteps describing the sequence of operations to get
-// from some root type to the current position in the value tree.
-// The first Path element is always an operation-less PathStep that exists
-// simply to identify the initial type.
-//
-// When traversing structs with embedded structs, the embedded struct will
-// always be accessed as a field before traversing the fields of the
-// embedded struct themselves. That is, an exported field from the
-// embedded struct will never be accessed directly from the parent struct.
-type Path []PathStep
-
-// PathStep is a union-type for specific operations to traverse
-// a value's tree structure. Users of this package never need to implement
-// these types as values of this type will be returned by this package.
-//
-// Implementations of this interface are
-// StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform.
-type PathStep interface {
- String() string
-
- // Type is the resulting type after performing the path step.
- Type() reflect.Type
-
- // Values is the resulting values after performing the path step.
- // The type of each valid value is guaranteed to be identical to Type.
- //
- // In some cases, one or both may be invalid or have restrictions:
- // - For StructField, both are not interface-able if the current field
- // is unexported and the struct type is not explicitly permitted by
- // an Exporter to traverse unexported fields.
- // - For SliceIndex, one may be invalid if an element is missing from
- // either the x or y slice.
- // - For MapIndex, one may be invalid if an entry is missing from
- // either the x or y map.
- //
- // The provided values must not be mutated.
- Values() (vx, vy reflect.Value)
-}
-
-var (
- _ PathStep = StructField{}
- _ PathStep = SliceIndex{}
- _ PathStep = MapIndex{}
- _ PathStep = Indirect{}
- _ PathStep = TypeAssertion{}
- _ PathStep = Transform{}
-)
-
-func (pa *Path) push(s PathStep) {
- *pa = append(*pa, s)
-}
-
-func (pa *Path) pop() {
- *pa = (*pa)[:len(*pa)-1]
-}
-
-// Last returns the last PathStep in the Path.
-// If the path is empty, this returns a non-nil PathStep that reports a nil Type.
-func (pa Path) Last() PathStep {
- return pa.Index(-1)
-}
-
-// Index returns the ith step in the Path and supports negative indexing.
-// A negative index starts counting from the tail of the Path such that -1
-// refers to the last step, -2 refers to the second-to-last step, and so on.
-// If index is invalid, this returns a non-nil PathStep that reports a nil Type.
-func (pa Path) Index(i int) PathStep {
- if i < 0 {
- i = len(pa) + i
- }
- if i < 0 || i >= len(pa) {
- return pathStep{}
- }
- return pa[i]
-}
-
-// String returns the simplified path to a node.
-// The simplified path only contains struct field accesses.
-//
-// For example:
-//
-// MyMap.MySlices.MyField
-func (pa Path) String() string {
- var ss []string
- for _, s := range pa {
- if _, ok := s.(StructField); ok {
- ss = append(ss, s.String())
- }
- }
- return strings.TrimPrefix(strings.Join(ss, ""), ".")
-}
-
-// GoString returns the path to a specific node using Go syntax.
-//
-// For example:
-//
-// (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField
-func (pa Path) GoString() string {
- var ssPre, ssPost []string
- var numIndirect int
- for i, s := range pa {
- var nextStep PathStep
- if i+1 < len(pa) {
- nextStep = pa[i+1]
- }
- switch s := s.(type) {
- case Indirect:
- numIndirect++
- pPre, pPost := "(", ")"
- switch nextStep.(type) {
- case Indirect:
- continue // Next step is indirection, so let them batch up
- case StructField:
- numIndirect-- // Automatic indirection on struct fields
- case nil:
- pPre, pPost = "", "" // Last step; no need for parenthesis
- }
- if numIndirect > 0 {
- ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect))
- ssPost = append(ssPost, pPost)
- }
- numIndirect = 0
- continue
- case Transform:
- ssPre = append(ssPre, s.trans.name+"(")
- ssPost = append(ssPost, ")")
- continue
- }
- ssPost = append(ssPost, s.String())
- }
- for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 {
- ssPre[i], ssPre[j] = ssPre[j], ssPre[i]
- }
- return strings.Join(ssPre, "") + strings.Join(ssPost, "")
-}
-
-type pathStep struct {
- typ reflect.Type
- vx, vy reflect.Value
-}
-
-func (ps pathStep) Type() reflect.Type { return ps.typ }
-func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy }
-func (ps pathStep) String() string {
- if ps.typ == nil {
- return "<nil>"
- }
- s := value.TypeString(ps.typ, false)
- if s == "" || strings.ContainsAny(s, "{}\n") {
- return "root" // Type too simple or complex to print
- }
- return fmt.Sprintf("{%s}", s)
-}
-
-// StructField represents a struct field access on a field called Name.
-type StructField struct{ *structField }
-type structField struct {
- pathStep
- name string
- idx int
-
- // These fields are used for forcibly accessing an unexported field.
- // pvx, pvy, and field are only valid if unexported is true.
- unexported bool
- mayForce bool // Forcibly allow visibility
- paddr bool // Was parent addressable?
- pvx, pvy reflect.Value // Parent values (always addressable)
- field reflect.StructField // Field information
-}
-
-func (sf StructField) Type() reflect.Type { return sf.typ }
-func (sf StructField) Values() (vx, vy reflect.Value) {
- if !sf.unexported {
- return sf.vx, sf.vy // CanInterface reports true
- }
-
- // Forcibly obtain read-write access to an unexported struct field.
- if sf.mayForce {
- vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr)
- vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr)
- return vx, vy // CanInterface reports true
- }
- return sf.vx, sf.vy // CanInterface reports false
-}
-func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) }
-
-// Name is the field name.
-func (sf StructField) Name() string { return sf.name }
-
-// Index is the index of the field in the parent struct type.
-// See reflect.Type.Field.
-func (sf StructField) Index() int { return sf.idx }
-
-// SliceIndex is an index operation on a slice or array at some index Key.
-type SliceIndex struct{ *sliceIndex }
-type sliceIndex struct {
- pathStep
- xkey, ykey int
- isSlice bool // False for reflect.Array
-}
-
-func (si SliceIndex) Type() reflect.Type { return si.typ }
-func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy }
-func (si SliceIndex) String() string {
- switch {
- case si.xkey == si.ykey:
- return fmt.Sprintf("[%d]", si.xkey)
- case si.ykey == -1:
- // [5->?] means "I don't know where X[5] went"
- return fmt.Sprintf("[%d->?]", si.xkey)
- case si.xkey == -1:
- // [?->3] means "I don't know where Y[3] came from"
- return fmt.Sprintf("[?->%d]", si.ykey)
- default:
- // [5->3] means "X[5] moved to Y[3]"
- return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey)
- }
-}
-
-// Key is the index key; it may return -1 if in a split state
-func (si SliceIndex) Key() int {
- if si.xkey != si.ykey {
- return -1
- }
- return si.xkey
-}
-
-// SplitKeys are the indexes for indexing into slices in the
-// x and y values, respectively. These indexes may differ due to the
-// insertion or removal of an element in one of the slices, causing
-// all of the indexes to be shifted. If an index is -1, then that
-// indicates that the element does not exist in the associated slice.
-//
-// Key is guaranteed to return -1 if and only if the indexes returned
-// by SplitKeys are not the same. SplitKeys will never return -1 for
-// both indexes.
-func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey }
-
-// MapIndex is an index operation on a map at some index Key.
-type MapIndex struct{ *mapIndex }
-type mapIndex struct {
- pathStep
- key reflect.Value
-}
-
-func (mi MapIndex) Type() reflect.Type { return mi.typ }
-func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy }
-func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) }
-
-// Key is the value of the map key.
-func (mi MapIndex) Key() reflect.Value { return mi.key }
-
-// Indirect represents pointer indirection on the parent type.
-type Indirect struct{ *indirect }
-type indirect struct {
- pathStep
-}
-
-func (in Indirect) Type() reflect.Type { return in.typ }
-func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy }
-func (in Indirect) String() string { return "*" }
-
-// TypeAssertion represents a type assertion on an interface.
-type TypeAssertion struct{ *typeAssertion }
-type typeAssertion struct {
- pathStep
-}
-
-func (ta TypeAssertion) Type() reflect.Type { return ta.typ }
-func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy }
-func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", value.TypeString(ta.typ, false)) }
-
-// Transform is a transformation from the parent type to the current type.
-type Transform struct{ *transform }
-type transform struct {
- pathStep
- trans *transformer
-}
-
-func (tf Transform) Type() reflect.Type { return tf.typ }
-func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy }
-func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) }
-
-// Name is the name of the Transformer.
-func (tf Transform) Name() string { return tf.trans.name }
-
-// Func is the function pointer to the transformer function.
-func (tf Transform) Func() reflect.Value { return tf.trans.fnc }
-
-// Option returns the originally constructed Transformer option.
-// The == operator can be used to detect the exact option used.
-func (tf Transform) Option() Option { return tf.trans }
-
-// pointerPath represents a dual-stack of pointers encountered when
-// recursively traversing the x and y values. This data structure supports
-// detection of cycles and determining whether the cycles are equal.
-// In Go, cycles can occur via pointers, slices, and maps.
-//
-// The pointerPath uses a map to represent a stack; where descension into a
-// pointer pushes the address onto the stack, and ascension from a pointer
-// pops the address from the stack. Thus, when traversing into a pointer from
-// reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles
-// by checking whether the pointer has already been visited. The cycle detection
-// uses a separate stack for the x and y values.
-//
-// If a cycle is detected we need to determine whether the two pointers
-// should be considered equal. The definition of equality chosen by Equal
-// requires two graphs to have the same structure. To determine this, both the
-// x and y values must have a cycle where the previous pointers were also
-// encountered together as a pair.
-//
-// Semantically, this is equivalent to augmenting Indirect, SliceIndex, and
-// MapIndex with pointer information for the x and y values.
-// Suppose px and py are two pointers to compare, we then search the
-// Path for whether px was ever encountered in the Path history of x, and
-// similarly so with py. If either side has a cycle, the comparison is only
-// equal if both px and py have a cycle resulting from the same PathStep.
-//
-// Using a map as a stack is more performant as we can perform cycle detection
-// in O(1) instead of O(N) where N is len(Path).
-type pointerPath struct {
- // mx is keyed by x pointers, where the value is the associated y pointer.
- mx map[value.Pointer]value.Pointer
- // my is keyed by y pointers, where the value is the associated x pointer.
- my map[value.Pointer]value.Pointer
-}
-
-func (p *pointerPath) Init() {
- p.mx = make(map[value.Pointer]value.Pointer)
- p.my = make(map[value.Pointer]value.Pointer)
-}
-
-// Push indicates intent to descend into pointers vx and vy where
-// visited reports whether either has been seen before. If visited before,
-// equal reports whether both pointers were encountered together.
-// Pop must be called if and only if the pointers were never visited.
-//
-// The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map
-// and be non-nil.
-func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) {
- px := value.PointerOf(vx)
- py := value.PointerOf(vy)
- _, ok1 := p.mx[px]
- _, ok2 := p.my[py]
- if ok1 || ok2 {
- equal = p.mx[px] == py && p.my[py] == px // Pointers paired together
- return equal, true
- }
- p.mx[px] = py
- p.my[py] = px
- return false, false
-}
-
-// Pop ascends from pointers vx and vy.
-func (p pointerPath) Pop(vx, vy reflect.Value) {
- delete(p.mx, value.PointerOf(vx))
- delete(p.my, value.PointerOf(vy))
-}
-
-// isExported reports whether the identifier is exported.
-func isExported(id string) bool {
- r, _ := utf8.DecodeRuneInString(id)
- return unicode.IsUpper(r)
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/report.go b/vendor/github.com/google/go-cmp/cmp/report.go
deleted file mode 100644
index f43cd12..0000000
--- a/vendor/github.com/google/go-cmp/cmp/report.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2017, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-// defaultReporter implements the reporter interface.
-//
-// As Equal serially calls the PushStep, Report, and PopStep methods, the
-// defaultReporter constructs a tree-based representation of the compared value
-// and the result of each comparison (see valueNode).
-//
-// When the String method is called, the FormatDiff method transforms the
-// valueNode tree into a textNode tree, which is a tree-based representation
-// of the textual output (see textNode).
-//
-// Lastly, the textNode.String method produces the final report as a string.
-type defaultReporter struct {
- root *valueNode
- curr *valueNode
-}
-
-func (r *defaultReporter) PushStep(ps PathStep) {
- r.curr = r.curr.PushStep(ps)
- if r.root == nil {
- r.root = r.curr
- }
-}
-func (r *defaultReporter) Report(rs Result) {
- r.curr.Report(rs)
-}
-func (r *defaultReporter) PopStep() {
- r.curr = r.curr.PopStep()
-}
-
-// String provides a full report of the differences detected as a structured
-// literal in pseudo-Go syntax. String may only be called after the entire tree
-// has been traversed.
-func (r *defaultReporter) String() string {
- assert(r.root != nil && r.curr == nil)
- if r.root.NumDiff == 0 {
- return ""
- }
- ptrs := new(pointerReferences)
- text := formatOptions{}.FormatDiff(r.root, ptrs)
- resolveReferences(text)
- return text.String()
-}
-
-func assert(ok bool) {
- if !ok {
- panic("assertion failure")
- }
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/report_compare.go b/vendor/github.com/google/go-cmp/cmp/report_compare.go
deleted file mode 100644
index 2050bf6..0000000
--- a/vendor/github.com/google/go-cmp/cmp/report_compare.go
+++ /dev/null
@@ -1,433 +0,0 @@
-// Copyright 2019, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import (
- "fmt"
- "reflect"
-)
-
-// numContextRecords is the number of surrounding equal records to print.
-const numContextRecords = 2
-
-type diffMode byte
-
-const (
- diffUnknown diffMode = 0
- diffIdentical diffMode = ' '
- diffRemoved diffMode = '-'
- diffInserted diffMode = '+'
-)
-
-type typeMode int
-
-const (
- // emitType always prints the type.
- emitType typeMode = iota
- // elideType never prints the type.
- elideType
- // autoType prints the type only for composite kinds
- // (i.e., structs, slices, arrays, and maps).
- autoType
-)
-
-type formatOptions struct {
- // DiffMode controls the output mode of FormatDiff.
- //
- // If diffUnknown, then produce a diff of the x and y values.
- // If diffIdentical, then emit values as if they were equal.
- // If diffRemoved, then only emit x values (ignoring y values).
- // If diffInserted, then only emit y values (ignoring x values).
- DiffMode diffMode
-
- // TypeMode controls whether to print the type for the current node.
- //
- // As a general rule of thumb, we always print the type of the next node
- // after an interface, and always elide the type of the next node after
- // a slice or map node.
- TypeMode typeMode
-
- // formatValueOptions are options specific to printing reflect.Values.
- formatValueOptions
-}
-
-func (opts formatOptions) WithDiffMode(d diffMode) formatOptions {
- opts.DiffMode = d
- return opts
-}
-func (opts formatOptions) WithTypeMode(t typeMode) formatOptions {
- opts.TypeMode = t
- return opts
-}
-func (opts formatOptions) WithVerbosity(level int) formatOptions {
- opts.VerbosityLevel = level
- opts.LimitVerbosity = true
- return opts
-}
-func (opts formatOptions) verbosity() uint {
- switch {
- case opts.VerbosityLevel < 0:
- return 0
- case opts.VerbosityLevel > 16:
- return 16 // some reasonable maximum to avoid shift overflow
- default:
- return uint(opts.VerbosityLevel)
- }
-}
-
-const maxVerbosityPreset = 6
-
-// verbosityPreset modifies the verbosity settings given an index
-// between 0 and maxVerbosityPreset, inclusive.
-func verbosityPreset(opts formatOptions, i int) formatOptions {
- opts.VerbosityLevel = int(opts.verbosity()) + 2*i
- if i > 0 {
- opts.AvoidStringer = true
- }
- if i >= maxVerbosityPreset {
- opts.PrintAddresses = true
- opts.QualifiedNames = true
- }
- return opts
-}
-
-// FormatDiff converts a valueNode tree into a textNode tree, where the later
-// is a textual representation of the differences detected in the former.
-func (opts formatOptions) FormatDiff(v *valueNode, ptrs *pointerReferences) (out textNode) {
- if opts.DiffMode == diffIdentical {
- opts = opts.WithVerbosity(1)
- } else if opts.verbosity() < 3 {
- opts = opts.WithVerbosity(3)
- }
-
- // Check whether we have specialized formatting for this node.
- // This is not necessary, but helpful for producing more readable outputs.
- if opts.CanFormatDiffSlice(v) {
- return opts.FormatDiffSlice(v)
- }
-
- var parentKind reflect.Kind
- if v.parent != nil && v.parent.TransformerName == "" {
- parentKind = v.parent.Type.Kind()
- }
-
- // For leaf nodes, format the value based on the reflect.Values alone.
- // As a special case, treat equal []byte as a leaf nodes.
- isBytes := v.Type.Kind() == reflect.Slice && v.Type.Elem() == byteType
- isEqualBytes := isBytes && v.NumDiff+v.NumIgnored+v.NumTransformed == 0
- if v.MaxDepth == 0 || isEqualBytes {
- switch opts.DiffMode {
- case diffUnknown, diffIdentical:
- // Format Equal.
- if v.NumDiff == 0 {
- outx := opts.FormatValue(v.ValueX, parentKind, ptrs)
- outy := opts.FormatValue(v.ValueY, parentKind, ptrs)
- if v.NumIgnored > 0 && v.NumSame == 0 {
- return textEllipsis
- } else if outx.Len() < outy.Len() {
- return outx
- } else {
- return outy
- }
- }
-
- // Format unequal.
- assert(opts.DiffMode == diffUnknown)
- var list textList
- outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, parentKind, ptrs)
- outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, parentKind, ptrs)
- for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ {
- opts2 := verbosityPreset(opts, i).WithTypeMode(elideType)
- outx = opts2.FormatValue(v.ValueX, parentKind, ptrs)
- outy = opts2.FormatValue(v.ValueY, parentKind, ptrs)
- }
- if outx != nil {
- list = append(list, textRecord{Diff: '-', Value: outx})
- }
- if outy != nil {
- list = append(list, textRecord{Diff: '+', Value: outy})
- }
- return opts.WithTypeMode(emitType).FormatType(v.Type, list)
- case diffRemoved:
- return opts.FormatValue(v.ValueX, parentKind, ptrs)
- case diffInserted:
- return opts.FormatValue(v.ValueY, parentKind, ptrs)
- default:
- panic("invalid diff mode")
- }
- }
-
- // Register slice element to support cycle detection.
- if parentKind == reflect.Slice {
- ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, true)
- defer ptrs.Pop()
- defer func() { out = wrapTrunkReferences(ptrRefs, out) }()
- }
-
- // Descend into the child value node.
- if v.TransformerName != "" {
- out := opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs)
- out = &textWrap{Prefix: "Inverse(" + v.TransformerName + ", ", Value: out, Suffix: ")"}
- return opts.FormatType(v.Type, out)
- } else {
- switch k := v.Type.Kind(); k {
- case reflect.Struct, reflect.Array, reflect.Slice:
- out = opts.formatDiffList(v.Records, k, ptrs)
- out = opts.FormatType(v.Type, out)
- case reflect.Map:
- // Register map to support cycle detection.
- ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false)
- defer ptrs.Pop()
-
- out = opts.formatDiffList(v.Records, k, ptrs)
- out = wrapTrunkReferences(ptrRefs, out)
- out = opts.FormatType(v.Type, out)
- case reflect.Ptr:
- // Register pointer to support cycle detection.
- ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false)
- defer ptrs.Pop()
-
- out = opts.FormatDiff(v.Value, ptrs)
- out = wrapTrunkReferences(ptrRefs, out)
- out = &textWrap{Prefix: "&", Value: out}
- case reflect.Interface:
- out = opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs)
- default:
- panic(fmt.Sprintf("%v cannot have children", k))
- }
- return out
- }
-}
-
-func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind, ptrs *pointerReferences) textNode {
- // Derive record name based on the data structure kind.
- var name string
- var formatKey func(reflect.Value) string
- switch k {
- case reflect.Struct:
- name = "field"
- opts = opts.WithTypeMode(autoType)
- formatKey = func(v reflect.Value) string { return v.String() }
- case reflect.Slice, reflect.Array:
- name = "element"
- opts = opts.WithTypeMode(elideType)
- formatKey = func(reflect.Value) string { return "" }
- case reflect.Map:
- name = "entry"
- opts = opts.WithTypeMode(elideType)
- formatKey = func(v reflect.Value) string { return formatMapKey(v, false, ptrs) }
- }
-
- maxLen := -1
- if opts.LimitVerbosity {
- if opts.DiffMode == diffIdentical {
- maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc...
- } else {
- maxLen = (1 << opts.verbosity()) << 1 // 2, 4, 8, 16, 32, 64, etc...
- }
- opts.VerbosityLevel--
- }
-
- // Handle unification.
- switch opts.DiffMode {
- case diffIdentical, diffRemoved, diffInserted:
- var list textList
- var deferredEllipsis bool // Add final "..." to indicate records were dropped
- for _, r := range recs {
- if len(list) == maxLen {
- deferredEllipsis = true
- break
- }
-
- // Elide struct fields that are zero value.
- if k == reflect.Struct {
- var isZero bool
- switch opts.DiffMode {
- case diffIdentical:
- isZero = r.Value.ValueX.IsZero() || r.Value.ValueY.IsZero()
- case diffRemoved:
- isZero = r.Value.ValueX.IsZero()
- case diffInserted:
- isZero = r.Value.ValueY.IsZero()
- }
- if isZero {
- continue
- }
- }
- // Elide ignored nodes.
- if r.Value.NumIgnored > 0 && r.Value.NumSame+r.Value.NumDiff == 0 {
- deferredEllipsis = !(k == reflect.Slice || k == reflect.Array)
- if !deferredEllipsis {
- list.AppendEllipsis(diffStats{})
- }
- continue
- }
- if out := opts.FormatDiff(r.Value, ptrs); out != nil {
- list = append(list, textRecord{Key: formatKey(r.Key), Value: out})
- }
- }
- if deferredEllipsis {
- list.AppendEllipsis(diffStats{})
- }
- return &textWrap{Prefix: "{", Value: list, Suffix: "}"}
- case diffUnknown:
- default:
- panic("invalid diff mode")
- }
-
- // Handle differencing.
- var numDiffs int
- var list textList
- var keys []reflect.Value // invariant: len(list) == len(keys)
- groups := coalesceAdjacentRecords(name, recs)
- maxGroup := diffStats{Name: name}
- for i, ds := range groups {
- if maxLen >= 0 && numDiffs >= maxLen {
- maxGroup = maxGroup.Append(ds)
- continue
- }
-
- // Handle equal records.
- if ds.NumDiff() == 0 {
- // Compute the number of leading and trailing records to print.
- var numLo, numHi int
- numEqual := ds.NumIgnored + ds.NumIdentical
- for numLo < numContextRecords && numLo+numHi < numEqual && i != 0 {
- if r := recs[numLo].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 {
- break
- }
- numLo++
- }
- for numHi < numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 {
- if r := recs[numEqual-numHi-1].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 {
- break
- }
- numHi++
- }
- if numEqual-(numLo+numHi) == 1 && ds.NumIgnored == 0 {
- numHi++ // Avoid pointless coalescing of a single equal record
- }
-
- // Format the equal values.
- for _, r := range recs[:numLo] {
- out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs)
- list = append(list, textRecord{Key: formatKey(r.Key), Value: out})
- keys = append(keys, r.Key)
- }
- if numEqual > numLo+numHi {
- ds.NumIdentical -= numLo + numHi
- list.AppendEllipsis(ds)
- for len(keys) < len(list) {
- keys = append(keys, reflect.Value{})
- }
- }
- for _, r := range recs[numEqual-numHi : numEqual] {
- out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs)
- list = append(list, textRecord{Key: formatKey(r.Key), Value: out})
- keys = append(keys, r.Key)
- }
- recs = recs[numEqual:]
- continue
- }
-
- // Handle unequal records.
- for _, r := range recs[:ds.NumDiff()] {
- switch {
- case opts.CanFormatDiffSlice(r.Value):
- out := opts.FormatDiffSlice(r.Value)
- list = append(list, textRecord{Key: formatKey(r.Key), Value: out})
- keys = append(keys, r.Key)
- case r.Value.NumChildren == r.Value.MaxDepth:
- outx := opts.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs)
- outy := opts.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs)
- for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ {
- opts2 := verbosityPreset(opts, i)
- outx = opts2.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs)
- outy = opts2.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs)
- }
- if outx != nil {
- list = append(list, textRecord{Diff: diffRemoved, Key: formatKey(r.Key), Value: outx})
- keys = append(keys, r.Key)
- }
- if outy != nil {
- list = append(list, textRecord{Diff: diffInserted, Key: formatKey(r.Key), Value: outy})
- keys = append(keys, r.Key)
- }
- default:
- out := opts.FormatDiff(r.Value, ptrs)
- list = append(list, textRecord{Key: formatKey(r.Key), Value: out})
- keys = append(keys, r.Key)
- }
- }
- recs = recs[ds.NumDiff():]
- numDiffs += ds.NumDiff()
- }
- if maxGroup.IsZero() {
- assert(len(recs) == 0)
- } else {
- list.AppendEllipsis(maxGroup)
- for len(keys) < len(list) {
- keys = append(keys, reflect.Value{})
- }
- }
- assert(len(list) == len(keys))
-
- // For maps, the default formatting logic uses fmt.Stringer which may
- // produce ambiguous output. Avoid calling String to disambiguate.
- if k == reflect.Map {
- var ambiguous bool
- seenKeys := map[string]reflect.Value{}
- for i, currKey := range keys {
- if currKey.IsValid() {
- strKey := list[i].Key
- prevKey, seen := seenKeys[strKey]
- if seen && prevKey.CanInterface() && currKey.CanInterface() {
- ambiguous = prevKey.Interface() != currKey.Interface()
- if ambiguous {
- break
- }
- }
- seenKeys[strKey] = currKey
- }
- }
- if ambiguous {
- for i, k := range keys {
- if k.IsValid() {
- list[i].Key = formatMapKey(k, true, ptrs)
- }
- }
- }
- }
-
- return &textWrap{Prefix: "{", Value: list, Suffix: "}"}
-}
-
-// coalesceAdjacentRecords coalesces the list of records into groups of
-// adjacent equal, or unequal counts.
-func coalesceAdjacentRecords(name string, recs []reportRecord) (groups []diffStats) {
- var prevCase int // Arbitrary index into which case last occurred
- lastStats := func(i int) *diffStats {
- if prevCase != i {
- groups = append(groups, diffStats{Name: name})
- prevCase = i
- }
- return &groups[len(groups)-1]
- }
- for _, r := range recs {
- switch rv := r.Value; {
- case rv.NumIgnored > 0 && rv.NumSame+rv.NumDiff == 0:
- lastStats(1).NumIgnored++
- case rv.NumDiff == 0:
- lastStats(1).NumIdentical++
- case rv.NumDiff > 0 && !rv.ValueY.IsValid():
- lastStats(2).NumRemoved++
- case rv.NumDiff > 0 && !rv.ValueX.IsValid():
- lastStats(2).NumInserted++
- default:
- lastStats(2).NumModified++
- }
- }
- return groups
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/report_references.go b/vendor/github.com/google/go-cmp/cmp/report_references.go
deleted file mode 100644
index be31b33..0000000
--- a/vendor/github.com/google/go-cmp/cmp/report_references.go
+++ /dev/null
@@ -1,264 +0,0 @@
-// Copyright 2020, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import (
- "fmt"
- "reflect"
- "strings"
-
- "github.com/google/go-cmp/cmp/internal/flags"
- "github.com/google/go-cmp/cmp/internal/value"
-)
-
-const (
- pointerDelimPrefix = "⟪"
- pointerDelimSuffix = "⟫"
-)
-
-// formatPointer prints the address of the pointer.
-func formatPointer(p value.Pointer, withDelims bool) string {
- v := p.Uintptr()
- if flags.Deterministic {
- v = 0xdeadf00f // Only used for stable testing purposes
- }
- if withDelims {
- return pointerDelimPrefix + formatHex(uint64(v)) + pointerDelimSuffix
- }
- return formatHex(uint64(v))
-}
-
-// pointerReferences is a stack of pointers visited so far.
-type pointerReferences [][2]value.Pointer
-
-func (ps *pointerReferences) PushPair(vx, vy reflect.Value, d diffMode, deref bool) (pp [2]value.Pointer) {
- if deref && vx.IsValid() {
- vx = vx.Addr()
- }
- if deref && vy.IsValid() {
- vy = vy.Addr()
- }
- switch d {
- case diffUnknown, diffIdentical:
- pp = [2]value.Pointer{value.PointerOf(vx), value.PointerOf(vy)}
- case diffRemoved:
- pp = [2]value.Pointer{value.PointerOf(vx), value.Pointer{}}
- case diffInserted:
- pp = [2]value.Pointer{value.Pointer{}, value.PointerOf(vy)}
- }
- *ps = append(*ps, pp)
- return pp
-}
-
-func (ps *pointerReferences) Push(v reflect.Value) (p value.Pointer, seen bool) {
- p = value.PointerOf(v)
- for _, pp := range *ps {
- if p == pp[0] || p == pp[1] {
- return p, true
- }
- }
- *ps = append(*ps, [2]value.Pointer{p, p})
- return p, false
-}
-
-func (ps *pointerReferences) Pop() {
- *ps = (*ps)[:len(*ps)-1]
-}
-
-// trunkReferences is metadata for a textNode indicating that the sub-tree
-// represents the value for either pointer in a pair of references.
-type trunkReferences struct{ pp [2]value.Pointer }
-
-// trunkReference is metadata for a textNode indicating that the sub-tree
-// represents the value for the given pointer reference.
-type trunkReference struct{ p value.Pointer }
-
-// leafReference is metadata for a textNode indicating that the value is
-// truncated as it refers to another part of the tree (i.e., a trunk).
-type leafReference struct{ p value.Pointer }
-
-func wrapTrunkReferences(pp [2]value.Pointer, s textNode) textNode {
- switch {
- case pp[0].IsNil():
- return &textWrap{Value: s, Metadata: trunkReference{pp[1]}}
- case pp[1].IsNil():
- return &textWrap{Value: s, Metadata: trunkReference{pp[0]}}
- case pp[0] == pp[1]:
- return &textWrap{Value: s, Metadata: trunkReference{pp[0]}}
- default:
- return &textWrap{Value: s, Metadata: trunkReferences{pp}}
- }
-}
-func wrapTrunkReference(p value.Pointer, printAddress bool, s textNode) textNode {
- var prefix string
- if printAddress {
- prefix = formatPointer(p, true)
- }
- return &textWrap{Prefix: prefix, Value: s, Metadata: trunkReference{p}}
-}
-func makeLeafReference(p value.Pointer, printAddress bool) textNode {
- out := &textWrap{Prefix: "(", Value: textEllipsis, Suffix: ")"}
- var prefix string
- if printAddress {
- prefix = formatPointer(p, true)
- }
- return &textWrap{Prefix: prefix, Value: out, Metadata: leafReference{p}}
-}
-
-// resolveReferences walks the textNode tree searching for any leaf reference
-// metadata and resolves each against the corresponding trunk references.
-// Since pointer addresses in memory are not particularly readable to the user,
-// it replaces each pointer value with an arbitrary and unique reference ID.
-func resolveReferences(s textNode) {
- var walkNodes func(textNode, func(textNode))
- walkNodes = func(s textNode, f func(textNode)) {
- f(s)
- switch s := s.(type) {
- case *textWrap:
- walkNodes(s.Value, f)
- case textList:
- for _, r := range s {
- walkNodes(r.Value, f)
- }
- }
- }
-
- // Collect all trunks and leaves with reference metadata.
- var trunks, leaves []*textWrap
- walkNodes(s, func(s textNode) {
- if s, ok := s.(*textWrap); ok {
- switch s.Metadata.(type) {
- case leafReference:
- leaves = append(leaves, s)
- case trunkReference, trunkReferences:
- trunks = append(trunks, s)
- }
- }
- })
-
- // No leaf references to resolve.
- if len(leaves) == 0 {
- return
- }
-
- // Collect the set of all leaf references to resolve.
- leafPtrs := make(map[value.Pointer]bool)
- for _, leaf := range leaves {
- leafPtrs[leaf.Metadata.(leafReference).p] = true
- }
-
- // Collect the set of trunk pointers that are always paired together.
- // This allows us to assign a single ID to both pointers for brevity.
- // If a pointer in a pair ever occurs by itself or as a different pair,
- // then the pair is broken.
- pairedTrunkPtrs := make(map[value.Pointer]value.Pointer)
- unpair := func(p value.Pointer) {
- if !pairedTrunkPtrs[p].IsNil() {
- pairedTrunkPtrs[pairedTrunkPtrs[p]] = value.Pointer{} // invalidate other half
- }
- pairedTrunkPtrs[p] = value.Pointer{} // invalidate this half
- }
- for _, trunk := range trunks {
- switch p := trunk.Metadata.(type) {
- case trunkReference:
- unpair(p.p) // standalone pointer cannot be part of a pair
- case trunkReferences:
- p0, ok0 := pairedTrunkPtrs[p.pp[0]]
- p1, ok1 := pairedTrunkPtrs[p.pp[1]]
- switch {
- case !ok0 && !ok1:
- // Register the newly seen pair.
- pairedTrunkPtrs[p.pp[0]] = p.pp[1]
- pairedTrunkPtrs[p.pp[1]] = p.pp[0]
- case ok0 && ok1 && p0 == p.pp[1] && p1 == p.pp[0]:
- // Exact pair already seen; do nothing.
- default:
- // Pair conflicts with some other pair; break all pairs.
- unpair(p.pp[0])
- unpair(p.pp[1])
- }
- }
- }
-
- // Correlate each pointer referenced by leaves to a unique identifier,
- // and print the IDs for each trunk that matches those pointers.
- var nextID uint
- ptrIDs := make(map[value.Pointer]uint)
- newID := func() uint {
- id := nextID
- nextID++
- return id
- }
- for _, trunk := range trunks {
- switch p := trunk.Metadata.(type) {
- case trunkReference:
- if print := leafPtrs[p.p]; print {
- id, ok := ptrIDs[p.p]
- if !ok {
- id = newID()
- ptrIDs[p.p] = id
- }
- trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id))
- }
- case trunkReferences:
- print0 := leafPtrs[p.pp[0]]
- print1 := leafPtrs[p.pp[1]]
- if print0 || print1 {
- id0, ok0 := ptrIDs[p.pp[0]]
- id1, ok1 := ptrIDs[p.pp[1]]
- isPair := pairedTrunkPtrs[p.pp[0]] == p.pp[1] && pairedTrunkPtrs[p.pp[1]] == p.pp[0]
- if isPair {
- var id uint
- assert(ok0 == ok1) // must be seen together or not at all
- if ok0 {
- assert(id0 == id1) // must have the same ID
- id = id0
- } else {
- id = newID()
- ptrIDs[p.pp[0]] = id
- ptrIDs[p.pp[1]] = id
- }
- trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id))
- } else {
- if print0 && !ok0 {
- id0 = newID()
- ptrIDs[p.pp[0]] = id0
- }
- if print1 && !ok1 {
- id1 = newID()
- ptrIDs[p.pp[1]] = id1
- }
- switch {
- case print0 && print1:
- trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0)+","+formatReference(id1))
- case print0:
- trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0))
- case print1:
- trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id1))
- }
- }
- }
- }
- }
-
- // Update all leaf references with the unique identifier.
- for _, leaf := range leaves {
- if id, ok := ptrIDs[leaf.Metadata.(leafReference).p]; ok {
- leaf.Prefix = updateReferencePrefix(leaf.Prefix, formatReference(id))
- }
- }
-}
-
-func formatReference(id uint) string {
- return fmt.Sprintf("ref#%d", id)
-}
-
-func updateReferencePrefix(prefix, ref string) string {
- if prefix == "" {
- return pointerDelimPrefix + ref + pointerDelimSuffix
- }
- suffix := strings.TrimPrefix(prefix, pointerDelimPrefix)
- return pointerDelimPrefix + ref + ": " + suffix
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/report_reflect.go b/vendor/github.com/google/go-cmp/cmp/report_reflect.go
deleted file mode 100644
index 2ab41fa..0000000
--- a/vendor/github.com/google/go-cmp/cmp/report_reflect.go
+++ /dev/null
@@ -1,414 +0,0 @@
-// Copyright 2019, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import (
- "bytes"
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "unicode"
- "unicode/utf8"
-
- "github.com/google/go-cmp/cmp/internal/value"
-)
-
-var (
- anyType = reflect.TypeOf((*interface{})(nil)).Elem()
- stringType = reflect.TypeOf((*string)(nil)).Elem()
- bytesType = reflect.TypeOf((*[]byte)(nil)).Elem()
- byteType = reflect.TypeOf((*byte)(nil)).Elem()
-)
-
-type formatValueOptions struct {
- // AvoidStringer controls whether to avoid calling custom stringer
- // methods like error.Error or fmt.Stringer.String.
- AvoidStringer bool
-
- // PrintAddresses controls whether to print the address of all pointers,
- // slice elements, and maps.
- PrintAddresses bool
-
- // QualifiedNames controls whether FormatType uses the fully qualified name
- // (including the full package path as opposed to just the package name).
- QualifiedNames bool
-
- // VerbosityLevel controls the amount of output to produce.
- // A higher value produces more output. A value of zero or lower produces
- // no output (represented using an ellipsis).
- // If LimitVerbosity is false, then the level is treated as infinite.
- VerbosityLevel int
-
- // LimitVerbosity specifies that formatting should respect VerbosityLevel.
- LimitVerbosity bool
-}
-
-// FormatType prints the type as if it were wrapping s.
-// This may return s as-is depending on the current type and TypeMode mode.
-func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode {
- // Check whether to emit the type or not.
- switch opts.TypeMode {
- case autoType:
- switch t.Kind() {
- case reflect.Struct, reflect.Slice, reflect.Array, reflect.Map:
- if s.Equal(textNil) {
- return s
- }
- default:
- return s
- }
- if opts.DiffMode == diffIdentical {
- return s // elide type for identical nodes
- }
- case elideType:
- return s
- }
-
- // Determine the type label, applying special handling for unnamed types.
- typeName := value.TypeString(t, opts.QualifiedNames)
- if t.Name() == "" {
- // According to Go grammar, certain type literals contain symbols that
- // do not strongly bind to the next lexicographical token (e.g., *T).
- switch t.Kind() {
- case reflect.Chan, reflect.Func, reflect.Ptr:
- typeName = "(" + typeName + ")"
- }
- }
- return &textWrap{Prefix: typeName, Value: wrapParens(s)}
-}
-
-// wrapParens wraps s with a set of parenthesis, but avoids it if the
-// wrapped node itself is already surrounded by a pair of parenthesis or braces.
-// It handles unwrapping one level of pointer-reference nodes.
-func wrapParens(s textNode) textNode {
- var refNode *textWrap
- if s2, ok := s.(*textWrap); ok {
- // Unwrap a single pointer reference node.
- switch s2.Metadata.(type) {
- case leafReference, trunkReference, trunkReferences:
- refNode = s2
- if s3, ok := refNode.Value.(*textWrap); ok {
- s2 = s3
- }
- }
-
- // Already has delimiters that make parenthesis unnecessary.
- hasParens := strings.HasPrefix(s2.Prefix, "(") && strings.HasSuffix(s2.Suffix, ")")
- hasBraces := strings.HasPrefix(s2.Prefix, "{") && strings.HasSuffix(s2.Suffix, "}")
- if hasParens || hasBraces {
- return s
- }
- }
- if refNode != nil {
- refNode.Value = &textWrap{Prefix: "(", Value: refNode.Value, Suffix: ")"}
- return s
- }
- return &textWrap{Prefix: "(", Value: s, Suffix: ")"}
-}
-
-// FormatValue prints the reflect.Value, taking extra care to avoid descending
-// into pointers already in ptrs. As pointers are visited, ptrs is also updated.
-func (opts formatOptions) FormatValue(v reflect.Value, parentKind reflect.Kind, ptrs *pointerReferences) (out textNode) {
- if !v.IsValid() {
- return nil
- }
- t := v.Type()
-
- // Check slice element for cycles.
- if parentKind == reflect.Slice {
- ptrRef, visited := ptrs.Push(v.Addr())
- if visited {
- return makeLeafReference(ptrRef, false)
- }
- defer ptrs.Pop()
- defer func() { out = wrapTrunkReference(ptrRef, false, out) }()
- }
-
- // Check whether there is an Error or String method to call.
- if !opts.AvoidStringer && v.CanInterface() {
- // Avoid calling Error or String methods on nil receivers since many
- // implementations crash when doing so.
- if (t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface) || !v.IsNil() {
- var prefix, strVal string
- func() {
- // Swallow and ignore any panics from String or Error.
- defer func() { recover() }()
- switch v := v.Interface().(type) {
- case error:
- strVal = v.Error()
- prefix = "e"
- case fmt.Stringer:
- strVal = v.String()
- prefix = "s"
- }
- }()
- if prefix != "" {
- return opts.formatString(prefix, strVal)
- }
- }
- }
-
- // Check whether to explicitly wrap the result with the type.
- var skipType bool
- defer func() {
- if !skipType {
- out = opts.FormatType(t, out)
- }
- }()
-
- switch t.Kind() {
- case reflect.Bool:
- return textLine(fmt.Sprint(v.Bool()))
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return textLine(fmt.Sprint(v.Int()))
- case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return textLine(fmt.Sprint(v.Uint()))
- case reflect.Uint8:
- if parentKind == reflect.Slice || parentKind == reflect.Array {
- return textLine(formatHex(v.Uint()))
- }
- return textLine(fmt.Sprint(v.Uint()))
- case reflect.Uintptr:
- return textLine(formatHex(v.Uint()))
- case reflect.Float32, reflect.Float64:
- return textLine(fmt.Sprint(v.Float()))
- case reflect.Complex64, reflect.Complex128:
- return textLine(fmt.Sprint(v.Complex()))
- case reflect.String:
- return opts.formatString("", v.String())
- case reflect.UnsafePointer, reflect.Chan, reflect.Func:
- return textLine(formatPointer(value.PointerOf(v), true))
- case reflect.Struct:
- var list textList
- v := makeAddressable(v) // needed for retrieveUnexportedField
- maxLen := v.NumField()
- if opts.LimitVerbosity {
- maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc...
- opts.VerbosityLevel--
- }
- for i := 0; i < v.NumField(); i++ {
- vv := v.Field(i)
- if vv.IsZero() {
- continue // Elide fields with zero values
- }
- if len(list) == maxLen {
- list.AppendEllipsis(diffStats{})
- break
- }
- sf := t.Field(i)
- if supportExporters && !isExported(sf.Name) {
- vv = retrieveUnexportedField(v, sf, true)
- }
- s := opts.WithTypeMode(autoType).FormatValue(vv, t.Kind(), ptrs)
- list = append(list, textRecord{Key: sf.Name, Value: s})
- }
- return &textWrap{Prefix: "{", Value: list, Suffix: "}"}
- case reflect.Slice:
- if v.IsNil() {
- return textNil
- }
-
- // Check whether this is a []byte of text data.
- if t.Elem() == byteType {
- b := v.Bytes()
- isPrintSpace := func(r rune) bool { return unicode.IsPrint(r) || unicode.IsSpace(r) }
- if len(b) > 0 && utf8.Valid(b) && len(bytes.TrimFunc(b, isPrintSpace)) == 0 {
- out = opts.formatString("", string(b))
- skipType = true
- return opts.FormatType(t, out)
- }
- }
-
- fallthrough
- case reflect.Array:
- maxLen := v.Len()
- if opts.LimitVerbosity {
- maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc...
- opts.VerbosityLevel--
- }
- var list textList
- for i := 0; i < v.Len(); i++ {
- if len(list) == maxLen {
- list.AppendEllipsis(diffStats{})
- break
- }
- s := opts.WithTypeMode(elideType).FormatValue(v.Index(i), t.Kind(), ptrs)
- list = append(list, textRecord{Value: s})
- }
-
- out = &textWrap{Prefix: "{", Value: list, Suffix: "}"}
- if t.Kind() == reflect.Slice && opts.PrintAddresses {
- header := fmt.Sprintf("ptr:%v, len:%d, cap:%d", formatPointer(value.PointerOf(v), false), v.Len(), v.Cap())
- out = &textWrap{Prefix: pointerDelimPrefix + header + pointerDelimSuffix, Value: out}
- }
- return out
- case reflect.Map:
- if v.IsNil() {
- return textNil
- }
-
- // Check pointer for cycles.
- ptrRef, visited := ptrs.Push(v)
- if visited {
- return makeLeafReference(ptrRef, opts.PrintAddresses)
- }
- defer ptrs.Pop()
-
- maxLen := v.Len()
- if opts.LimitVerbosity {
- maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc...
- opts.VerbosityLevel--
- }
- var list textList
- for _, k := range value.SortKeys(v.MapKeys()) {
- if len(list) == maxLen {
- list.AppendEllipsis(diffStats{})
- break
- }
- sk := formatMapKey(k, false, ptrs)
- sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), t.Kind(), ptrs)
- list = append(list, textRecord{Key: sk, Value: sv})
- }
-
- out = &textWrap{Prefix: "{", Value: list, Suffix: "}"}
- out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out)
- return out
- case reflect.Ptr:
- if v.IsNil() {
- return textNil
- }
-
- // Check pointer for cycles.
- ptrRef, visited := ptrs.Push(v)
- if visited {
- out = makeLeafReference(ptrRef, opts.PrintAddresses)
- return &textWrap{Prefix: "&", Value: out}
- }
- defer ptrs.Pop()
-
- // Skip the name only if this is an unnamed pointer type.
- // Otherwise taking the address of a value does not reproduce
- // the named pointer type.
- if v.Type().Name() == "" {
- skipType = true // Let the underlying value print the type instead
- }
- out = opts.FormatValue(v.Elem(), t.Kind(), ptrs)
- out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out)
- out = &textWrap{Prefix: "&", Value: out}
- return out
- case reflect.Interface:
- if v.IsNil() {
- return textNil
- }
- // Interfaces accept different concrete types,
- // so configure the underlying value to explicitly print the type.
- return opts.WithTypeMode(emitType).FormatValue(v.Elem(), t.Kind(), ptrs)
- default:
- panic(fmt.Sprintf("%v kind not handled", v.Kind()))
- }
-}
-
-func (opts formatOptions) formatString(prefix, s string) textNode {
- maxLen := len(s)
- maxLines := strings.Count(s, "\n") + 1
- if opts.LimitVerbosity {
- maxLen = (1 << opts.verbosity()) << 5 // 32, 64, 128, 256, etc...
- maxLines = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc...
- }
-
- // For multiline strings, use the triple-quote syntax,
- // but only use it when printing removed or inserted nodes since
- // we only want the extra verbosity for those cases.
- lines := strings.Split(strings.TrimSuffix(s, "\n"), "\n")
- isTripleQuoted := len(lines) >= 4 && (opts.DiffMode == '-' || opts.DiffMode == '+')
- for i := 0; i < len(lines) && isTripleQuoted; i++ {
- lines[i] = strings.TrimPrefix(strings.TrimSuffix(lines[i], "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support
- isPrintable := func(r rune) bool {
- return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable
- }
- line := lines[i]
- isTripleQuoted = !strings.HasPrefix(strings.TrimPrefix(line, prefix), `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == "" && len(line) <= maxLen
- }
- if isTripleQuoted {
- var list textList
- list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(prefix + `"""`), ElideComma: true})
- for i, line := range lines {
- if numElided := len(lines) - i; i == maxLines-1 && numElided > 1 {
- comment := commentString(fmt.Sprintf("%d elided lines", numElided))
- list = append(list, textRecord{Diff: opts.DiffMode, Value: textEllipsis, ElideComma: true, Comment: comment})
- break
- }
- list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(line), ElideComma: true})
- }
- list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(prefix + `"""`), ElideComma: true})
- return &textWrap{Prefix: "(", Value: list, Suffix: ")"}
- }
-
- // Format the string as a single-line quoted string.
- if len(s) > maxLen+len(textEllipsis) {
- return textLine(prefix + formatString(s[:maxLen]) + string(textEllipsis))
- }
- return textLine(prefix + formatString(s))
-}
-
-// formatMapKey formats v as if it were a map key.
-// The result is guaranteed to be a single line.
-func formatMapKey(v reflect.Value, disambiguate bool, ptrs *pointerReferences) string {
- var opts formatOptions
- opts.DiffMode = diffIdentical
- opts.TypeMode = elideType
- opts.PrintAddresses = disambiguate
- opts.AvoidStringer = disambiguate
- opts.QualifiedNames = disambiguate
- opts.VerbosityLevel = maxVerbosityPreset
- opts.LimitVerbosity = true
- s := opts.FormatValue(v, reflect.Map, ptrs).String()
- return strings.TrimSpace(s)
-}
-
-// formatString prints s as a double-quoted or backtick-quoted string.
-func formatString(s string) string {
- // Use quoted string if it the same length as a raw string literal.
- // Otherwise, attempt to use the raw string form.
- qs := strconv.Quote(s)
- if len(qs) == 1+len(s)+1 {
- return qs
- }
-
- // Disallow newlines to ensure output is a single line.
- // Only allow printable runes for readability purposes.
- rawInvalid := func(r rune) bool {
- return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t')
- }
- if utf8.ValidString(s) && strings.IndexFunc(s, rawInvalid) < 0 {
- return "`" + s + "`"
- }
- return qs
-}
-
-// formatHex prints u as a hexadecimal integer in Go notation.
-func formatHex(u uint64) string {
- var f string
- switch {
- case u <= 0xff:
- f = "0x%02x"
- case u <= 0xffff:
- f = "0x%04x"
- case u <= 0xffffff:
- f = "0x%06x"
- case u <= 0xffffffff:
- f = "0x%08x"
- case u <= 0xffffffffff:
- f = "0x%010x"
- case u <= 0xffffffffffff:
- f = "0x%012x"
- case u <= 0xffffffffffffff:
- f = "0x%014x"
- case u <= 0xffffffffffffffff:
- f = "0x%016x"
- }
- return fmt.Sprintf(f, u)
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/report_slices.go b/vendor/github.com/google/go-cmp/cmp/report_slices.go
deleted file mode 100644
index 23e444f..0000000
--- a/vendor/github.com/google/go-cmp/cmp/report_slices.go
+++ /dev/null
@@ -1,614 +0,0 @@
-// Copyright 2019, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import (
- "bytes"
- "fmt"
- "math"
- "reflect"
- "strconv"
- "strings"
- "unicode"
- "unicode/utf8"
-
- "github.com/google/go-cmp/cmp/internal/diff"
-)
-
-// CanFormatDiffSlice reports whether we support custom formatting for nodes
-// that are slices of primitive kinds or strings.
-func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool {
- switch {
- case opts.DiffMode != diffUnknown:
- return false // Must be formatting in diff mode
- case v.NumDiff == 0:
- return false // No differences detected
- case !v.ValueX.IsValid() || !v.ValueY.IsValid():
- return false // Both values must be valid
- case v.NumIgnored > 0:
- return false // Some ignore option was used
- case v.NumTransformed > 0:
- return false // Some transform option was used
- case v.NumCompared > 1:
- return false // More than one comparison was used
- case v.NumCompared == 1 && v.Type.Name() != "":
- // The need for cmp to check applicability of options on every element
- // in a slice is a significant performance detriment for large []byte.
- // The workaround is to specify Comparer(bytes.Equal),
- // which enables cmp to compare []byte more efficiently.
- // If they differ, we still want to provide batched diffing.
- // The logic disallows named types since they tend to have their own
- // String method, with nicer formatting than what this provides.
- return false
- }
-
- // Check whether this is an interface with the same concrete types.
- t := v.Type
- vx, vy := v.ValueX, v.ValueY
- if t.Kind() == reflect.Interface && !vx.IsNil() && !vy.IsNil() && vx.Elem().Type() == vy.Elem().Type() {
- vx, vy = vx.Elem(), vy.Elem()
- t = vx.Type()
- }
-
- // Check whether we provide specialized diffing for this type.
- switch t.Kind() {
- case reflect.String:
- case reflect.Array, reflect.Slice:
- // Only slices of primitive types have specialized handling.
- switch t.Elem().Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
- reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
- default:
- return false
- }
-
- // Both slice values have to be non-empty.
- if t.Kind() == reflect.Slice && (vx.Len() == 0 || vy.Len() == 0) {
- return false
- }
-
- // If a sufficient number of elements already differ,
- // use specialized formatting even if length requirement is not met.
- if v.NumDiff > v.NumSame {
- return true
- }
- default:
- return false
- }
-
- // Use specialized string diffing for longer slices or strings.
- const minLength = 32
- return vx.Len() >= minLength && vy.Len() >= minLength
-}
-
-// FormatDiffSlice prints a diff for the slices (or strings) represented by v.
-// This provides custom-tailored logic to make printing of differences in
-// textual strings and slices of primitive kinds more readable.
-func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode {
- assert(opts.DiffMode == diffUnknown)
- t, vx, vy := v.Type, v.ValueX, v.ValueY
- if t.Kind() == reflect.Interface {
- vx, vy = vx.Elem(), vy.Elem()
- t = vx.Type()
- opts = opts.WithTypeMode(emitType)
- }
-
- // Auto-detect the type of the data.
- var sx, sy string
- var ssx, ssy []string
- var isString, isMostlyText, isPureLinedText, isBinary bool
- switch {
- case t.Kind() == reflect.String:
- sx, sy = vx.String(), vy.String()
- isString = true
- case t.Kind() == reflect.Slice && t.Elem() == byteType:
- sx, sy = string(vx.Bytes()), string(vy.Bytes())
- isString = true
- case t.Kind() == reflect.Array:
- // Arrays need to be addressable for slice operations to work.
- vx2, vy2 := reflect.New(t).Elem(), reflect.New(t).Elem()
- vx2.Set(vx)
- vy2.Set(vy)
- vx, vy = vx2, vy2
- }
- if isString {
- var numTotalRunes, numValidRunes, numLines, lastLineIdx, maxLineLen int
- for i, r := range sx + sy {
- numTotalRunes++
- if (unicode.IsPrint(r) || unicode.IsSpace(r)) && r != utf8.RuneError {
- numValidRunes++
- }
- if r == '\n' {
- if maxLineLen < i-lastLineIdx {
- maxLineLen = i - lastLineIdx
- }
- lastLineIdx = i + 1
- numLines++
- }
- }
- isPureText := numValidRunes == numTotalRunes
- isMostlyText = float64(numValidRunes) > math.Floor(0.90*float64(numTotalRunes))
- isPureLinedText = isPureText && numLines >= 4 && maxLineLen <= 1024
- isBinary = !isMostlyText
-
- // Avoid diffing by lines if it produces a significantly more complex
- // edit script than diffing by bytes.
- if isPureLinedText {
- ssx = strings.Split(sx, "\n")
- ssy = strings.Split(sy, "\n")
- esLines := diff.Difference(len(ssx), len(ssy), func(ix, iy int) diff.Result {
- return diff.BoolResult(ssx[ix] == ssy[iy])
- })
- esBytes := diff.Difference(len(sx), len(sy), func(ix, iy int) diff.Result {
- return diff.BoolResult(sx[ix] == sy[iy])
- })
- efficiencyLines := float64(esLines.Dist()) / float64(len(esLines))
- efficiencyBytes := float64(esBytes.Dist()) / float64(len(esBytes))
- quotedLength := len(strconv.Quote(sx + sy))
- unquotedLength := len(sx) + len(sy)
- escapeExpansionRatio := float64(quotedLength) / float64(unquotedLength)
- isPureLinedText = efficiencyLines < 4*efficiencyBytes || escapeExpansionRatio > 1.1
- }
- }
-
- // Format the string into printable records.
- var list textList
- var delim string
- switch {
- // If the text appears to be multi-lined text,
- // then perform differencing across individual lines.
- case isPureLinedText:
- list = opts.formatDiffSlice(
- reflect.ValueOf(ssx), reflect.ValueOf(ssy), 1, "line",
- func(v reflect.Value, d diffMode) textRecord {
- s := formatString(v.Index(0).String())
- return textRecord{Diff: d, Value: textLine(s)}
- },
- )
- delim = "\n"
-
- // If possible, use a custom triple-quote (""") syntax for printing
- // differences in a string literal. This format is more readable,
- // but has edge-cases where differences are visually indistinguishable.
- // This format is avoided under the following conditions:
- // - A line starts with `"""`
- // - A line starts with "..."
- // - A line contains non-printable characters
- // - Adjacent different lines differ only by whitespace
- //
- // For example:
- //
- // """
- // ... // 3 identical lines
- // foo
- // bar
- // - baz
- // + BAZ
- // """
- isTripleQuoted := true
- prevRemoveLines := map[string]bool{}
- prevInsertLines := map[string]bool{}
- var list2 textList
- list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true})
- for _, r := range list {
- if !r.Value.Equal(textEllipsis) {
- line, _ := strconv.Unquote(string(r.Value.(textLine)))
- line = strings.TrimPrefix(strings.TrimSuffix(line, "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support
- normLine := strings.Map(func(r rune) rune {
- if unicode.IsSpace(r) {
- return -1 // drop whitespace to avoid visually indistinguishable output
- }
- return r
- }, line)
- isPrintable := func(r rune) bool {
- return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable
- }
- isTripleQuoted = !strings.HasPrefix(line, `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == ""
- switch r.Diff {
- case diffRemoved:
- isTripleQuoted = isTripleQuoted && !prevInsertLines[normLine]
- prevRemoveLines[normLine] = true
- case diffInserted:
- isTripleQuoted = isTripleQuoted && !prevRemoveLines[normLine]
- prevInsertLines[normLine] = true
- }
- if !isTripleQuoted {
- break
- }
- r.Value = textLine(line)
- r.ElideComma = true
- }
- if !(r.Diff == diffRemoved || r.Diff == diffInserted) { // start a new non-adjacent difference group
- prevRemoveLines = map[string]bool{}
- prevInsertLines = map[string]bool{}
- }
- list2 = append(list2, r)
- }
- if r := list2[len(list2)-1]; r.Diff == diffIdentical && len(r.Value.(textLine)) == 0 {
- list2 = list2[:len(list2)-1] // elide single empty line at the end
- }
- list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true})
- if isTripleQuoted {
- var out textNode = &textWrap{Prefix: "(", Value: list2, Suffix: ")"}
- switch t.Kind() {
- case reflect.String:
- if t != stringType {
- out = opts.FormatType(t, out)
- }
- case reflect.Slice:
- // Always emit type for slices since the triple-quote syntax
- // looks like a string (not a slice).
- opts = opts.WithTypeMode(emitType)
- out = opts.FormatType(t, out)
- }
- return out
- }
-
- // If the text appears to be single-lined text,
- // then perform differencing in approximately fixed-sized chunks.
- // The output is printed as quoted strings.
- case isMostlyText:
- list = opts.formatDiffSlice(
- reflect.ValueOf(sx), reflect.ValueOf(sy), 64, "byte",
- func(v reflect.Value, d diffMode) textRecord {
- s := formatString(v.String())
- return textRecord{Diff: d, Value: textLine(s)}
- },
- )
-
- // If the text appears to be binary data,
- // then perform differencing in approximately fixed-sized chunks.
- // The output is inspired by hexdump.
- case isBinary:
- list = opts.formatDiffSlice(
- reflect.ValueOf(sx), reflect.ValueOf(sy), 16, "byte",
- func(v reflect.Value, d diffMode) textRecord {
- var ss []string
- for i := 0; i < v.Len(); i++ {
- ss = append(ss, formatHex(v.Index(i).Uint()))
- }
- s := strings.Join(ss, ", ")
- comment := commentString(fmt.Sprintf("%c|%v|", d, formatASCII(v.String())))
- return textRecord{Diff: d, Value: textLine(s), Comment: comment}
- },
- )
-
- // For all other slices of primitive types,
- // then perform differencing in approximately fixed-sized chunks.
- // The size of each chunk depends on the width of the element kind.
- default:
- var chunkSize int
- if t.Elem().Kind() == reflect.Bool {
- chunkSize = 16
- } else {
- switch t.Elem().Bits() {
- case 8:
- chunkSize = 16
- case 16:
- chunkSize = 12
- case 32:
- chunkSize = 8
- default:
- chunkSize = 8
- }
- }
- list = opts.formatDiffSlice(
- vx, vy, chunkSize, t.Elem().Kind().String(),
- func(v reflect.Value, d diffMode) textRecord {
- var ss []string
- for i := 0; i < v.Len(); i++ {
- switch t.Elem().Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- ss = append(ss, fmt.Sprint(v.Index(i).Int()))
- case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- ss = append(ss, fmt.Sprint(v.Index(i).Uint()))
- case reflect.Uint8, reflect.Uintptr:
- ss = append(ss, formatHex(v.Index(i).Uint()))
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
- ss = append(ss, fmt.Sprint(v.Index(i).Interface()))
- }
- }
- s := strings.Join(ss, ", ")
- return textRecord{Diff: d, Value: textLine(s)}
- },
- )
- }
-
- // Wrap the output with appropriate type information.
- var out textNode = &textWrap{Prefix: "{", Value: list, Suffix: "}"}
- if !isMostlyText {
- // The "{...}" byte-sequence literal is not valid Go syntax for strings.
- // Emit the type for extra clarity (e.g. "string{...}").
- if t.Kind() == reflect.String {
- opts = opts.WithTypeMode(emitType)
- }
- return opts.FormatType(t, out)
- }
- switch t.Kind() {
- case reflect.String:
- out = &textWrap{Prefix: "strings.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)}
- if t != stringType {
- out = opts.FormatType(t, out)
- }
- case reflect.Slice:
- out = &textWrap{Prefix: "bytes.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)}
- if t != bytesType {
- out = opts.FormatType(t, out)
- }
- }
- return out
-}
-
-// formatASCII formats s as an ASCII string.
-// This is useful for printing binary strings in a semi-legible way.
-func formatASCII(s string) string {
- b := bytes.Repeat([]byte{'.'}, len(s))
- for i := 0; i < len(s); i++ {
- if ' ' <= s[i] && s[i] <= '~' {
- b[i] = s[i]
- }
- }
- return string(b)
-}
-
-func (opts formatOptions) formatDiffSlice(
- vx, vy reflect.Value, chunkSize int, name string,
- makeRec func(reflect.Value, diffMode) textRecord,
-) (list textList) {
- eq := func(ix, iy int) bool {
- return vx.Index(ix).Interface() == vy.Index(iy).Interface()
- }
- es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result {
- return diff.BoolResult(eq(ix, iy))
- })
-
- appendChunks := func(v reflect.Value, d diffMode) int {
- n0 := v.Len()
- for v.Len() > 0 {
- n := chunkSize
- if n > v.Len() {
- n = v.Len()
- }
- list = append(list, makeRec(v.Slice(0, n), d))
- v = v.Slice(n, v.Len())
- }
- return n0 - v.Len()
- }
-
- var numDiffs int
- maxLen := -1
- if opts.LimitVerbosity {
- maxLen = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc...
- opts.VerbosityLevel--
- }
-
- groups := coalesceAdjacentEdits(name, es)
- groups = coalesceInterveningIdentical(groups, chunkSize/4)
- groups = cleanupSurroundingIdentical(groups, eq)
- maxGroup := diffStats{Name: name}
- for i, ds := range groups {
- if maxLen >= 0 && numDiffs >= maxLen {
- maxGroup = maxGroup.Append(ds)
- continue
- }
-
- // Print equal.
- if ds.NumDiff() == 0 {
- // Compute the number of leading and trailing equal bytes to print.
- var numLo, numHi int
- numEqual := ds.NumIgnored + ds.NumIdentical
- for numLo < chunkSize*numContextRecords && numLo+numHi < numEqual && i != 0 {
- numLo++
- }
- for numHi < chunkSize*numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 {
- numHi++
- }
- if numEqual-(numLo+numHi) <= chunkSize && ds.NumIgnored == 0 {
- numHi = numEqual - numLo // Avoid pointless coalescing of single equal row
- }
-
- // Print the equal bytes.
- appendChunks(vx.Slice(0, numLo), diffIdentical)
- if numEqual > numLo+numHi {
- ds.NumIdentical -= numLo + numHi
- list.AppendEllipsis(ds)
- }
- appendChunks(vx.Slice(numEqual-numHi, numEqual), diffIdentical)
- vx = vx.Slice(numEqual, vx.Len())
- vy = vy.Slice(numEqual, vy.Len())
- continue
- }
-
- // Print unequal.
- len0 := len(list)
- nx := appendChunks(vx.Slice(0, ds.NumIdentical+ds.NumRemoved+ds.NumModified), diffRemoved)
- vx = vx.Slice(nx, vx.Len())
- ny := appendChunks(vy.Slice(0, ds.NumIdentical+ds.NumInserted+ds.NumModified), diffInserted)
- vy = vy.Slice(ny, vy.Len())
- numDiffs += len(list) - len0
- }
- if maxGroup.IsZero() {
- assert(vx.Len() == 0 && vy.Len() == 0)
- } else {
- list.AppendEllipsis(maxGroup)
- }
- return list
-}
-
-// coalesceAdjacentEdits coalesces the list of edits into groups of adjacent
-// equal or unequal counts.
-//
-// Example:
-//
-// Input: "..XXY...Y"
-// Output: [
-// {NumIdentical: 2},
-// {NumRemoved: 2, NumInserted 1},
-// {NumIdentical: 3},
-// {NumInserted: 1},
-// ]
-func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) {
- var prevMode byte
- lastStats := func(mode byte) *diffStats {
- if prevMode != mode {
- groups = append(groups, diffStats{Name: name})
- prevMode = mode
- }
- return &groups[len(groups)-1]
- }
- for _, e := range es {
- switch e {
- case diff.Identity:
- lastStats('=').NumIdentical++
- case diff.UniqueX:
- lastStats('!').NumRemoved++
- case diff.UniqueY:
- lastStats('!').NumInserted++
- case diff.Modified:
- lastStats('!').NumModified++
- }
- }
- return groups
-}
-
-// coalesceInterveningIdentical coalesces sufficiently short (<= windowSize)
-// equal groups into adjacent unequal groups that currently result in a
-// dual inserted/removed printout. This acts as a high-pass filter to smooth
-// out high-frequency changes within the windowSize.
-//
-// Example:
-//
-// WindowSize: 16,
-// Input: [
-// {NumIdentical: 61}, // group 0
-// {NumRemoved: 3, NumInserted: 1}, // group 1
-// {NumIdentical: 6}, // ├── coalesce
-// {NumInserted: 2}, // ├── coalesce
-// {NumIdentical: 1}, // ├── coalesce
-// {NumRemoved: 9}, // └── coalesce
-// {NumIdentical: 64}, // group 2
-// {NumRemoved: 3, NumInserted: 1}, // group 3
-// {NumIdentical: 6}, // ├── coalesce
-// {NumInserted: 2}, // ├── coalesce
-// {NumIdentical: 1}, // ├── coalesce
-// {NumRemoved: 7}, // ├── coalesce
-// {NumIdentical: 1}, // ├── coalesce
-// {NumRemoved: 2}, // └── coalesce
-// {NumIdentical: 63}, // group 4
-// ]
-// Output: [
-// {NumIdentical: 61},
-// {NumIdentical: 7, NumRemoved: 12, NumInserted: 3},
-// {NumIdentical: 64},
-// {NumIdentical: 8, NumRemoved: 12, NumInserted: 3},
-// {NumIdentical: 63},
-// ]
-func coalesceInterveningIdentical(groups []diffStats, windowSize int) []diffStats {
- groups, groupsOrig := groups[:0], groups
- for i, ds := range groupsOrig {
- if len(groups) >= 2 && ds.NumDiff() > 0 {
- prev := &groups[len(groups)-2] // Unequal group
- curr := &groups[len(groups)-1] // Equal group
- next := &groupsOrig[i] // Unequal group
- hadX, hadY := prev.NumRemoved > 0, prev.NumInserted > 0
- hasX, hasY := next.NumRemoved > 0, next.NumInserted > 0
- if ((hadX || hasX) && (hadY || hasY)) && curr.NumIdentical <= windowSize {
- *prev = prev.Append(*curr).Append(*next)
- groups = groups[:len(groups)-1] // Truncate off equal group
- continue
- }
- }
- groups = append(groups, ds)
- }
- return groups
-}
-
-// cleanupSurroundingIdentical scans through all unequal groups, and
-// moves any leading sequence of equal elements to the preceding equal group and
-// moves and trailing sequence of equal elements to the succeeding equal group.
-//
-// This is necessary since coalesceInterveningIdentical may coalesce edit groups
-// together such that leading/trailing spans of equal elements becomes possible.
-// Note that this can occur even with an optimal diffing algorithm.
-//
-// Example:
-//
-// Input: [
-// {NumIdentical: 61},
-// {NumIdentical: 1 , NumRemoved: 11, NumInserted: 2}, // assume 3 leading identical elements
-// {NumIdentical: 67},
-// {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, // assume 10 trailing identical elements
-// {NumIdentical: 54},
-// ]
-// Output: [
-// {NumIdentical: 64}, // incremented by 3
-// {NumRemoved: 9},
-// {NumIdentical: 67},
-// {NumRemoved: 9},
-// {NumIdentical: 64}, // incremented by 10
-// ]
-func cleanupSurroundingIdentical(groups []diffStats, eq func(i, j int) bool) []diffStats {
- var ix, iy int // indexes into sequence x and y
- for i, ds := range groups {
- // Handle equal group.
- if ds.NumDiff() == 0 {
- ix += ds.NumIdentical
- iy += ds.NumIdentical
- continue
- }
-
- // Handle unequal group.
- nx := ds.NumIdentical + ds.NumRemoved + ds.NumModified
- ny := ds.NumIdentical + ds.NumInserted + ds.NumModified
- var numLeadingIdentical, numTrailingIdentical int
- for j := 0; j < nx && j < ny && eq(ix+j, iy+j); j++ {
- numLeadingIdentical++
- }
- for j := 0; j < nx && j < ny && eq(ix+nx-1-j, iy+ny-1-j); j++ {
- numTrailingIdentical++
- }
- if numIdentical := numLeadingIdentical + numTrailingIdentical; numIdentical > 0 {
- if numLeadingIdentical > 0 {
- // Remove leading identical span from this group and
- // insert it into the preceding group.
- if i-1 >= 0 {
- groups[i-1].NumIdentical += numLeadingIdentical
- } else {
- // No preceding group exists, so prepend a new group,
- // but do so after we finish iterating over all groups.
- defer func() {
- groups = append([]diffStats{{Name: groups[0].Name, NumIdentical: numLeadingIdentical}}, groups...)
- }()
- }
- // Increment indexes since the preceding group would have handled this.
- ix += numLeadingIdentical
- iy += numLeadingIdentical
- }
- if numTrailingIdentical > 0 {
- // Remove trailing identical span from this group and
- // insert it into the succeeding group.
- if i+1 < len(groups) {
- groups[i+1].NumIdentical += numTrailingIdentical
- } else {
- // No succeeding group exists, so append a new group,
- // but do so after we finish iterating over all groups.
- defer func() {
- groups = append(groups, diffStats{Name: groups[len(groups)-1].Name, NumIdentical: numTrailingIdentical})
- }()
- }
- // Do not increment indexes since the succeeding group will handle this.
- }
-
- // Update this group since some identical elements were removed.
- nx -= numIdentical
- ny -= numIdentical
- groups[i] = diffStats{Name: ds.Name, NumRemoved: nx, NumInserted: ny}
- }
- ix += nx
- iy += ny
- }
- return groups
-}
diff --git a/vendor/github.com/google/go-cmp/cmp/report_text.go b/vendor/github.com/google/go-cmp/cmp/report_text.go
deleted file mode 100644
index 388fcf5..0000000
--- a/vendor/github.com/google/go-cmp/cmp/report_text.go
+++ /dev/null
@@ -1,432 +0,0 @@
-// Copyright 2019, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import (
- "bytes"
- "fmt"
- "math/rand"
- "strings"
- "time"
- "unicode/utf8"
-
- "github.com/google/go-cmp/cmp/internal/flags"
-)
-
-var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0
-
-const maxColumnLength = 80
-
-type indentMode int
-
-func (n indentMode) appendIndent(b []byte, d diffMode) []byte {
- // The output of Diff is documented as being unstable to provide future
- // flexibility in changing the output for more humanly readable reports.
- // This logic intentionally introduces instability to the exact output
- // so that users can detect accidental reliance on stability early on,
- // rather than much later when an actual change to the format occurs.
- if flags.Deterministic || randBool {
- // Use regular spaces (U+0020).
- switch d {
- case diffUnknown, diffIdentical:
- b = append(b, " "...)
- case diffRemoved:
- b = append(b, "- "...)
- case diffInserted:
- b = append(b, "+ "...)
- }
- } else {
- // Use non-breaking spaces (U+00a0).
- switch d {
- case diffUnknown, diffIdentical:
- b = append(b, "  "...)
- case diffRemoved:
- b = append(b, "- "...)
- case diffInserted:
- b = append(b, "+ "...)
- }
- }
- return repeatCount(n).appendChar(b, '\t')
-}
-
-type repeatCount int
-
-func (n repeatCount) appendChar(b []byte, c byte) []byte {
- for ; n > 0; n-- {
- b = append(b, c)
- }
- return b
-}
-
-// textNode is a simplified tree-based representation of structured text.
-// Possible node types are textWrap, textList, or textLine.
-type textNode interface {
- // Len reports the length in bytes of a single-line version of the tree.
- // Nested textRecord.Diff and textRecord.Comment fields are ignored.
- Len() int
- // Equal reports whether the two trees are structurally identical.
- // Nested textRecord.Diff and textRecord.Comment fields are compared.
- Equal(textNode) bool
- // String returns the string representation of the text tree.
- // It is not guaranteed that len(x.String()) == x.Len(),
- // nor that x.String() == y.String() implies that x.Equal(y).
- String() string
-
- // formatCompactTo formats the contents of the tree as a single-line string
- // to the provided buffer. Any nested textRecord.Diff and textRecord.Comment
- // fields are ignored.
- //
- // However, not all nodes in the tree should be collapsed as a single-line.
- // If a node can be collapsed as a single-line, it is replaced by a textLine
- // node. Since the top-level node cannot replace itself, this also returns
- // the current node itself.
- //
- // This does not mutate the receiver.
- formatCompactTo([]byte, diffMode) ([]byte, textNode)
- // formatExpandedTo formats the contents of the tree as a multi-line string
- // to the provided buffer. In order for column alignment to operate well,
- // formatCompactTo must be called before calling formatExpandedTo.
- formatExpandedTo([]byte, diffMode, indentMode) []byte
-}
-
-// textWrap is a wrapper that concatenates a prefix and/or a suffix
-// to the underlying node.
-type textWrap struct {
- Prefix string // e.g., "bytes.Buffer{"
- Value textNode // textWrap | textList | textLine
- Suffix string // e.g., "}"
- Metadata interface{} // arbitrary metadata; has no effect on formatting
-}
-
-func (s *textWrap) Len() int {
- return len(s.Prefix) + s.Value.Len() + len(s.Suffix)
-}
-func (s1 *textWrap) Equal(s2 textNode) bool {
- if s2, ok := s2.(*textWrap); ok {
- return s1.Prefix == s2.Prefix && s1.Value.Equal(s2.Value) && s1.Suffix == s2.Suffix
- }
- return false
-}
-func (s *textWrap) String() string {
- var d diffMode
- var n indentMode
- _, s2 := s.formatCompactTo(nil, d)
- b := n.appendIndent(nil, d) // Leading indent
- b = s2.formatExpandedTo(b, d, n) // Main body
- b = append(b, '\n') // Trailing newline
- return string(b)
-}
-func (s *textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) {
- n0 := len(b) // Original buffer length
- b = append(b, s.Prefix...)
- b, s.Value = s.Value.formatCompactTo(b, d)
- b = append(b, s.Suffix...)
- if _, ok := s.Value.(textLine); ok {
- return b, textLine(b[n0:])
- }
- return b, s
-}
-func (s *textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte {
- b = append(b, s.Prefix...)
- b = s.Value.formatExpandedTo(b, d, n)
- b = append(b, s.Suffix...)
- return b
-}
-
-// textList is a comma-separated list of textWrap or textLine nodes.
-// The list may be formatted as multi-lines or single-line at the discretion
-// of the textList.formatCompactTo method.
-type textList []textRecord
-type textRecord struct {
- Diff diffMode // e.g., 0 or '-' or '+'
- Key string // e.g., "MyField"
- Value textNode // textWrap | textLine
- ElideComma bool // avoid trailing comma
- Comment fmt.Stringer // e.g., "6 identical fields"
-}
-
-// AppendEllipsis appends a new ellipsis node to the list if none already
-// exists at the end. If cs is non-zero it coalesces the statistics with the
-// previous diffStats.
-func (s *textList) AppendEllipsis(ds diffStats) {
- hasStats := !ds.IsZero()
- if len(*s) == 0 || !(*s)[len(*s)-1].Value.Equal(textEllipsis) {
- if hasStats {
- *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true, Comment: ds})
- } else {
- *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true})
- }
- return
- }
- if hasStats {
- (*s)[len(*s)-1].Comment = (*s)[len(*s)-1].Comment.(diffStats).Append(ds)
- }
-}
-
-func (s textList) Len() (n int) {
- for i, r := range s {
- n += len(r.Key)
- if r.Key != "" {
- n += len(": ")
- }
- n += r.Value.Len()
- if i < len(s)-1 {
- n += len(", ")
- }
- }
- return n
-}
-
-func (s1 textList) Equal(s2 textNode) bool {
- if s2, ok := s2.(textList); ok {
- if len(s1) != len(s2) {
- return false
- }
- for i := range s1 {
- r1, r2 := s1[i], s2[i]
- if !(r1.Diff == r2.Diff && r1.Key == r2.Key && r1.Value.Equal(r2.Value) && r1.Comment == r2.Comment) {
- return false
- }
- }
- return true
- }
- return false
-}
-
-func (s textList) String() string {
- return (&textWrap{Prefix: "{", Value: s, Suffix: "}"}).String()
-}
-
-func (s textList) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) {
- s = append(textList(nil), s...) // Avoid mutating original
-
- // Determine whether we can collapse this list as a single line.
- n0 := len(b) // Original buffer length
- var multiLine bool
- for i, r := range s {
- if r.Diff == diffInserted || r.Diff == diffRemoved {
- multiLine = true
- }
- b = append(b, r.Key...)
- if r.Key != "" {
- b = append(b, ": "...)
- }
- b, s[i].Value = r.Value.formatCompactTo(b, d|r.Diff)
- if _, ok := s[i].Value.(textLine); !ok {
- multiLine = true
- }
- if r.Comment != nil {
- multiLine = true
- }
- if i < len(s)-1 {
- b = append(b, ", "...)
- }
- }
- // Force multi-lined output when printing a removed/inserted node that
- // is sufficiently long.
- if (d == diffInserted || d == diffRemoved) && len(b[n0:]) > maxColumnLength {
- multiLine = true
- }
- if !multiLine {
- return b, textLine(b[n0:])
- }
- return b, s
-}
-
-func (s textList) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte {
- alignKeyLens := s.alignLens(
- func(r textRecord) bool {
- _, isLine := r.Value.(textLine)
- return r.Key == "" || !isLine
- },
- func(r textRecord) int { return utf8.RuneCountInString(r.Key) },
- )
- alignValueLens := s.alignLens(
- func(r textRecord) bool {
- _, isLine := r.Value.(textLine)
- return !isLine || r.Value.Equal(textEllipsis) || r.Comment == nil
- },
- func(r textRecord) int { return utf8.RuneCount(r.Value.(textLine)) },
- )
-
- // Format lists of simple lists in a batched form.
- // If the list is sequence of only textLine values,
- // then batch multiple values on a single line.
- var isSimple bool
- for _, r := range s {
- _, isLine := r.Value.(textLine)
- isSimple = r.Diff == 0 && r.Key == "" && isLine && r.Comment == nil
- if !isSimple {
- break
- }
- }
- if isSimple {
- n++
- var batch []byte
- emitBatch := func() {
- if len(batch) > 0 {
- b = n.appendIndent(append(b, '\n'), d)
- b = append(b, bytes.TrimRight(batch, " ")...)
- batch = batch[:0]
- }
- }
- for _, r := range s {
- line := r.Value.(textLine)
- if len(batch)+len(line)+len(", ") > maxColumnLength {
- emitBatch()
- }
- batch = append(batch, line...)
- batch = append(batch, ", "...)
- }
- emitBatch()
- n--
- return n.appendIndent(append(b, '\n'), d)
- }
-
- // Format the list as a multi-lined output.
- n++
- for i, r := range s {
- b = n.appendIndent(append(b, '\n'), d|r.Diff)
- if r.Key != "" {
- b = append(b, r.Key+": "...)
- }
- b = alignKeyLens[i].appendChar(b, ' ')
-
- b = r.Value.formatExpandedTo(b, d|r.Diff, n)
- if !r.ElideComma {
- b = append(b, ',')
- }
- b = alignValueLens[i].appendChar(b, ' ')
-
- if r.Comment != nil {
- b = append(b, " // "+r.Comment.String()...)
- }
- }
- n--
-
- return n.appendIndent(append(b, '\n'), d)
-}
-
-func (s textList) alignLens(
- skipFunc func(textRecord) bool,
- lenFunc func(textRecord) int,
-) []repeatCount {
- var startIdx, endIdx, maxLen int
- lens := make([]repeatCount, len(s))
- for i, r := range s {
- if skipFunc(r) {
- for j := startIdx; j < endIdx && j < len(s); j++ {
- lens[j] = repeatCount(maxLen - lenFunc(s[j]))
- }
- startIdx, endIdx, maxLen = i+1, i+1, 0
- } else {
- if maxLen < lenFunc(r) {
- maxLen = lenFunc(r)
- }
- endIdx = i + 1
- }
- }
- for j := startIdx; j < endIdx && j < len(s); j++ {
- lens[j] = repeatCount(maxLen - lenFunc(s[j]))
- }
- return lens
-}
-
-// textLine is a single-line segment of text and is always a leaf node
-// in the textNode tree.
-type textLine []byte
-
-var (
- textNil = textLine("nil")
- textEllipsis = textLine("...")
-)
-
-func (s textLine) Len() int {
- return len(s)
-}
-func (s1 textLine) Equal(s2 textNode) bool {
- if s2, ok := s2.(textLine); ok {
- return bytes.Equal([]byte(s1), []byte(s2))
- }
- return false
-}
-func (s textLine) String() string {
- return string(s)
-}
-func (s textLine) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) {
- return append(b, s...), s
-}
-func (s textLine) formatExpandedTo(b []byte, _ diffMode, _ indentMode) []byte {
- return append(b, s...)
-}
-
-type diffStats struct {
- Name string
- NumIgnored int
- NumIdentical int
- NumRemoved int
- NumInserted int
- NumModified int
-}
-
-func (s diffStats) IsZero() bool {
- s.Name = ""
- return s == diffStats{}
-}
-
-func (s diffStats) NumDiff() int {
- return s.NumRemoved + s.NumInserted + s.NumModified
-}
-
-func (s diffStats) Append(ds diffStats) diffStats {
- assert(s.Name == ds.Name)
- s.NumIgnored += ds.NumIgnored
- s.NumIdentical += ds.NumIdentical
- s.NumRemoved += ds.NumRemoved
- s.NumInserted += ds.NumInserted
- s.NumModified += ds.NumModified
- return s
-}
-
-// String prints a humanly-readable summary of coalesced records.
-//
-// Example:
-//
-// diffStats{Name: "Field", NumIgnored: 5}.String() => "5 ignored fields"
-func (s diffStats) String() string {
- var ss []string
- var sum int
- labels := [...]string{"ignored", "identical", "removed", "inserted", "modified"}
- counts := [...]int{s.NumIgnored, s.NumIdentical, s.NumRemoved, s.NumInserted, s.NumModified}
- for i, n := range counts {
- if n > 0 {
- ss = append(ss, fmt.Sprintf("%d %v", n, labels[i]))
- }
- sum += n
- }
-
- // Pluralize the name (adjusting for some obscure English grammar rules).
- name := s.Name
- if sum > 1 {
- name += "s"
- if strings.HasSuffix(name, "ys") {
- name = name[:len(name)-2] + "ies" // e.g., "entrys" => "entries"
- }
- }
-
- // Format the list according to English grammar (with Oxford comma).
- switch n := len(ss); n {
- case 0:
- return ""
- case 1, 2:
- return strings.Join(ss, " and ") + " " + name
- default:
- return strings.Join(ss[:n-1], ", ") + ", and " + ss[n-1] + " " + name
- }
-}
-
-type commentString string
-
-func (s commentString) String() string { return string(s) }
diff --git a/vendor/github.com/google/go-cmp/cmp/report_value.go b/vendor/github.com/google/go-cmp/cmp/report_value.go
deleted file mode 100644
index 668d470..0000000
--- a/vendor/github.com/google/go-cmp/cmp/report_value.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright 2019, The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package cmp
-
-import "reflect"
-
-// valueNode represents a single node within a report, which is a
-// structured representation of the value tree, containing information
-// regarding which nodes are equal or not.
-type valueNode struct {
- parent *valueNode
-
- Type reflect.Type
- ValueX reflect.Value
- ValueY reflect.Value
-
- // NumSame is the number of leaf nodes that are equal.
- // All descendants are equal only if NumDiff is 0.
- NumSame int
- // NumDiff is the number of leaf nodes that are not equal.
- NumDiff int
- // NumIgnored is the number of leaf nodes that are ignored.
- NumIgnored int
- // NumCompared is the number of leaf nodes that were compared
- // using an Equal method or Comparer function.
- NumCompared int
- // NumTransformed is the number of non-leaf nodes that were transformed.
- NumTransformed int
- // NumChildren is the number of transitive descendants of this node.
- // This counts from zero; thus, leaf nodes have no descendants.
- NumChildren int
- // MaxDepth is the maximum depth of the tree. This counts from zero;
- // thus, leaf nodes have a depth of zero.
- MaxDepth int
-
- // Records is a list of struct fields, slice elements, or map entries.
- Records []reportRecord // If populated, implies Value is not populated
-
- // Value is the result of a transformation, pointer indirect, of
- // type assertion.
- Value *valueNode // If populated, implies Records is not populated
-
- // TransformerName is the name of the transformer.
- TransformerName string // If non-empty, implies Value is populated
-}
-type reportRecord struct {
- Key reflect.Value // Invalid for slice element
- Value *valueNode
-}
-
-func (parent *valueNode) PushStep(ps PathStep) (child *valueNode) {
- vx, vy := ps.Values()
- child = &valueNode{parent: parent, Type: ps.Type(), ValueX: vx, ValueY: vy}
- switch s := ps.(type) {
- case StructField:
- assert(parent.Value == nil)
- parent.Records = append(parent.Records, reportRecord{Key: reflect.ValueOf(s.Name()), Value: child})
- case SliceIndex:
- assert(parent.Value == nil)
- parent.Records = append(parent.Records, reportRecord{Value: child})
- case MapIndex:
- assert(parent.Value == nil)
- parent.Records = append(parent.Records, reportRecord{Key: s.Key(), Value: child})
- case Indirect:
- assert(parent.Value == nil && parent.Records == nil)
- parent.Value = child
- case TypeAssertion:
- assert(parent.Value == nil && parent.Records == nil)
- parent.Value = child
- case Transform:
- assert(parent.Value == nil && parent.Records == nil)
- parent.Value = child
- parent.TransformerName = s.Name()
- parent.NumTransformed++
- default:
- assert(parent == nil) // Must be the root step
- }
- return child
-}
-
-func (r *valueNode) Report(rs Result) {
- assert(r.MaxDepth == 0) // May only be called on leaf nodes
-
- if rs.ByIgnore() {
- r.NumIgnored++
- } else {
- if rs.Equal() {
- r.NumSame++
- } else {
- r.NumDiff++
- }
- }
- assert(r.NumSame+r.NumDiff+r.NumIgnored == 1)
-
- if rs.ByMethod() {
- r.NumCompared++
- }
- if rs.ByFunc() {
- r.NumCompared++
- }
- assert(r.NumCompared <= 1)
-}
-
-func (child *valueNode) PopStep() (parent *valueNode) {
- if child.parent == nil {
- return nil
- }
- parent = child.parent
- parent.NumSame += child.NumSame
- parent.NumDiff += child.NumDiff
- parent.NumIgnored += child.NumIgnored
- parent.NumCompared += child.NumCompared
- parent.NumTransformed += child.NumTransformed
- parent.NumChildren += child.NumChildren + 1
- if parent.MaxDepth < child.MaxDepth+1 {
- parent.MaxDepth = child.MaxDepth + 1
- }
- return parent
-}
diff --git a/vendor/github.com/google/subcommands/CONTRIBUTING b/vendor/github.com/google/subcommands/CONTRIBUTING
deleted file mode 100644
index 2827b7d..0000000
--- a/vendor/github.com/google/subcommands/CONTRIBUTING
+++ /dev/null
@@ -1,27 +0,0 @@
-Want to contribute? Great! First, read this page (including the small print at the end).
-
-### Before you contribute
-Before we can use your code, you must sign the
-[Google Individual Contributor License Agreement]
-(https://cla.developers.google.com/about/google-individual)
-(CLA), which you can do online. The CLA is necessary mainly because you own the
-copyright to your changes, even after your contribution becomes part of our
-codebase, so we need your permission to use and distribute your code. We also
-need to be sure of various other things—for instance that you'll tell us if you
-know that your code infringes on other people's patents. You don't have to sign
-the CLA until after you've submitted your code for review and a member has
-approved it, but you must do it before we can put your code into our codebase.
-Before you start working on a larger contribution, you should get in touch with
-us first through the issue tracker with your idea so that we can help out and
-possibly guide you. Coordinating up front makes it much easier to avoid
-frustration later on.
-
-### Code reviews
-All submissions, including submissions by project members, require review. We
-use Github pull requests for this purpose.
-
-### The small print
-Contributions made by corporations are covered by a different agreement than
-the one above, the
-[Software Grant and Corporate Contributor License Agreement]
-(https://cla.developers.google.com/about/google-corporate).
diff --git a/vendor/github.com/google/subcommands/LICENSE b/vendor/github.com/google/subcommands/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/vendor/github.com/google/subcommands/LICENSE
+++ /dev/null
@@ -1,202 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/vendor/github.com/google/subcommands/README.md b/vendor/github.com/google/subcommands/README.md
deleted file mode 100644
index c769745..0000000
--- a/vendor/github.com/google/subcommands/README.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# subcommands #
-
-[![GoDoc](https://godoc.org/github.com/google/subcommands?status.svg)](https://godoc.org/github.com/google/subcommands)
-Subcommands is a Go package that implements a simple way for a single command to
-have many subcommands, each of which takes arguments and so forth.
-
-This is not an official Google product.
-
-## Usage ##
-
-Set up a 'print' subcommand:
-
-```go
-import (
- "context"
- "flag"
- "fmt"
- "os"
- "strings"
-
- "github.com/google/subcommands"
-)
-
-type printCmd struct {
- capitalize bool
-}
-
-func (*printCmd) Name() string { return "print" }
-func (*printCmd) Synopsis() string { return "Print args to stdout." }
-func (*printCmd) Usage() string {
- return `print [-capitalize] <some text>:
- Print args to stdout.
-`
-}
-
-func (p *printCmd) SetFlags(f *flag.FlagSet) {
- f.BoolVar(&p.capitalize, "capitalize", false, "capitalize output")
-}
-
-func (p *printCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
- for _, arg := range f.Args() {
- if p.capitalize {
- arg = strings.ToUpper(arg)
- }
- fmt.Printf("%s ", arg)
- }
- fmt.Println()
- return subcommands.ExitSuccess
-}
-```
-
-Register using the default Commander, also use some built in subcommands,
-finally run Execute using ExitStatus as the exit code:
-
-```go
-func main() {
- subcommands.Register(subcommands.HelpCommand(), "")
- subcommands.Register(subcommands.FlagsCommand(), "")
- subcommands.Register(subcommands.CommandsCommand(), "")
- subcommands.Register(&printCmd{}, "")
-
- flag.Parse()
- ctx := context.Background()
- os.Exit(int(subcommands.Execute(ctx)))
-}
-```
-
diff --git a/vendor/github.com/google/subcommands/subcommands.go b/vendor/github.com/google/subcommands/subcommands.go
deleted file mode 100644
index 39268f7..0000000
--- a/vendor/github.com/google/subcommands/subcommands.go
+++ /dev/null
@@ -1,512 +0,0 @@
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package subcommands implements a simple way for a single command to have many
-// subcommands, each of which takes arguments and so forth.
-package subcommands
-
-import (
- "context"
- "flag"
- "fmt"
- "io"
- "os"
- "path"
- "sort"
- "strings"
-)
-
-// A Command represents a single command.
-type Command interface {
- // Name returns the name of the command.
- Name() string
-
- // Synopsis returns a short string (less than one line) describing the command.
- Synopsis() string
-
- // Usage returns a long string explaining the command and giving usage
- // information.
- Usage() string
-
- // SetFlags adds the flags for this command to the specified set.
- SetFlags(*flag.FlagSet)
-
- // Execute executes the command and returns an ExitStatus.
- Execute(ctx context.Context, f *flag.FlagSet, args ...interface{}) ExitStatus
-}
-
-// A Commander represents a set of commands.
-type Commander struct {
- commands []*CommandGroup
- topFlags *flag.FlagSet // top-level flags
- important []string // important top-level flags
- name string // normally path.Base(os.Args[0])
-
- Explain func(io.Writer) // A function to print a top level usage explanation. Can be overridden.
- ExplainGroup func(io.Writer, *CommandGroup) // A function to print a command group's usage explanation. Can be overridden.
- ExplainCommand func(io.Writer, Command) // A function to print a command usage explanation. Can be overridden.
-
- Output io.Writer // Output specifies where the commander should write its output (default: os.Stdout).
- Error io.Writer // Error specifies where the commander should write its error (default: os.Stderr).
-}
-
-// A CommandGroup represents a set of commands about a common topic.
-type CommandGroup struct {
- name string
- commands []Command
-}
-
-// Name returns the group name
-func (g *CommandGroup) Name() string {
- return g.name
-}
-
-// An ExitStatus represents a Posix exit status that a subcommand
-// expects to be returned to the shell.
-type ExitStatus int
-
-const (
- ExitSuccess ExitStatus = iota
- ExitFailure
- ExitUsageError
-)
-
-// NewCommander returns a new commander with the specified top-level
-// flags and command name. The Usage function for the topLevelFlags
-// will be set as well.
-func NewCommander(topLevelFlags *flag.FlagSet, name string) *Commander {
- cdr := &Commander{
- topFlags: topLevelFlags,
- name: name,
- Output: os.Stdout,
- Error: os.Stderr,
- }
-
- cdr.Explain = cdr.explain
- cdr.ExplainGroup = explainGroup
- cdr.ExplainCommand = explain
- topLevelFlags.Usage = func() { cdr.Explain(cdr.Error) }
- return cdr
-}
-
-// Name returns the commander's name
-func (cdr *Commander) Name() string {
- return cdr.name
-}
-
-// Register adds a subcommand to the supported subcommands in the
-// specified group. (Help output is sorted and arranged by group name.)
-// The empty string is an acceptable group name; such subcommands are
-// explained first before named groups.
-func (cdr *Commander) Register(cmd Command, group string) {
- for _, g := range cdr.commands {
- if g.name == group {
- g.commands = append(g.commands, cmd)
- return
- }
- }
- cdr.commands = append(cdr.commands, &CommandGroup{
- name: group,
- commands: []Command{cmd},
- })
-}
-
-// ImportantFlag marks a top-level flag as important, which means it
-// will be printed out as part of the output of an ordinary "help"
-// subcommand. (All flags, important or not, are printed by the
-// "flags" subcommand.)
-func (cdr *Commander) ImportantFlag(name string) {
- cdr.important = append(cdr.important, name)
-}
-
-// VisitGroups visits each command group in lexicographical order, calling
-// fn for each.
-func (cdr *Commander) VisitGroups(fn func(*CommandGroup)) {
- sort.Sort(byGroupName(cdr.commands))
- for _, g := range cdr.commands {
- fn(g)
- }
-}
-
-// VisitCommands visits each command in registered order grouped by
-// command group in lexicographical order, calling fn for each.
-func (cdr *Commander) VisitCommands(fn func(*CommandGroup, Command)) {
- cdr.VisitGroups(func(g *CommandGroup) {
- for _, cmd := range g.commands {
- fn(g, cmd)
- }
- })
-}
-
-// VisitAllImportant visits the important top level flags in lexicographical
-// order, calling fn for each. It visits all flags, even those not set.
-func (cdr *Commander) VisitAllImportant(fn func(*flag.Flag)) {
- sort.Strings(cdr.important)
- for _, name := range cdr.important {
- f := cdr.topFlags.Lookup(name)
- if f == nil {
- panic(fmt.Sprintf("Important flag (%s) is not defined", name))
- }
- fn(f)
- }
-}
-
-// VisitAll visits the top level flags in lexicographical order, calling fn
-// for each. It visits all flags, even those not set.
-func (cdr *Commander) VisitAll(fn func(*flag.Flag)) {
- if cdr.topFlags != nil {
- cdr.topFlags.VisitAll(fn)
- }
-}
-
-// countFlags returns the number of top-level flags defined, even those not set.
-func (cdr *Commander) countTopFlags() int {
- count := 0
- cdr.VisitAll(func(*flag.Flag) {
- count++
- })
- return count
-}
-
-// Execute should be called once the top-level-flags on a Commander
-// have been initialized. It finds the correct subcommand and executes
-// it, and returns an ExitStatus with the result. On a usage error, an
-// appropriate message is printed to os.Stderr, and ExitUsageError is
-// returned. The additional args are provided as-is to the Execute method
-// of the selected Command.
-func (cdr *Commander) Execute(ctx context.Context, args ...interface{}) ExitStatus {
- if cdr.topFlags.NArg() < 1 {
- cdr.topFlags.Usage()
- return ExitUsageError
- }
-
- name := cdr.topFlags.Arg(0)
-
- for _, group := range cdr.commands {
- for _, cmd := range group.commands {
- if name != cmd.Name() {
- continue
- }
- f := flag.NewFlagSet(name, flag.ContinueOnError)
- f.Usage = func() { cdr.ExplainCommand(cdr.Error, cmd) }
- cmd.SetFlags(f)
- if f.Parse(cdr.topFlags.Args()[1:]) != nil {
- return ExitUsageError
- }
- return cmd.Execute(ctx, f, args...)
- }
- }
-
- // Cannot find this command.
- cdr.topFlags.Usage()
- return ExitUsageError
-}
-
-// Sorting of a slice of command groups.
-type byGroupName []*CommandGroup
-
-// TODO Sort by function rather than implement sortable?
-func (p byGroupName) Len() int { return len(p) }
-func (p byGroupName) Less(i, j int) bool { return p[i].name < p[j].name }
-func (p byGroupName) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
-
-// explain prints a brief description of all the subcommands and the
-// important top-level flags.
-func (cdr *Commander) explain(w io.Writer) {
- fmt.Fprintf(w, "Usage: %s <flags> <subcommand> <subcommand args>\n\n", cdr.name)
- sort.Sort(byGroupName(cdr.commands))
- for _, group := range cdr.commands {
- cdr.ExplainGroup(w, group)
- }
- if cdr.topFlags == nil {
- fmt.Fprintln(w, "\nNo top level flags.")
- return
- }
-
- sort.Strings(cdr.important)
- if len(cdr.important) == 0 {
- if cdr.countTopFlags() > 0 {
- fmt.Fprintf(w, "\nUse \"%s flags\" for a list of top-level flags\n", cdr.name)
- }
- return
- }
-
- fmt.Fprintf(w, "\nTop-level flags (use \"%s flags\" for a full list):\n", cdr.name)
- for _, name := range cdr.important {
- f := cdr.topFlags.Lookup(name)
- if f == nil {
- panic(fmt.Sprintf("Important flag (%s) is not defined", name))
- }
- fmt.Fprintf(w, " -%s=%s: %s\n", f.Name, f.DefValue, f.Usage)
- }
-}
-
-// Sorting of the commands within a group.
-func (g CommandGroup) Len() int { return len(g.commands) }
-func (g CommandGroup) Less(i, j int) bool { return g.commands[i].Name() < g.commands[j].Name() }
-func (g CommandGroup) Swap(i, j int) { g.commands[i], g.commands[j] = g.commands[j], g.commands[i] }
-
-// explainGroup explains all the subcommands for a particular group.
-func explainGroup(w io.Writer, group *CommandGroup) {
- if len(group.commands) == 0 {
- return
- }
- if group.name == "" {
- fmt.Fprintf(w, "Subcommands:\n")
- } else {
- fmt.Fprintf(w, "Subcommands for %s:\n", group.name)
- }
- sort.Sort(group)
-
- aliases := make(map[string][]string)
- for _, cmd := range group.commands {
- if alias, ok := cmd.(*aliaser); ok {
- root := dealias(alias).Name()
-
- if _, ok := aliases[root]; !ok {
- aliases[root] = []string{}
- }
- aliases[root] = append(aliases[root], alias.Name())
- }
- }
-
- for _, cmd := range group.commands {
- if _, ok := cmd.(*aliaser); ok {
- continue
- }
-
- name := cmd.Name()
- names := []string{name}
-
- if a, ok := aliases[name]; ok {
- names = append(names, a...)
- }
-
- fmt.Fprintf(w, "\t%-15s %s\n", strings.Join(names, ", "), cmd.Synopsis())
- }
- fmt.Fprintln(w)
-}
-
-// explainCmd prints a brief description of a single command.
-func explain(w io.Writer, cmd Command) {
- fmt.Fprintf(w, "%s", cmd.Usage())
- subflags := flag.NewFlagSet(cmd.Name(), flag.PanicOnError)
- subflags.SetOutput(w)
- cmd.SetFlags(subflags)
- subflags.PrintDefaults()
-}
-
-// A helper is a Command implementing a "help" command for
-// a given Commander.
-type helper Commander
-
-func (h *helper) Name() string { return "help" }
-func (h *helper) Synopsis() string { return "describe subcommands and their syntax" }
-func (h *helper) SetFlags(*flag.FlagSet) {}
-func (h *helper) Usage() string {
- return `help [<subcommand>]:
- With an argument, prints detailed information on the use of
- the specified subcommand. With no argument, print a list of
- all commands and a brief description of each.
-`
-}
-func (h *helper) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) ExitStatus {
- switch f.NArg() {
- case 0:
- (*Commander)(h).Explain(h.Output)
- return ExitSuccess
-
- case 1:
- for _, group := range h.commands {
- for _, cmd := range group.commands {
- if f.Arg(0) != cmd.Name() {
- continue
- }
- (*Commander)(h).ExplainCommand(h.Output, cmd)
- return ExitSuccess
- }
- }
- fmt.Fprintf(h.Error, "Subcommand %s not understood\n", f.Arg(0))
- }
-
- f.Usage()
- return ExitUsageError
-}
-
-// HelpCommand returns a Command which implements a "help" subcommand.
-func (cdr *Commander) HelpCommand() Command {
- return (*helper)(cdr)
-}
-
-// A flagger is a Command implementing a "flags" command for a given Commander.
-type flagger Commander
-
-func (flg *flagger) Name() string { return "flags" }
-func (flg *flagger) Synopsis() string { return "describe all known top-level flags" }
-func (flg *flagger) SetFlags(*flag.FlagSet) {}
-func (flg *flagger) Usage() string {
- return `flags [<subcommand>]:
- With an argument, print all flags of <subcommand>. Else,
- print a description of all known top-level flags. (The basic
- help information only discusses the most generally important
- top-level flags.)
-`
-}
-func (flg *flagger) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) ExitStatus {
- if f.NArg() > 1 {
- f.Usage()
- return ExitUsageError
- }
-
- if f.NArg() == 0 {
- if flg.topFlags == nil {
- fmt.Fprintln(flg.Output, "No top-level flags are defined.")
- } else {
- flg.topFlags.PrintDefaults()
- }
- return ExitSuccess
- }
-
- for _, group := range flg.commands {
- for _, cmd := range group.commands {
- if f.Arg(0) != cmd.Name() {
- continue
- }
- subflags := flag.NewFlagSet(cmd.Name(), flag.PanicOnError)
- subflags.SetOutput(flg.Output)
- cmd.SetFlags(subflags)
- subflags.PrintDefaults()
- return ExitSuccess
- }
- }
- fmt.Fprintf(flg.Error, "Subcommand %s not understood\n", f.Arg(0))
- return ExitFailure
-}
-
-// FlagsCommand returns a Command which implements a "flags" subcommand.
-func (cdr *Commander) FlagsCommand() Command {
- return (*flagger)(cdr)
-}
-
-// A lister is a Command implementing a "commands" command for a given Commander.
-type lister Commander
-
-func (l *lister) Name() string { return "commands" }
-func (l *lister) Synopsis() string { return "list all command names" }
-func (l *lister) SetFlags(*flag.FlagSet) {}
-func (l *lister) Usage() string {
- return `commands:
- Print a list of all commands.
-`
-}
-func (l *lister) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) ExitStatus {
- if f.NArg() != 0 {
- f.Usage()
- return ExitUsageError
- }
-
- for _, group := range l.commands {
- for _, cmd := range group.commands {
- fmt.Fprintf(l.Output, "%s\n", cmd.Name())
- }
- }
- return ExitSuccess
-}
-
-// CommandsCommand returns Command which implements a "commands" subcommand.
-func (cdr *Commander) CommandsCommand() Command {
- return (*lister)(cdr)
-}
-
-// An aliaser is a Command wrapping another Command but returning a
-// different name as its alias.
-type aliaser struct {
- alias string
- Command
-}
-
-func (a *aliaser) Name() string { return a.alias }
-
-// Alias returns a Command alias which implements a "commands" subcommand.
-func Alias(alias string, cmd Command) Command {
- return &aliaser{alias, cmd}
-}
-
-// dealias recursivly dealiases a command until a non-aliased command
-// is reached.
-func dealias(cmd Command) Command {
- if alias, ok := cmd.(*aliaser); ok {
- return dealias(alias.Command)
- }
-
- return cmd
-}
-
-// DefaultCommander is the default commander using flag.CommandLine for flags
-// and os.Args[0] for the command name.
-var DefaultCommander *Commander
-
-func init() {
- DefaultCommander = NewCommander(flag.CommandLine, path.Base(os.Args[0]))
-}
-
-// Register adds a subcommand to the supported subcommands in the
-// specified group. (Help output is sorted and arranged by group
-// name.) The empty string is an acceptable group name; such
-// subcommands are explained first before named groups. It is a
-// wrapper around DefaultCommander.Register.
-func Register(cmd Command, group string) {
- DefaultCommander.Register(cmd, group)
-}
-
-// ImportantFlag marks a top-level flag as important, which means it
-// will be printed out as part of the output of an ordinary "help"
-// subcommand. (All flags, important or not, are printed by the
-// "flags" subcommand.) It is a wrapper around
-// DefaultCommander.ImportantFlag.
-func ImportantFlag(name string) {
- DefaultCommander.ImportantFlag(name)
-}
-
-// Execute should be called once the default flags have been
-// initialized by flag.Parse. It finds the correct subcommand and
-// executes it, and returns an ExitStatus with the result. On a usage
-// error, an appropriate message is printed to os.Stderr, and
-// ExitUsageError is returned. The additional args are provided as-is
-// to the Execute method of the selected Command. It is a wrapper
-// around DefaultCommander.Execute.
-func Execute(ctx context.Context, args ...interface{}) ExitStatus {
- return DefaultCommander.Execute(ctx, args...)
-}
-
-// HelpCommand returns a Command which implements "help" for the
-// DefaultCommander. Use Register(HelpCommand(), <group>) for it to be
-// recognized.
-func HelpCommand() Command {
- return DefaultCommander.HelpCommand()
-}
-
-// FlagsCommand returns a Command which implements "flags" for the
-// DefaultCommander. Use Register(FlagsCommand(), <group>) for it to be
-// recognized.
-func FlagsCommand() Command {
- return DefaultCommander.FlagsCommand()
-}
-
-// CommandsCommand returns Command which implements a "commands" subcommand.
-func CommandsCommand() Command {
- return DefaultCommander.CommandsCommand()
-}
diff --git a/vendor/github.com/kelseyhightower/envconfig/.travis.yml b/vendor/github.com/kelseyhightower/envconfig/.travis.yml
deleted file mode 100644
index 04b97ae..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/.travis.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-language: go
-
-go:
- - 1.4.x
- - 1.5.x
- - 1.6.x
- - 1.7.x
- - 1.8.x
- - 1.9.x
- - 1.10.x
- - 1.11.x
- - 1.12.x
- - tip
diff --git a/vendor/github.com/kelseyhightower/envconfig/LICENSE b/vendor/github.com/kelseyhightower/envconfig/LICENSE
deleted file mode 100644
index 4bfa7a8..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2013 Kelsey Hightower
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/vendor/github.com/kelseyhightower/envconfig/MAINTAINERS b/vendor/github.com/kelseyhightower/envconfig/MAINTAINERS
deleted file mode 100644
index 6527a9f..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/MAINTAINERS
+++ /dev/null
@@ -1,2 +0,0 @@
-Kelsey Hightower kelsey.hightower@gmail.com github.com/kelseyhightower
-Travis Parker travis.parker@gmail.com github.com/teepark
diff --git a/vendor/github.com/kelseyhightower/envconfig/README.md b/vendor/github.com/kelseyhightower/envconfig/README.md
deleted file mode 100644
index 33408d6..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/README.md
+++ /dev/null
@@ -1,192 +0,0 @@
-# envconfig
-
-[![Build Status](https://travis-ci.org/kelseyhightower/envconfig.svg)](https://travis-ci.org/kelseyhightower/envconfig)
-
-```Go
-import "github.com/kelseyhightower/envconfig"
-```
-
-## Documentation
-
-See [godoc](http://godoc.org/github.com/kelseyhightower/envconfig)
-
-## Usage
-
-Set some environment variables:
-
-```Bash
-export MYAPP_DEBUG=false
-export MYAPP_PORT=8080
-export MYAPP_USER=Kelsey
-export MYAPP_RATE="0.5"
-export MYAPP_TIMEOUT="3m"
-export MYAPP_USERS="rob,ken,robert"
-export MYAPP_COLORCODES="red:1,green:2,blue:3"
-```
-
-Write some code:
-
-```Go
-package main
-
-import (
- "fmt"
- "log"
- "time"
-
- "github.com/kelseyhightower/envconfig"
-)
-
-type Specification struct {
- Debug bool
- Port int
- User string
- Users []string
- Rate float32
- Timeout time.Duration
- ColorCodes map[string]int
-}
-
-func main() {
- var s Specification
- err := envconfig.Process("myapp", &s)
- if err != nil {
- log.Fatal(err.Error())
- }
- format := "Debug: %v\nPort: %d\nUser: %s\nRate: %f\nTimeout: %s\n"
- _, err = fmt.Printf(format, s.Debug, s.Port, s.User, s.Rate, s.Timeout)
- if err != nil {
- log.Fatal(err.Error())
- }
-
- fmt.Println("Users:")
- for _, u := range s.Users {
- fmt.Printf(" %s\n", u)
- }
-
- fmt.Println("Color codes:")
- for k, v := range s.ColorCodes {
- fmt.Printf(" %s: %d\n", k, v)
- }
-}
-```
-
-Results:
-
-```Bash
-Debug: false
-Port: 8080
-User: Kelsey
-Rate: 0.500000
-Timeout: 3m0s
-Users:
- rob
- ken
- robert
-Color codes:
- red: 1
- green: 2
- blue: 3
-```
-
-## Struct Tag Support
-
-Envconfig supports the use of struct tags to specify alternate, default, and required
-environment variables.
-
-For example, consider the following struct:
-
-```Go
-type Specification struct {
- ManualOverride1 string `envconfig:"manual_override_1"`
- DefaultVar string `default:"foobar"`
- RequiredVar string `required:"true"`
- IgnoredVar string `ignored:"true"`
- AutoSplitVar string `split_words:"true"`
- RequiredAndAutoSplitVar string `required:"true" split_words:"true"`
-}
-```
-
-Envconfig has automatic support for CamelCased struct elements when the
-`split_words:"true"` tag is supplied. Without this tag, `AutoSplitVar` above
-would look for an environment variable called `MYAPP_AUTOSPLITVAR`. With the
-setting applied it will look for `MYAPP_AUTO_SPLIT_VAR`. Note that numbers
-will get globbed into the previous word. If the setting does not do the
-right thing, you may use a manual override.
-
-Envconfig will process value for `ManualOverride1` by populating it with the
-value for `MYAPP_MANUAL_OVERRIDE_1`. Without this struct tag, it would have
-instead looked up `MYAPP_MANUALOVERRIDE1`. With the `split_words:"true"` tag
-it would have looked up `MYAPP_MANUAL_OVERRIDE1`.
-
-```Bash
-export MYAPP_MANUAL_OVERRIDE_1="this will be the value"
-
-# export MYAPP_MANUALOVERRIDE1="and this will not"
-```
-
-If envconfig can't find an environment variable value for `MYAPP_DEFAULTVAR`,
-it will populate it with "foobar" as a default value.
-
-If envconfig can't find an environment variable value for `MYAPP_REQUIREDVAR`,
-it will return an error when asked to process the struct. If
-`MYAPP_REQUIREDVAR` is present but empty, envconfig will not return an error.
-
-If envconfig can't find an environment variable in the form `PREFIX_MYVAR`, and there
-is a struct tag defined, it will try to populate your variable with an environment
-variable that directly matches the envconfig tag in your struct definition:
-
-```shell
-export SERVICE_HOST=127.0.0.1
-export MYAPP_DEBUG=true
-```
-```Go
-type Specification struct {
- ServiceHost string `envconfig:"SERVICE_HOST"`
- Debug bool
-}
-```
-
-Envconfig won't process a field with the "ignored" tag set to "true", even if a corresponding
-environment variable is set.
-
-## Supported Struct Field Types
-
-envconfig supports these struct field types:
-
- * string
- * int8, int16, int32, int64
- * bool
- * float32, float64
- * slices of any supported type
- * maps (keys and values of any supported type)
- * [encoding.TextUnmarshaler](https://golang.org/pkg/encoding/#TextUnmarshaler)
- * [encoding.BinaryUnmarshaler](https://golang.org/pkg/encoding/#BinaryUnmarshaler)
- * [time.Duration](https://golang.org/pkg/time/#Duration)
-
-Embedded structs using these fields are also supported.
-
-## Custom Decoders
-
-Any field whose type (or pointer-to-type) implements `envconfig.Decoder` can
-control its own deserialization:
-
-```Bash
-export DNS_SERVER=8.8.8.8
-```
-
-```Go
-type IPDecoder net.IP
-
-func (ipd *IPDecoder) Decode(value string) error {
- *ipd = IPDecoder(net.ParseIP(value))
- return nil
-}
-
-type DNSConfig struct {
- Address IPDecoder `envconfig:"DNS_SERVER"`
-}
-```
-
-Also, envconfig will use a `Set(string) error` method like from the
-[flag.Value](https://godoc.org/flag#Value) interface if implemented.
diff --git a/vendor/github.com/kelseyhightower/envconfig/doc.go b/vendor/github.com/kelseyhightower/envconfig/doc.go
deleted file mode 100644
index f28561c..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/doc.go
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2013 Kelsey Hightower. All rights reserved.
-// Use of this source code is governed by the MIT License that can be found in
-// the LICENSE file.
-
-// Package envconfig implements decoding of environment variables based on a user
-// defined specification. A typical use is using environment variables for
-// configuration settings.
-package envconfig
diff --git a/vendor/github.com/kelseyhightower/envconfig/env_os.go b/vendor/github.com/kelseyhightower/envconfig/env_os.go
deleted file mode 100644
index eba07a6..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/env_os.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build appengine go1.5
-
-package envconfig
-
-import "os"
-
-var lookupEnv = os.LookupEnv
diff --git a/vendor/github.com/kelseyhightower/envconfig/env_syscall.go b/vendor/github.com/kelseyhightower/envconfig/env_syscall.go
deleted file mode 100644
index 4254540..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/env_syscall.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build !appengine,!go1.5
-
-package envconfig
-
-import "syscall"
-
-var lookupEnv = syscall.Getenv
diff --git a/vendor/github.com/kelseyhightower/envconfig/envconfig.go b/vendor/github.com/kelseyhightower/envconfig/envconfig.go
deleted file mode 100644
index 3f16108..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/envconfig.go
+++ /dev/null
@@ -1,382 +0,0 @@
-// Copyright (c) 2013 Kelsey Hightower. All rights reserved.
-// Use of this source code is governed by the MIT License that can be found in
-// the LICENSE file.
-
-package envconfig
-
-import (
- "encoding"
- "errors"
- "fmt"
- "os"
- "reflect"
- "regexp"
- "strconv"
- "strings"
- "time"
-)
-
-// ErrInvalidSpecification indicates that a specification is of the wrong type.
-var ErrInvalidSpecification = errors.New("specification must be a struct pointer")
-
-var gatherRegexp = regexp.MustCompile("([^A-Z]+|[A-Z]+[^A-Z]+|[A-Z]+)")
-var acronymRegexp = regexp.MustCompile("([A-Z]+)([A-Z][^A-Z]+)")
-
-// A ParseError occurs when an environment variable cannot be converted to
-// the type required by a struct field during assignment.
-type ParseError struct {
- KeyName string
- FieldName string
- TypeName string
- Value string
- Err error
-}
-
-// Decoder has the same semantics as Setter, but takes higher precedence.
-// It is provided for historical compatibility.
-type Decoder interface {
- Decode(value string) error
-}
-
-// Setter is implemented by types can self-deserialize values.
-// Any type that implements flag.Value also implements Setter.
-type Setter interface {
- Set(value string) error
-}
-
-func (e *ParseError) Error() string {
- return fmt.Sprintf("envconfig.Process: assigning %[1]s to %[2]s: converting '%[3]s' to type %[4]s. details: %[5]s", e.KeyName, e.FieldName, e.Value, e.TypeName, e.Err)
-}
-
-// varInfo maintains information about the configuration variable
-type varInfo struct {
- Name string
- Alt string
- Key string
- Field reflect.Value
- Tags reflect.StructTag
-}
-
-// GatherInfo gathers information about the specified struct
-func gatherInfo(prefix string, spec interface{}) ([]varInfo, error) {
- s := reflect.ValueOf(spec)
-
- if s.Kind() != reflect.Ptr {
- return nil, ErrInvalidSpecification
- }
- s = s.Elem()
- if s.Kind() != reflect.Struct {
- return nil, ErrInvalidSpecification
- }
- typeOfSpec := s.Type()
-
- // over allocate an info array, we will extend if needed later
- infos := make([]varInfo, 0, s.NumField())
- for i := 0; i < s.NumField(); i++ {
- f := s.Field(i)
- ftype := typeOfSpec.Field(i)
- if !f.CanSet() || isTrue(ftype.Tag.Get("ignored")) {
- continue
- }
-
- for f.Kind() == reflect.Ptr {
- if f.IsNil() {
- if f.Type().Elem().Kind() != reflect.Struct {
- // nil pointer to a non-struct: leave it alone
- break
- }
- // nil pointer to struct: create a zero instance
- f.Set(reflect.New(f.Type().Elem()))
- }
- f = f.Elem()
- }
-
- // Capture information about the config variable
- info := varInfo{
- Name: ftype.Name,
- Field: f,
- Tags: ftype.Tag,
- Alt: strings.ToUpper(ftype.Tag.Get("envconfig")),
- }
-
- // Default to the field name as the env var name (will be upcased)
- info.Key = info.Name
-
- // Best effort to un-pick camel casing as separate words
- if isTrue(ftype.Tag.Get("split_words")) {
- words := gatherRegexp.FindAllStringSubmatch(ftype.Name, -1)
- if len(words) > 0 {
- var name []string
- for _, words := range words {
- if m := acronymRegexp.FindStringSubmatch(words[0]); len(m) == 3 {
- name = append(name, m[1], m[2])
- } else {
- name = append(name, words[0])
- }
- }
-
- info.Key = strings.Join(name, "_")
- }
- }
- if info.Alt != "" {
- info.Key = info.Alt
- }
- if prefix != "" {
- info.Key = fmt.Sprintf("%s_%s", prefix, info.Key)
- }
- info.Key = strings.ToUpper(info.Key)
- infos = append(infos, info)
-
- if f.Kind() == reflect.Struct {
- // honor Decode if present
- if decoderFrom(f) == nil && setterFrom(f) == nil && textUnmarshaler(f) == nil && binaryUnmarshaler(f) == nil {
- innerPrefix := prefix
- if !ftype.Anonymous {
- innerPrefix = info.Key
- }
-
- embeddedPtr := f.Addr().Interface()
- embeddedInfos, err := gatherInfo(innerPrefix, embeddedPtr)
- if err != nil {
- return nil, err
- }
- infos = append(infos[:len(infos)-1], embeddedInfos...)
-
- continue
- }
- }
- }
- return infos, nil
-}
-
-// CheckDisallowed checks that no environment variables with the prefix are set
-// that we don't know how or want to parse. This is likely only meaningful with
-// a non-empty prefix.
-func CheckDisallowed(prefix string, spec interface{}) error {
- infos, err := gatherInfo(prefix, spec)
- if err != nil {
- return err
- }
-
- vars := make(map[string]struct{})
- for _, info := range infos {
- vars[info.Key] = struct{}{}
- }
-
- if prefix != "" {
- prefix = strings.ToUpper(prefix) + "_"
- }
-
- for _, env := range os.Environ() {
- if !strings.HasPrefix(env, prefix) {
- continue
- }
- v := strings.SplitN(env, "=", 2)[0]
- if _, found := vars[v]; !found {
- return fmt.Errorf("unknown environment variable %s", v)
- }
- }
-
- return nil
-}
-
-// Process populates the specified struct based on environment variables
-func Process(prefix string, spec interface{}) error {
- infos, err := gatherInfo(prefix, spec)
-
- for _, info := range infos {
-
- // `os.Getenv` cannot differentiate between an explicitly set empty value
- // and an unset value. `os.LookupEnv` is preferred to `syscall.Getenv`,
- // but it is only available in go1.5 or newer. We're using Go build tags
- // here to use os.LookupEnv for >=go1.5
- value, ok := lookupEnv(info.Key)
- if !ok && info.Alt != "" {
- value, ok = lookupEnv(info.Alt)
- }
-
- def := info.Tags.Get("default")
- if def != "" && !ok {
- value = def
- }
-
- req := info.Tags.Get("required")
- if !ok && def == "" {
- if isTrue(req) {
- key := info.Key
- if info.Alt != "" {
- key = info.Alt
- }
- return fmt.Errorf("required key %s missing value", key)
- }
- continue
- }
-
- err = processField(value, info.Field)
- if err != nil {
- return &ParseError{
- KeyName: info.Key,
- FieldName: info.Name,
- TypeName: info.Field.Type().String(),
- Value: value,
- Err: err,
- }
- }
- }
-
- return err
-}
-
-// MustProcess is the same as Process but panics if an error occurs
-func MustProcess(prefix string, spec interface{}) {
- if err := Process(prefix, spec); err != nil {
- panic(err)
- }
-}
-
-func processField(value string, field reflect.Value) error {
- typ := field.Type()
-
- decoder := decoderFrom(field)
- if decoder != nil {
- return decoder.Decode(value)
- }
- // look for Set method if Decode not defined
- setter := setterFrom(field)
- if setter != nil {
- return setter.Set(value)
- }
-
- if t := textUnmarshaler(field); t != nil {
- return t.UnmarshalText([]byte(value))
- }
-
- if b := binaryUnmarshaler(field); b != nil {
- return b.UnmarshalBinary([]byte(value))
- }
-
- if typ.Kind() == reflect.Ptr {
- typ = typ.Elem()
- if field.IsNil() {
- field.Set(reflect.New(typ))
- }
- field = field.Elem()
- }
-
- switch typ.Kind() {
- case reflect.String:
- field.SetString(value)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- var (
- val int64
- err error
- )
- if field.Kind() == reflect.Int64 && typ.PkgPath() == "time" && typ.Name() == "Duration" {
- var d time.Duration
- d, err = time.ParseDuration(value)
- val = int64(d)
- } else {
- val, err = strconv.ParseInt(value, 0, typ.Bits())
- }
- if err != nil {
- return err
- }
-
- field.SetInt(val)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- val, err := strconv.ParseUint(value, 0, typ.Bits())
- if err != nil {
- return err
- }
- field.SetUint(val)
- case reflect.Bool:
- val, err := strconv.ParseBool(value)
- if err != nil {
- return err
- }
- field.SetBool(val)
- case reflect.Float32, reflect.Float64:
- val, err := strconv.ParseFloat(value, typ.Bits())
- if err != nil {
- return err
- }
- field.SetFloat(val)
- case reflect.Slice:
- sl := reflect.MakeSlice(typ, 0, 0)
- if typ.Elem().Kind() == reflect.Uint8 {
- sl = reflect.ValueOf([]byte(value))
- } else if len(strings.TrimSpace(value)) != 0 {
- vals := strings.Split(value, ",")
- sl = reflect.MakeSlice(typ, len(vals), len(vals))
- for i, val := range vals {
- err := processField(val, sl.Index(i))
- if err != nil {
- return err
- }
- }
- }
- field.Set(sl)
- case reflect.Map:
- mp := reflect.MakeMap(typ)
- if len(strings.TrimSpace(value)) != 0 {
- pairs := strings.Split(value, ",")
- for _, pair := range pairs {
- kvpair := strings.Split(pair, ":")
- if len(kvpair) != 2 {
- return fmt.Errorf("invalid map item: %q", pair)
- }
- k := reflect.New(typ.Key()).Elem()
- err := processField(kvpair[0], k)
- if err != nil {
- return err
- }
- v := reflect.New(typ.Elem()).Elem()
- err = processField(kvpair[1], v)
- if err != nil {
- return err
- }
- mp.SetMapIndex(k, v)
- }
- }
- field.Set(mp)
- }
-
- return nil
-}
-
-func interfaceFrom(field reflect.Value, fn func(interface{}, *bool)) {
- // it may be impossible for a struct field to fail this check
- if !field.CanInterface() {
- return
- }
- var ok bool
- fn(field.Interface(), &ok)
- if !ok && field.CanAddr() {
- fn(field.Addr().Interface(), &ok)
- }
-}
-
-func decoderFrom(field reflect.Value) (d Decoder) {
- interfaceFrom(field, func(v interface{}, ok *bool) { d, *ok = v.(Decoder) })
- return d
-}
-
-func setterFrom(field reflect.Value) (s Setter) {
- interfaceFrom(field, func(v interface{}, ok *bool) { s, *ok = v.(Setter) })
- return s
-}
-
-func textUnmarshaler(field reflect.Value) (t encoding.TextUnmarshaler) {
- interfaceFrom(field, func(v interface{}, ok *bool) { t, *ok = v.(encoding.TextUnmarshaler) })
- return t
-}
-
-func binaryUnmarshaler(field reflect.Value) (b encoding.BinaryUnmarshaler) {
- interfaceFrom(field, func(v interface{}, ok *bool) { b, *ok = v.(encoding.BinaryUnmarshaler) })
- return b
-}
-
-func isTrue(s string) bool {
- b, _ := strconv.ParseBool(s)
- return b
-}
diff --git a/vendor/github.com/kelseyhightower/envconfig/usage.go b/vendor/github.com/kelseyhightower/envconfig/usage.go
deleted file mode 100644
index 1e6d0a8..0000000
--- a/vendor/github.com/kelseyhightower/envconfig/usage.go
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright (c) 2016 Kelsey Hightower and others. All rights reserved.
-// Use of this source code is governed by the MIT License that can be found in
-// the LICENSE file.
-
-package envconfig
-
-import (
- "encoding"
- "fmt"
- "io"
- "os"
- "reflect"
- "strconv"
- "strings"
- "text/tabwriter"
- "text/template"
-)
-
-const (
- // DefaultListFormat constant to use to display usage in a list format
- DefaultListFormat = `This application is configured via the environment. The following environment
-variables can be used:
-{{range .}}
-{{usage_key .}}
- [description] {{usage_description .}}
- [type] {{usage_type .}}
- [default] {{usage_default .}}
- [required] {{usage_required .}}{{end}}
-`
- // DefaultTableFormat constant to use to display usage in a tabular format
- DefaultTableFormat = `This application is configured via the environment. The following environment
-variables can be used:
-
-KEY TYPE DEFAULT REQUIRED DESCRIPTION
-{{range .}}{{usage_key .}} {{usage_type .}} {{usage_default .}} {{usage_required .}} {{usage_description .}}
-{{end}}`
-)
-
-var (
- decoderType = reflect.TypeOf((*Decoder)(nil)).Elem()
- setterType = reflect.TypeOf((*Setter)(nil)).Elem()
- textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
- binaryUnmarshalerType = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
-)
-
-func implementsInterface(t reflect.Type) bool {
- return t.Implements(decoderType) ||
- reflect.PtrTo(t).Implements(decoderType) ||
- t.Implements(setterType) ||
- reflect.PtrTo(t).Implements(setterType) ||
- t.Implements(textUnmarshalerType) ||
- reflect.PtrTo(t).Implements(textUnmarshalerType) ||
- t.Implements(binaryUnmarshalerType) ||
- reflect.PtrTo(t).Implements(binaryUnmarshalerType)
-}
-
-// toTypeDescription converts Go types into a human readable description
-func toTypeDescription(t reflect.Type) string {
- switch t.Kind() {
- case reflect.Array, reflect.Slice:
- if t.Elem().Kind() == reflect.Uint8 {
- return "String"
- }
- return fmt.Sprintf("Comma-separated list of %s", toTypeDescription(t.Elem()))
- case reflect.Map:
- return fmt.Sprintf(
- "Comma-separated list of %s:%s pairs",
- toTypeDescription(t.Key()),
- toTypeDescription(t.Elem()),
- )
- case reflect.Ptr:
- return toTypeDescription(t.Elem())
- case reflect.Struct:
- if implementsInterface(t) && t.Name() != "" {
- return t.Name()
- }
- return ""
- case reflect.String:
- name := t.Name()
- if name != "" && name != "string" {
- return name
- }
- return "String"
- case reflect.Bool:
- name := t.Name()
- if name != "" && name != "bool" {
- return name
- }
- return "True or False"
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- name := t.Name()
- if name != "" && !strings.HasPrefix(name, "int") {
- return name
- }
- return "Integer"
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- name := t.Name()
- if name != "" && !strings.HasPrefix(name, "uint") {
- return name
- }
- return "Unsigned Integer"
- case reflect.Float32, reflect.Float64:
- name := t.Name()
- if name != "" && !strings.HasPrefix(name, "float") {
- return name
- }
- return "Float"
- }
- return fmt.Sprintf("%+v", t)
-}
-
-// Usage writes usage information to stdout using the default header and table format
-func Usage(prefix string, spec interface{}) error {
- // The default is to output the usage information as a table
- // Create tabwriter instance to support table output
- tabs := tabwriter.NewWriter(os.Stdout, 1, 0, 4, ' ', 0)
-
- err := Usagef(prefix, spec, tabs, DefaultTableFormat)
- tabs.Flush()
- return err
-}
-
-// Usagef writes usage information to the specified io.Writer using the specifed template specification
-func Usagef(prefix string, spec interface{}, out io.Writer, format string) error {
-
- // Specify the default usage template functions
- functions := template.FuncMap{
- "usage_key": func(v varInfo) string { return v.Key },
- "usage_description": func(v varInfo) string { return v.Tags.Get("desc") },
- "usage_type": func(v varInfo) string { return toTypeDescription(v.Field.Type()) },
- "usage_default": func(v varInfo) string { return v.Tags.Get("default") },
- "usage_required": func(v varInfo) (string, error) {
- req := v.Tags.Get("required")
- if req != "" {
- reqB, err := strconv.ParseBool(req)
- if err != nil {
- return "", err
- }
- if reqB {
- req = "true"
- }
- }
- return req, nil
- },
- }
-
- tmpl, err := template.New("envconfig").Funcs(functions).Parse(format)
- if err != nil {
- return err
- }
-
- return Usaget(prefix, spec, out, tmpl)
-}
-
-// Usaget writes usage information to the specified io.Writer using the specified template
-func Usaget(prefix string, spec interface{}, out io.Writer, tmpl *template.Template) error {
- // gather first
- infos, err := gatherInfo(prefix, spec)
- if err != nil {
- return err
- }
-
- return tmpl.Execute(out, infos)
-}
diff --git a/vendor/github.com/lib/pq/.gitignore b/vendor/github.com/lib/pq/.gitignore
deleted file mode 100644
index 3243952..0000000
--- a/vendor/github.com/lib/pq/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-.db
-*.test
-*~
-*.swp
-.idea
-.vscode \ No newline at end of file
diff --git a/vendor/github.com/lib/pq/LICENSE.md b/vendor/github.com/lib/pq/LICENSE.md
deleted file mode 100644
index 5773904..0000000
--- a/vendor/github.com/lib/pq/LICENSE.md
+++ /dev/null
@@ -1,8 +0,0 @@
-Copyright (c) 2011-2013, 'pq' Contributors
-Portions Copyright (C) 2011 Blake Mizerany
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/github.com/lib/pq/README.md b/vendor/github.com/lib/pq/README.md
deleted file mode 100644
index 126ee5d..0000000
--- a/vendor/github.com/lib/pq/README.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# pq - A pure Go postgres driver for Go's database/sql package
-
-[![GoDoc](https://godoc.org/github.com/lib/pq?status.svg)](https://pkg.go.dev/github.com/lib/pq?tab=doc)
-
-## Install
-
- go get github.com/lib/pq
-
-## Features
-
-* SSL
-* Handles bad connections for `database/sql`
-* Scan `time.Time` correctly (i.e. `timestamp[tz]`, `time[tz]`, `date`)
-* Scan binary blobs correctly (i.e. `bytea`)
-* Package for `hstore` support
-* COPY FROM support
-* pq.ParseURL for converting urls to connection strings for sql.Open.
-* Many libpq compatible environment variables
-* Unix socket support
-* Notifications: `LISTEN`/`NOTIFY`
-* pgpass support
-* GSS (Kerberos) auth
-
-## Tests
-
-`go test` is used for testing. See [TESTS.md](TESTS.md) for more details.
-
-## Status
-
-This package is currently in maintenance mode, which means:
-1. It generally does not accept new features.
-2. It does accept bug fixes and version compatability changes provided by the community.
-3. Maintainers usually do not resolve reported issues.
-4. Community members are encouraged to help each other with reported issues.
-
-For users that require new features or reliable resolution of reported bugs, we recommend using [pgx](https://github.com/jackc/pgx) which is under active development.
diff --git a/vendor/github.com/lib/pq/TESTS.md b/vendor/github.com/lib/pq/TESTS.md
deleted file mode 100644
index f050211..0000000
--- a/vendor/github.com/lib/pq/TESTS.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# Tests
-
-## Running Tests
-
-`go test` is used for testing. A running PostgreSQL
-server is required, with the ability to log in. The
-database to connect to test with is "pqgotest," on
-"localhost" but these can be overridden using [environment
-variables](https://www.postgresql.org/docs/9.3/static/libpq-envars.html).
-
-Example:
-
- PGHOST=/run/postgresql go test
-
-## Benchmarks
-
-A benchmark suite can be run as part of the tests:
-
- go test -bench .
-
-## Example setup (Docker)
-
-Run a postgres container:
-
-```
-docker run --expose 5432:5432 postgres
-```
-
-Run tests:
-
-```
-PGHOST=localhost PGPORT=5432 PGUSER=postgres PGSSLMODE=disable PGDATABASE=postgres go test
-```
diff --git a/vendor/github.com/lib/pq/array.go b/vendor/github.com/lib/pq/array.go
deleted file mode 100644
index 39c8f7e..0000000
--- a/vendor/github.com/lib/pq/array.go
+++ /dev/null
@@ -1,895 +0,0 @@
-package pq
-
-import (
- "bytes"
- "database/sql"
- "database/sql/driver"
- "encoding/hex"
- "fmt"
- "reflect"
- "strconv"
- "strings"
-)
-
-var typeByteSlice = reflect.TypeOf([]byte{})
-var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
-var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
-
-// Array returns the optimal driver.Valuer and sql.Scanner for an array or
-// slice of any dimension.
-//
-// For example:
-// db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))
-//
-// var x []sql.NullInt64
-// db.QueryRow(`SELECT ARRAY[235, 401]`).Scan(pq.Array(&x))
-//
-// Scanning multi-dimensional arrays is not supported. Arrays where the lower
-// bound is not one (such as `[0:0]={1}') are not supported.
-func Array(a interface{}) interface {
- driver.Valuer
- sql.Scanner
-} {
- switch a := a.(type) {
- case []bool:
- return (*BoolArray)(&a)
- case []float64:
- return (*Float64Array)(&a)
- case []float32:
- return (*Float32Array)(&a)
- case []int64:
- return (*Int64Array)(&a)
- case []int32:
- return (*Int32Array)(&a)
- case []string:
- return (*StringArray)(&a)
- case [][]byte:
- return (*ByteaArray)(&a)
-
- case *[]bool:
- return (*BoolArray)(a)
- case *[]float64:
- return (*Float64Array)(a)
- case *[]float32:
- return (*Float32Array)(a)
- case *[]int64:
- return (*Int64Array)(a)
- case *[]int32:
- return (*Int32Array)(a)
- case *[]string:
- return (*StringArray)(a)
- case *[][]byte:
- return (*ByteaArray)(a)
- }
-
- return GenericArray{a}
-}
-
-// ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner
-// to override the array delimiter used by GenericArray.
-type ArrayDelimiter interface {
- // ArrayDelimiter returns the delimiter character(s) for this element's type.
- ArrayDelimiter() string
-}
-
-// BoolArray represents a one-dimensional array of the PostgreSQL boolean type.
-type BoolArray []bool
-
-// Scan implements the sql.Scanner interface.
-func (a *BoolArray) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src)
- case string:
- return a.scanBytes([]byte(src))
- case nil:
- *a = nil
- return nil
- }
-
- return fmt.Errorf("pq: cannot convert %T to BoolArray", src)
-}
-
-func (a *BoolArray) scanBytes(src []byte) error {
- elems, err := scanLinearArray(src, []byte{','}, "BoolArray")
- if err != nil {
- return err
- }
- if *a != nil && len(elems) == 0 {
- *a = (*a)[:0]
- } else {
- b := make(BoolArray, len(elems))
- for i, v := range elems {
- if len(v) != 1 {
- return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v)
- }
- switch v[0] {
- case 't':
- b[i] = true
- case 'f':
- b[i] = false
- default:
- return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v)
- }
- }
- *a = b
- }
- return nil
-}
-
-// Value implements the driver.Valuer interface.
-func (a BoolArray) Value() (driver.Value, error) {
- if a == nil {
- return nil, nil
- }
-
- if n := len(a); n > 0 {
- // There will be exactly two curly brackets, N bytes of values,
- // and N-1 bytes of delimiters.
- b := make([]byte, 1+2*n)
-
- for i := 0; i < n; i++ {
- b[2*i] = ','
- if a[i] {
- b[1+2*i] = 't'
- } else {
- b[1+2*i] = 'f'
- }
- }
-
- b[0] = '{'
- b[2*n] = '}'
-
- return string(b), nil
- }
-
- return "{}", nil
-}
-
-// ByteaArray represents a one-dimensional array of the PostgreSQL bytea type.
-type ByteaArray [][]byte
-
-// Scan implements the sql.Scanner interface.
-func (a *ByteaArray) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src)
- case string:
- return a.scanBytes([]byte(src))
- case nil:
- *a = nil
- return nil
- }
-
- return fmt.Errorf("pq: cannot convert %T to ByteaArray", src)
-}
-
-func (a *ByteaArray) scanBytes(src []byte) error {
- elems, err := scanLinearArray(src, []byte{','}, "ByteaArray")
- if err != nil {
- return err
- }
- if *a != nil && len(elems) == 0 {
- *a = (*a)[:0]
- } else {
- b := make(ByteaArray, len(elems))
- for i, v := range elems {
- b[i], err = parseBytea(v)
- if err != nil {
- return fmt.Errorf("could not parse bytea array index %d: %s", i, err.Error())
- }
- }
- *a = b
- }
- return nil
-}
-
-// Value implements the driver.Valuer interface. It uses the "hex" format which
-// is only supported on PostgreSQL 9.0 or newer.
-func (a ByteaArray) Value() (driver.Value, error) {
- if a == nil {
- return nil, nil
- }
-
- if n := len(a); n > 0 {
- // There will be at least two curly brackets, 2*N bytes of quotes,
- // 3*N bytes of hex formatting, and N-1 bytes of delimiters.
- size := 1 + 6*n
- for _, x := range a {
- size += hex.EncodedLen(len(x))
- }
-
- b := make([]byte, size)
-
- for i, s := 0, b; i < n; i++ {
- o := copy(s, `,"\\x`)
- o += hex.Encode(s[o:], a[i])
- s[o] = '"'
- s = s[o+1:]
- }
-
- b[0] = '{'
- b[size-1] = '}'
-
- return string(b), nil
- }
-
- return "{}", nil
-}
-
-// Float64Array represents a one-dimensional array of the PostgreSQL double
-// precision type.
-type Float64Array []float64
-
-// Scan implements the sql.Scanner interface.
-func (a *Float64Array) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src)
- case string:
- return a.scanBytes([]byte(src))
- case nil:
- *a = nil
- return nil
- }
-
- return fmt.Errorf("pq: cannot convert %T to Float64Array", src)
-}
-
-func (a *Float64Array) scanBytes(src []byte) error {
- elems, err := scanLinearArray(src, []byte{','}, "Float64Array")
- if err != nil {
- return err
- }
- if *a != nil && len(elems) == 0 {
- *a = (*a)[:0]
- } else {
- b := make(Float64Array, len(elems))
- for i, v := range elems {
- if b[i], err = strconv.ParseFloat(string(v), 64); err != nil {
- return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
- }
- }
- *a = b
- }
- return nil
-}
-
-// Value implements the driver.Valuer interface.
-func (a Float64Array) Value() (driver.Value, error) {
- if a == nil {
- return nil, nil
- }
-
- if n := len(a); n > 0 {
- // There will be at least two curly brackets, N bytes of values,
- // and N-1 bytes of delimiters.
- b := make([]byte, 1, 1+2*n)
- b[0] = '{'
-
- b = strconv.AppendFloat(b, a[0], 'f', -1, 64)
- for i := 1; i < n; i++ {
- b = append(b, ',')
- b = strconv.AppendFloat(b, a[i], 'f', -1, 64)
- }
-
- return string(append(b, '}')), nil
- }
-
- return "{}", nil
-}
-
-// Float32Array represents a one-dimensional array of the PostgreSQL double
-// precision type.
-type Float32Array []float32
-
-// Scan implements the sql.Scanner interface.
-func (a *Float32Array) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src)
- case string:
- return a.scanBytes([]byte(src))
- case nil:
- *a = nil
- return nil
- }
-
- return fmt.Errorf("pq: cannot convert %T to Float32Array", src)
-}
-
-func (a *Float32Array) scanBytes(src []byte) error {
- elems, err := scanLinearArray(src, []byte{','}, "Float32Array")
- if err != nil {
- return err
- }
- if *a != nil && len(elems) == 0 {
- *a = (*a)[:0]
- } else {
- b := make(Float32Array, len(elems))
- for i, v := range elems {
- var x float64
- if x, err = strconv.ParseFloat(string(v), 32); err != nil {
- return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
- }
- b[i] = float32(x)
- }
- *a = b
- }
- return nil
-}
-
-// Value implements the driver.Valuer interface.
-func (a Float32Array) Value() (driver.Value, error) {
- if a == nil {
- return nil, nil
- }
-
- if n := len(a); n > 0 {
- // There will be at least two curly brackets, N bytes of values,
- // and N-1 bytes of delimiters.
- b := make([]byte, 1, 1+2*n)
- b[0] = '{'
-
- b = strconv.AppendFloat(b, float64(a[0]), 'f', -1, 32)
- for i := 1; i < n; i++ {
- b = append(b, ',')
- b = strconv.AppendFloat(b, float64(a[i]), 'f', -1, 32)
- }
-
- return string(append(b, '}')), nil
- }
-
- return "{}", nil
-}
-
-// GenericArray implements the driver.Valuer and sql.Scanner interfaces for
-// an array or slice of any dimension.
-type GenericArray struct{ A interface{} }
-
-func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) {
- var assign func([]byte, reflect.Value) error
- var del = ","
-
- // TODO calculate the assign function for other types
- // TODO repeat this section on the element type of arrays or slices (multidimensional)
- {
- if reflect.PtrTo(rt).Implements(typeSQLScanner) {
- // dest is always addressable because it is an element of a slice.
- assign = func(src []byte, dest reflect.Value) (err error) {
- ss := dest.Addr().Interface().(sql.Scanner)
- if src == nil {
- err = ss.Scan(nil)
- } else {
- err = ss.Scan(src)
- }
- return
- }
- goto FoundType
- }
-
- assign = func([]byte, reflect.Value) error {
- return fmt.Errorf("pq: scanning to %s is not implemented; only sql.Scanner", rt)
- }
- }
-
-FoundType:
-
- if ad, ok := reflect.Zero(rt).Interface().(ArrayDelimiter); ok {
- del = ad.ArrayDelimiter()
- }
-
- return rt, assign, del
-}
-
-// Scan implements the sql.Scanner interface.
-func (a GenericArray) Scan(src interface{}) error {
- dpv := reflect.ValueOf(a.A)
- switch {
- case dpv.Kind() != reflect.Ptr:
- return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A)
- case dpv.IsNil():
- return fmt.Errorf("pq: destination %T is nil", a.A)
- }
-
- dv := dpv.Elem()
- switch dv.Kind() {
- case reflect.Slice:
- case reflect.Array:
- default:
- return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A)
- }
-
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src, dv)
- case string:
- return a.scanBytes([]byte(src), dv)
- case nil:
- if dv.Kind() == reflect.Slice {
- dv.Set(reflect.Zero(dv.Type()))
- return nil
- }
- }
-
- return fmt.Errorf("pq: cannot convert %T to %s", src, dv.Type())
-}
-
-func (a GenericArray) scanBytes(src []byte, dv reflect.Value) error {
- dtype, assign, del := a.evaluateDestination(dv.Type().Elem())
- dims, elems, err := parseArray(src, []byte(del))
- if err != nil {
- return err
- }
-
- // TODO allow multidimensional
-
- if len(dims) > 1 {
- return fmt.Errorf("pq: scanning from multidimensional ARRAY%s is not implemented",
- strings.Replace(fmt.Sprint(dims), " ", "][", -1))
- }
-
- // Treat a zero-dimensional array like an array with a single dimension of zero.
- if len(dims) == 0 {
- dims = append(dims, 0)
- }
-
- for i, rt := 0, dv.Type(); i < len(dims); i, rt = i+1, rt.Elem() {
- switch rt.Kind() {
- case reflect.Slice:
- case reflect.Array:
- if rt.Len() != dims[i] {
- return fmt.Errorf("pq: cannot convert ARRAY%s to %s",
- strings.Replace(fmt.Sprint(dims), " ", "][", -1), dv.Type())
- }
- default:
- // TODO handle multidimensional
- }
- }
-
- values := reflect.MakeSlice(reflect.SliceOf(dtype), len(elems), len(elems))
- for i, e := range elems {
- if err := assign(e, values.Index(i)); err != nil {
- return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
- }
- }
-
- // TODO handle multidimensional
-
- switch dv.Kind() {
- case reflect.Slice:
- dv.Set(values.Slice(0, dims[0]))
- case reflect.Array:
- for i := 0; i < dims[0]; i++ {
- dv.Index(i).Set(values.Index(i))
- }
- }
-
- return nil
-}
-
-// Value implements the driver.Valuer interface.
-func (a GenericArray) Value() (driver.Value, error) {
- if a.A == nil {
- return nil, nil
- }
-
- rv := reflect.ValueOf(a.A)
-
- switch rv.Kind() {
- case reflect.Slice:
- if rv.IsNil() {
- return nil, nil
- }
- case reflect.Array:
- default:
- return nil, fmt.Errorf("pq: Unable to convert %T to array", a.A)
- }
-
- if n := rv.Len(); n > 0 {
- // There will be at least two curly brackets, N bytes of values,
- // and N-1 bytes of delimiters.
- b := make([]byte, 0, 1+2*n)
-
- b, _, err := appendArray(b, rv, n)
- return string(b), err
- }
-
- return "{}", nil
-}
-
-// Int64Array represents a one-dimensional array of the PostgreSQL integer types.
-type Int64Array []int64
-
-// Scan implements the sql.Scanner interface.
-func (a *Int64Array) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src)
- case string:
- return a.scanBytes([]byte(src))
- case nil:
- *a = nil
- return nil
- }
-
- return fmt.Errorf("pq: cannot convert %T to Int64Array", src)
-}
-
-func (a *Int64Array) scanBytes(src []byte) error {
- elems, err := scanLinearArray(src, []byte{','}, "Int64Array")
- if err != nil {
- return err
- }
- if *a != nil && len(elems) == 0 {
- *a = (*a)[:0]
- } else {
- b := make(Int64Array, len(elems))
- for i, v := range elems {
- if b[i], err = strconv.ParseInt(string(v), 10, 64); err != nil {
- return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
- }
- }
- *a = b
- }
- return nil
-}
-
-// Value implements the driver.Valuer interface.
-func (a Int64Array) Value() (driver.Value, error) {
- if a == nil {
- return nil, nil
- }
-
- if n := len(a); n > 0 {
- // There will be at least two curly brackets, N bytes of values,
- // and N-1 bytes of delimiters.
- b := make([]byte, 1, 1+2*n)
- b[0] = '{'
-
- b = strconv.AppendInt(b, a[0], 10)
- for i := 1; i < n; i++ {
- b = append(b, ',')
- b = strconv.AppendInt(b, a[i], 10)
- }
-
- return string(append(b, '}')), nil
- }
-
- return "{}", nil
-}
-
-// Int32Array represents a one-dimensional array of the PostgreSQL integer types.
-type Int32Array []int32
-
-// Scan implements the sql.Scanner interface.
-func (a *Int32Array) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src)
- case string:
- return a.scanBytes([]byte(src))
- case nil:
- *a = nil
- return nil
- }
-
- return fmt.Errorf("pq: cannot convert %T to Int32Array", src)
-}
-
-func (a *Int32Array) scanBytes(src []byte) error {
- elems, err := scanLinearArray(src, []byte{','}, "Int32Array")
- if err != nil {
- return err
- }
- if *a != nil && len(elems) == 0 {
- *a = (*a)[:0]
- } else {
- b := make(Int32Array, len(elems))
- for i, v := range elems {
- x, err := strconv.ParseInt(string(v), 10, 32)
- if err != nil {
- return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
- }
- b[i] = int32(x)
- }
- *a = b
- }
- return nil
-}
-
-// Value implements the driver.Valuer interface.
-func (a Int32Array) Value() (driver.Value, error) {
- if a == nil {
- return nil, nil
- }
-
- if n := len(a); n > 0 {
- // There will be at least two curly brackets, N bytes of values,
- // and N-1 bytes of delimiters.
- b := make([]byte, 1, 1+2*n)
- b[0] = '{'
-
- b = strconv.AppendInt(b, int64(a[0]), 10)
- for i := 1; i < n; i++ {
- b = append(b, ',')
- b = strconv.AppendInt(b, int64(a[i]), 10)
- }
-
- return string(append(b, '}')), nil
- }
-
- return "{}", nil
-}
-
-// StringArray represents a one-dimensional array of the PostgreSQL character types.
-type StringArray []string
-
-// Scan implements the sql.Scanner interface.
-func (a *StringArray) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- return a.scanBytes(src)
- case string:
- return a.scanBytes([]byte(src))
- case nil:
- *a = nil
- return nil
- }
-
- return fmt.Errorf("pq: cannot convert %T to StringArray", src)
-}
-
-func (a *StringArray) scanBytes(src []byte) error {
- elems, err := scanLinearArray(src, []byte{','}, "StringArray")
- if err != nil {
- return err
- }
- if *a != nil && len(elems) == 0 {
- *a = (*a)[:0]
- } else {
- b := make(StringArray, len(elems))
- for i, v := range elems {
- if b[i] = string(v); v == nil {
- return fmt.Errorf("pq: parsing array element index %d: cannot convert nil to string", i)
- }
- }
- *a = b
- }
- return nil
-}
-
-// Value implements the driver.Valuer interface.
-func (a StringArray) Value() (driver.Value, error) {
- if a == nil {
- return nil, nil
- }
-
- if n := len(a); n > 0 {
- // There will be at least two curly brackets, 2*N bytes of quotes,
- // and N-1 bytes of delimiters.
- b := make([]byte, 1, 1+3*n)
- b[0] = '{'
-
- b = appendArrayQuotedBytes(b, []byte(a[0]))
- for i := 1; i < n; i++ {
- b = append(b, ',')
- b = appendArrayQuotedBytes(b, []byte(a[i]))
- }
-
- return string(append(b, '}')), nil
- }
-
- return "{}", nil
-}
-
-// appendArray appends rv to the buffer, returning the extended buffer and
-// the delimiter used between elements.
-//
-// It panics when n <= 0 or rv's Kind is not reflect.Array nor reflect.Slice.
-func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) {
- var del string
- var err error
-
- b = append(b, '{')
-
- if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil {
- return b, del, err
- }
-
- for i := 1; i < n; i++ {
- b = append(b, del...)
- if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil {
- return b, del, err
- }
- }
-
- return append(b, '}'), del, nil
-}
-
-// appendArrayElement appends rv to the buffer, returning the extended buffer
-// and the delimiter to use before the next element.
-//
-// When rv's Kind is neither reflect.Array nor reflect.Slice, it is converted
-// using driver.DefaultParameterConverter and the resulting []byte or string
-// is double-quoted.
-//
-// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO
-func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) {
- if k := rv.Kind(); k == reflect.Array || k == reflect.Slice {
- if t := rv.Type(); t != typeByteSlice && !t.Implements(typeDriverValuer) {
- if n := rv.Len(); n > 0 {
- return appendArray(b, rv, n)
- }
-
- return b, "", nil
- }
- }
-
- var del = ","
- var err error
- var iv interface{} = rv.Interface()
-
- if ad, ok := iv.(ArrayDelimiter); ok {
- del = ad.ArrayDelimiter()
- }
-
- if iv, err = driver.DefaultParameterConverter.ConvertValue(iv); err != nil {
- return b, del, err
- }
-
- switch v := iv.(type) {
- case nil:
- return append(b, "NULL"...), del, nil
- case []byte:
- return appendArrayQuotedBytes(b, v), del, nil
- case string:
- return appendArrayQuotedBytes(b, []byte(v)), del, nil
- }
-
- b, err = appendValue(b, iv)
- return b, del, err
-}
-
-func appendArrayQuotedBytes(b, v []byte) []byte {
- b = append(b, '"')
- for {
- i := bytes.IndexAny(v, `"\`)
- if i < 0 {
- b = append(b, v...)
- break
- }
- if i > 0 {
- b = append(b, v[:i]...)
- }
- b = append(b, '\\', v[i])
- v = v[i+1:]
- }
- return append(b, '"')
-}
-
-func appendValue(b []byte, v driver.Value) ([]byte, error) {
- return append(b, encode(nil, v, 0)...), nil
-}
-
-// parseArray extracts the dimensions and elements of an array represented in
-// text format. Only representations emitted by the backend are supported.
-// Notably, whitespace around brackets and delimiters is significant, and NULL
-// is case-sensitive.
-//
-// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO
-func parseArray(src, del []byte) (dims []int, elems [][]byte, err error) {
- var depth, i int
-
- if len(src) < 1 || src[0] != '{' {
- return nil, nil, fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '{', 0)
- }
-
-Open:
- for i < len(src) {
- switch src[i] {
- case '{':
- depth++
- i++
- case '}':
- elems = make([][]byte, 0)
- goto Close
- default:
- break Open
- }
- }
- dims = make([]int, i)
-
-Element:
- for i < len(src) {
- switch src[i] {
- case '{':
- if depth == len(dims) {
- break Element
- }
- depth++
- dims[depth-1] = 0
- i++
- case '"':
- var elem = []byte{}
- var escape bool
- for i++; i < len(src); i++ {
- if escape {
- elem = append(elem, src[i])
- escape = false
- } else {
- switch src[i] {
- default:
- elem = append(elem, src[i])
- case '\\':
- escape = true
- case '"':
- elems = append(elems, elem)
- i++
- break Element
- }
- }
- }
- default:
- for start := i; i < len(src); i++ {
- if bytes.HasPrefix(src[i:], del) || src[i] == '}' {
- elem := src[start:i]
- if len(elem) == 0 {
- return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i)
- }
- if bytes.Equal(elem, []byte("NULL")) {
- elem = nil
- }
- elems = append(elems, elem)
- break Element
- }
- }
- }
- }
-
- for i < len(src) {
- if bytes.HasPrefix(src[i:], del) && depth > 0 {
- dims[depth-1]++
- i += len(del)
- goto Element
- } else if src[i] == '}' && depth > 0 {
- dims[depth-1]++
- depth--
- i++
- } else {
- return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i)
- }
- }
-
-Close:
- for i < len(src) {
- if src[i] == '}' && depth > 0 {
- depth--
- i++
- } else {
- return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i)
- }
- }
- if depth > 0 {
- err = fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '}', i)
- }
- if err == nil {
- for _, d := range dims {
- if (len(elems) % d) != 0 {
- err = fmt.Errorf("pq: multidimensional arrays must have elements with matching dimensions")
- }
- }
- }
- return
-}
-
-func scanLinearArray(src, del []byte, typ string) (elems [][]byte, err error) {
- dims, elems, err := parseArray(src, del)
- if err != nil {
- return nil, err
- }
- if len(dims) > 1 {
- return nil, fmt.Errorf("pq: cannot convert ARRAY%s to %s", strings.Replace(fmt.Sprint(dims), " ", "][", -1), typ)
- }
- return elems, err
-}
diff --git a/vendor/github.com/lib/pq/buf.go b/vendor/github.com/lib/pq/buf.go
deleted file mode 100644
index 4b0a0a8..0000000
--- a/vendor/github.com/lib/pq/buf.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package pq
-
-import (
- "bytes"
- "encoding/binary"
-
- "github.com/lib/pq/oid"
-)
-
-type readBuf []byte
-
-func (b *readBuf) int32() (n int) {
- n = int(int32(binary.BigEndian.Uint32(*b)))
- *b = (*b)[4:]
- return
-}
-
-func (b *readBuf) oid() (n oid.Oid) {
- n = oid.Oid(binary.BigEndian.Uint32(*b))
- *b = (*b)[4:]
- return
-}
-
-// N.B: this is actually an unsigned 16-bit integer, unlike int32
-func (b *readBuf) int16() (n int) {
- n = int(binary.BigEndian.Uint16(*b))
- *b = (*b)[2:]
- return
-}
-
-func (b *readBuf) string() string {
- i := bytes.IndexByte(*b, 0)
- if i < 0 {
- errorf("invalid message format; expected string terminator")
- }
- s := (*b)[:i]
- *b = (*b)[i+1:]
- return string(s)
-}
-
-func (b *readBuf) next(n int) (v []byte) {
- v = (*b)[:n]
- *b = (*b)[n:]
- return
-}
-
-func (b *readBuf) byte() byte {
- return b.next(1)[0]
-}
-
-type writeBuf struct {
- buf []byte
- pos int
-}
-
-func (b *writeBuf) int32(n int) {
- x := make([]byte, 4)
- binary.BigEndian.PutUint32(x, uint32(n))
- b.buf = append(b.buf, x...)
-}
-
-func (b *writeBuf) int16(n int) {
- x := make([]byte, 2)
- binary.BigEndian.PutUint16(x, uint16(n))
- b.buf = append(b.buf, x...)
-}
-
-func (b *writeBuf) string(s string) {
- b.buf = append(append(b.buf, s...), '\000')
-}
-
-func (b *writeBuf) byte(c byte) {
- b.buf = append(b.buf, c)
-}
-
-func (b *writeBuf) bytes(v []byte) {
- b.buf = append(b.buf, v...)
-}
-
-func (b *writeBuf) wrap() []byte {
- p := b.buf[b.pos:]
- binary.BigEndian.PutUint32(p, uint32(len(p)))
- return b.buf
-}
-
-func (b *writeBuf) next(c byte) {
- p := b.buf[b.pos:]
- binary.BigEndian.PutUint32(p, uint32(len(p)))
- b.pos = len(b.buf) + 1
- b.buf = append(b.buf, c, 0, 0, 0, 0)
-}
diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go
deleted file mode 100644
index da4ff9d..0000000
--- a/vendor/github.com/lib/pq/conn.go
+++ /dev/null
@@ -1,2112 +0,0 @@
-package pq
-
-import (
- "bufio"
- "bytes"
- "context"
- "crypto/md5"
- "crypto/sha256"
- "database/sql"
- "database/sql/driver"
- "encoding/binary"
- "errors"
- "fmt"
- "io"
- "net"
- "os"
- "os/user"
- "path"
- "path/filepath"
- "strconv"
- "strings"
- "sync"
- "time"
- "unicode"
-
- "github.com/lib/pq/oid"
- "github.com/lib/pq/scram"
-)
-
-// Common error types
-var (
- ErrNotSupported = errors.New("pq: Unsupported command")
- ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction")
- ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server")
- ErrSSLKeyUnknownOwnership = errors.New("pq: Could not get owner information for private key, may not be properly protected")
- ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key has world access. Permissions should be u=rw,g=r (0640) if owned by root, or u=rw (0600), or less")
-
- ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly")
-
- errUnexpectedReady = errors.New("unexpected ReadyForQuery")
- errNoRowsAffected = errors.New("no RowsAffected available after the empty statement")
- errNoLastInsertID = errors.New("no LastInsertId available after the empty statement")
-)
-
-// Compile time validation that our types implement the expected interfaces
-var (
- _ driver.Driver = Driver{}
-)
-
-// Driver is the Postgres database driver.
-type Driver struct{}
-
-// Open opens a new connection to the database. name is a connection string.
-// Most users should only use it through database/sql package from the standard
-// library.
-func (d Driver) Open(name string) (driver.Conn, error) {
- return Open(name)
-}
-
-func init() {
- sql.Register("postgres", &Driver{})
-}
-
-type parameterStatus struct {
- // server version in the same format as server_version_num, or 0 if
- // unavailable
- serverVersion int
-
- // the current location based on the TimeZone value of the session, if
- // available
- currentLocation *time.Location
-}
-
-type transactionStatus byte
-
-const (
- txnStatusIdle transactionStatus = 'I'
- txnStatusIdleInTransaction transactionStatus = 'T'
- txnStatusInFailedTransaction transactionStatus = 'E'
-)
-
-func (s transactionStatus) String() string {
- switch s {
- case txnStatusIdle:
- return "idle"
- case txnStatusIdleInTransaction:
- return "idle in transaction"
- case txnStatusInFailedTransaction:
- return "in a failed transaction"
- default:
- errorf("unknown transactionStatus %d", s)
- }
-
- panic("not reached")
-}
-
-// Dialer is the dialer interface. It can be used to obtain more control over
-// how pq creates network connections.
-type Dialer interface {
- Dial(network, address string) (net.Conn, error)
- DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
-}
-
-// DialerContext is the context-aware dialer interface.
-type DialerContext interface {
- DialContext(ctx context.Context, network, address string) (net.Conn, error)
-}
-
-type defaultDialer struct {
- d net.Dialer
-}
-
-func (d defaultDialer) Dial(network, address string) (net.Conn, error) {
- return d.d.Dial(network, address)
-}
-func (d defaultDialer) DialTimeout(
- network, address string, timeout time.Duration,
-) (net.Conn, error) {
- ctx, cancel := context.WithTimeout(context.Background(), timeout)
- defer cancel()
- return d.DialContext(ctx, network, address)
-}
-func (d defaultDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
- return d.d.DialContext(ctx, network, address)
-}
-
-type conn struct {
- c net.Conn
- buf *bufio.Reader
- namei int
- scratch [512]byte
- txnStatus transactionStatus
- txnFinish func()
-
- // Save connection arguments to use during CancelRequest.
- dialer Dialer
- opts values
-
- // Cancellation key data for use with CancelRequest messages.
- processID int
- secretKey int
-
- parameterStatus parameterStatus
-
- saveMessageType byte
- saveMessageBuffer []byte
-
- // If an error is set, this connection is bad and all public-facing
- // functions should return the appropriate error by calling get()
- // (ErrBadConn) or getForNext().
- err syncErr
-
- // If set, this connection should never use the binary format when
- // receiving query results from prepared statements. Only provided for
- // debugging.
- disablePreparedBinaryResult bool
-
- // Whether to always send []byte parameters over as binary. Enables single
- // round-trip mode for non-prepared Query calls.
- binaryParameters bool
-
- // If true this connection is in the middle of a COPY
- inCopy bool
-
- // If not nil, notices will be synchronously sent here
- noticeHandler func(*Error)
-
- // If not nil, notifications will be synchronously sent here
- notificationHandler func(*Notification)
-
- // GSSAPI context
- gss GSS
-}
-
-type syncErr struct {
- err error
- sync.Mutex
-}
-
-// Return ErrBadConn if connection is bad.
-func (e *syncErr) get() error {
- e.Lock()
- defer e.Unlock()
- if e.err != nil {
- return driver.ErrBadConn
- }
- return nil
-}
-
-// Return the error set on the connection. Currently only used by rows.Next.
-func (e *syncErr) getForNext() error {
- e.Lock()
- defer e.Unlock()
- return e.err
-}
-
-// Set error, only if it isn't set yet.
-func (e *syncErr) set(err error) {
- if err == nil {
- panic("attempt to set nil err")
- }
- e.Lock()
- defer e.Unlock()
- if e.err == nil {
- e.err = err
- }
-}
-
-// Handle driver-side settings in parsed connection string.
-func (cn *conn) handleDriverSettings(o values) (err error) {
- boolSetting := func(key string, val *bool) error {
- if value, ok := o[key]; ok {
- if value == "yes" {
- *val = true
- } else if value == "no" {
- *val = false
- } else {
- return fmt.Errorf("unrecognized value %q for %s", value, key)
- }
- }
- return nil
- }
-
- err = boolSetting("disable_prepared_binary_result", &cn.disablePreparedBinaryResult)
- if err != nil {
- return err
- }
- return boolSetting("binary_parameters", &cn.binaryParameters)
-}
-
-func (cn *conn) handlePgpass(o values) {
- // if a password was supplied, do not process .pgpass
- if _, ok := o["password"]; ok {
- return
- }
- filename := os.Getenv("PGPASSFILE")
- if filename == "" {
- // XXX this code doesn't work on Windows where the default filename is
- // XXX %APPDATA%\postgresql\pgpass.conf
- // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470
- userHome := os.Getenv("HOME")
- if userHome == "" {
- user, err := user.Current()
- if err != nil {
- return
- }
- userHome = user.HomeDir
- }
- filename = filepath.Join(userHome, ".pgpass")
- }
- fileinfo, err := os.Stat(filename)
- if err != nil {
- return
- }
- mode := fileinfo.Mode()
- if mode&(0x77) != 0 {
- // XXX should warn about incorrect .pgpass permissions as psql does
- return
- }
- file, err := os.Open(filename)
- if err != nil {
- return
- }
- defer file.Close()
- scanner := bufio.NewScanner(io.Reader(file))
- // From: https://github.com/tg/pgpass/blob/master/reader.go
- for scanner.Scan() {
- if scanText(scanner.Text(), o) {
- break
- }
- }
-}
-
-// GetFields is a helper function for scanText.
-func getFields(s string) []string {
- fs := make([]string, 0, 5)
- f := make([]rune, 0, len(s))
-
- var esc bool
- for _, c := range s {
- switch {
- case esc:
- f = append(f, c)
- esc = false
- case c == '\\':
- esc = true
- case c == ':':
- fs = append(fs, string(f))
- f = f[:0]
- default:
- f = append(f, c)
- }
- }
- return append(fs, string(f))
-}
-
-// ScanText assists HandlePgpass in it's objective.
-func scanText(line string, o values) bool {
- hostname := o["host"]
- ntw, _ := network(o)
- port := o["port"]
- db := o["dbname"]
- username := o["user"]
- if len(line) == 0 || line[0] == '#' {
- return false
- }
- split := getFields(line)
- if len(split) != 5 {
- return false
- }
- if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) {
- o["password"] = split[4]
- return true
- }
- return false
-}
-
-func (cn *conn) writeBuf(b byte) *writeBuf {
- cn.scratch[0] = b
- return &writeBuf{
- buf: cn.scratch[:5],
- pos: 1,
- }
-}
-
-// Open opens a new connection to the database. dsn is a connection string.
-// Most users should only use it through database/sql package from the standard
-// library.
-func Open(dsn string) (_ driver.Conn, err error) {
- return DialOpen(defaultDialer{}, dsn)
-}
-
-// DialOpen opens a new connection to the database using a dialer.
-func DialOpen(d Dialer, dsn string) (_ driver.Conn, err error) {
- c, err := NewConnector(dsn)
- if err != nil {
- return nil, err
- }
- c.Dialer(d)
- return c.open(context.Background())
-}
-
-func (c *Connector) open(ctx context.Context) (cn *conn, err error) {
- // Handle any panics during connection initialization. Note that we
- // specifically do *not* want to use errRecover(), as that would turn any
- // connection errors into ErrBadConns, hiding the real error message from
- // the user.
- defer errRecoverNoErrBadConn(&err)
-
- // Create a new values map (copy). This makes it so maps in different
- // connections do not reference the same underlying data structure, so it
- // is safe for multiple connections to concurrently write to their opts.
- o := make(values)
- for k, v := range c.opts {
- o[k] = v
- }
-
- cn = &conn{
- opts: o,
- dialer: c.dialer,
- }
- err = cn.handleDriverSettings(o)
- if err != nil {
- return nil, err
- }
- cn.handlePgpass(o)
-
- cn.c, err = dial(ctx, c.dialer, o)
- if err != nil {
- return nil, err
- }
-
- err = cn.ssl(o)
- if err != nil {
- if cn.c != nil {
- cn.c.Close()
- }
- return nil, err
- }
-
- // cn.startup panics on error. Make sure we don't leak cn.c.
- panicking := true
- defer func() {
- if panicking {
- cn.c.Close()
- }
- }()
-
- cn.buf = bufio.NewReader(cn.c)
- cn.startup(o)
-
- // reset the deadline, in case one was set (see dial)
- if timeout, ok := o["connect_timeout"]; ok && timeout != "0" {
- err = cn.c.SetDeadline(time.Time{})
- }
- panicking = false
- return cn, err
-}
-
-func dial(ctx context.Context, d Dialer, o values) (net.Conn, error) {
- network, address := network(o)
-
- // Zero or not specified means wait indefinitely.
- if timeout, ok := o["connect_timeout"]; ok && timeout != "0" {
- seconds, err := strconv.ParseInt(timeout, 10, 0)
- if err != nil {
- return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err)
- }
- duration := time.Duration(seconds) * time.Second
-
- // connect_timeout should apply to the entire connection establishment
- // procedure, so we both use a timeout for the TCP connection
- // establishment and set a deadline for doing the initial handshake.
- // The deadline is then reset after startup() is done.
- deadline := time.Now().Add(duration)
- var conn net.Conn
- if dctx, ok := d.(DialerContext); ok {
- ctx, cancel := context.WithTimeout(ctx, duration)
- defer cancel()
- conn, err = dctx.DialContext(ctx, network, address)
- } else {
- conn, err = d.DialTimeout(network, address, duration)
- }
- if err != nil {
- return nil, err
- }
- err = conn.SetDeadline(deadline)
- return conn, err
- }
- if dctx, ok := d.(DialerContext); ok {
- return dctx.DialContext(ctx, network, address)
- }
- return d.Dial(network, address)
-}
-
-func network(o values) (string, string) {
- host := o["host"]
-
- if strings.HasPrefix(host, "/") {
- sockPath := path.Join(host, ".s.PGSQL."+o["port"])
- return "unix", sockPath
- }
-
- return "tcp", net.JoinHostPort(host, o["port"])
-}
-
-type values map[string]string
-
-// scanner implements a tokenizer for libpq-style option strings.
-type scanner struct {
- s []rune
- i int
-}
-
-// newScanner returns a new scanner initialized with the option string s.
-func newScanner(s string) *scanner {
- return &scanner{[]rune(s), 0}
-}
-
-// Next returns the next rune.
-// It returns 0, false if the end of the text has been reached.
-func (s *scanner) Next() (rune, bool) {
- if s.i >= len(s.s) {
- return 0, false
- }
- r := s.s[s.i]
- s.i++
- return r, true
-}
-
-// SkipSpaces returns the next non-whitespace rune.
-// It returns 0, false if the end of the text has been reached.
-func (s *scanner) SkipSpaces() (rune, bool) {
- r, ok := s.Next()
- for unicode.IsSpace(r) && ok {
- r, ok = s.Next()
- }
- return r, ok
-}
-
-// parseOpts parses the options from name and adds them to the values.
-//
-// The parsing code is based on conninfo_parse from libpq's fe-connect.c
-func parseOpts(name string, o values) error {
- s := newScanner(name)
-
- for {
- var (
- keyRunes, valRunes []rune
- r rune
- ok bool
- )
-
- if r, ok = s.SkipSpaces(); !ok {
- break
- }
-
- // Scan the key
- for !unicode.IsSpace(r) && r != '=' {
- keyRunes = append(keyRunes, r)
- if r, ok = s.Next(); !ok {
- break
- }
- }
-
- // Skip any whitespace if we're not at the = yet
- if r != '=' {
- r, ok = s.SkipSpaces()
- }
-
- // The current character should be =
- if r != '=' || !ok {
- return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes))
- }
-
- // Skip any whitespace after the =
- if r, ok = s.SkipSpaces(); !ok {
- // If we reach the end here, the last value is just an empty string as per libpq.
- o[string(keyRunes)] = ""
- break
- }
-
- if r != '\'' {
- for !unicode.IsSpace(r) {
- if r == '\\' {
- if r, ok = s.Next(); !ok {
- return fmt.Errorf(`missing character after backslash`)
- }
- }
- valRunes = append(valRunes, r)
-
- if r, ok = s.Next(); !ok {
- break
- }
- }
- } else {
- quote:
- for {
- if r, ok = s.Next(); !ok {
- return fmt.Errorf(`unterminated quoted string literal in connection string`)
- }
- switch r {
- case '\'':
- break quote
- case '\\':
- r, _ = s.Next()
- fallthrough
- default:
- valRunes = append(valRunes, r)
- }
- }
- }
-
- o[string(keyRunes)] = string(valRunes)
- }
-
- return nil
-}
-
-func (cn *conn) isInTransaction() bool {
- return cn.txnStatus == txnStatusIdleInTransaction ||
- cn.txnStatus == txnStatusInFailedTransaction
-}
-
-func (cn *conn) checkIsInTransaction(intxn bool) {
- if cn.isInTransaction() != intxn {
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected transaction status %v", cn.txnStatus)
- }
-}
-
-func (cn *conn) Begin() (_ driver.Tx, err error) {
- return cn.begin("")
-}
-
-func (cn *conn) begin(mode string) (_ driver.Tx, err error) {
- if err := cn.err.get(); err != nil {
- return nil, err
- }
- defer cn.errRecover(&err)
-
- cn.checkIsInTransaction(false)
- _, commandTag, err := cn.simpleExec("BEGIN" + mode)
- if err != nil {
- return nil, err
- }
- if commandTag != "BEGIN" {
- cn.err.set(driver.ErrBadConn)
- return nil, fmt.Errorf("unexpected command tag %s", commandTag)
- }
- if cn.txnStatus != txnStatusIdleInTransaction {
- cn.err.set(driver.ErrBadConn)
- return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus)
- }
- return cn, nil
-}
-
-func (cn *conn) closeTxn() {
- if finish := cn.txnFinish; finish != nil {
- finish()
- }
-}
-
-func (cn *conn) Commit() (err error) {
- defer cn.closeTxn()
- if err := cn.err.get(); err != nil {
- return err
- }
- defer cn.errRecover(&err)
-
- cn.checkIsInTransaction(true)
- // We don't want the client to think that everything is okay if it tries
- // to commit a failed transaction. However, no matter what we return,
- // database/sql will release this connection back into the free connection
- // pool so we have to abort the current transaction here. Note that you
- // would get the same behaviour if you issued a COMMIT in a failed
- // transaction, so it's also the least surprising thing to do here.
- if cn.txnStatus == txnStatusInFailedTransaction {
- if err := cn.rollback(); err != nil {
- return err
- }
- return ErrInFailedTransaction
- }
-
- _, commandTag, err := cn.simpleExec("COMMIT")
- if err != nil {
- if cn.isInTransaction() {
- cn.err.set(driver.ErrBadConn)
- }
- return err
- }
- if commandTag != "COMMIT" {
- cn.err.set(driver.ErrBadConn)
- return fmt.Errorf("unexpected command tag %s", commandTag)
- }
- cn.checkIsInTransaction(false)
- return nil
-}
-
-func (cn *conn) Rollback() (err error) {
- defer cn.closeTxn()
- if err := cn.err.get(); err != nil {
- return err
- }
- defer cn.errRecover(&err)
- return cn.rollback()
-}
-
-func (cn *conn) rollback() (err error) {
- cn.checkIsInTransaction(true)
- _, commandTag, err := cn.simpleExec("ROLLBACK")
- if err != nil {
- if cn.isInTransaction() {
- cn.err.set(driver.ErrBadConn)
- }
- return err
- }
- if commandTag != "ROLLBACK" {
- return fmt.Errorf("unexpected command tag %s", commandTag)
- }
- cn.checkIsInTransaction(false)
- return nil
-}
-
-func (cn *conn) gname() string {
- cn.namei++
- return strconv.FormatInt(int64(cn.namei), 10)
-}
-
-func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) {
- b := cn.writeBuf('Q')
- b.string(q)
- cn.send(b)
-
- for {
- t, r := cn.recv1()
- switch t {
- case 'C':
- res, commandTag = cn.parseComplete(r.string())
- case 'Z':
- cn.processReadyForQuery(r)
- if res == nil && err == nil {
- err = errUnexpectedReady
- }
- // done
- return
- case 'E':
- err = parseError(r)
- case 'I':
- res = emptyRows
- case 'T', 'D':
- // ignore any results
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unknown response for simple query: %q", t)
- }
- }
-}
-
-func (cn *conn) simpleQuery(q string) (res *rows, err error) {
- defer cn.errRecover(&err)
-
- b := cn.writeBuf('Q')
- b.string(q)
- cn.send(b)
-
- for {
- t, r := cn.recv1()
- switch t {
- case 'C', 'I':
- // We allow queries which don't return any results through Query as
- // well as Exec. We still have to give database/sql a rows object
- // the user can close, though, to avoid connections from being
- // leaked. A "rows" with done=true works fine for that purpose.
- if err != nil {
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected message %q in simple query execution", t)
- }
- if res == nil {
- res = &rows{
- cn: cn,
- }
- }
- // Set the result and tag to the last command complete if there wasn't a
- // query already run. Although queries usually return from here and cede
- // control to Next, a query with zero results does not.
- if t == 'C' {
- res.result, res.tag = cn.parseComplete(r.string())
- if res.colNames != nil {
- return
- }
- }
- res.done = true
- case 'Z':
- cn.processReadyForQuery(r)
- // done
- return
- case 'E':
- res = nil
- err = parseError(r)
- case 'D':
- if res == nil {
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected DataRow in simple query execution")
- }
- // the query didn't fail; kick off to Next
- cn.saveMessage(t, r)
- return
- case 'T':
- // res might be non-nil here if we received a previous
- // CommandComplete, but that's fine; just overwrite it
- res = &rows{cn: cn}
- res.rowsHeader = parsePortalRowDescribe(r)
-
- // To work around a bug in QueryRow in Go 1.2 and earlier, wait
- // until the first DataRow has been received.
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unknown response for simple query: %q", t)
- }
- }
-}
-
-type noRows struct{}
-
-var emptyRows noRows
-
-var _ driver.Result = noRows{}
-
-func (noRows) LastInsertId() (int64, error) {
- return 0, errNoLastInsertID
-}
-
-func (noRows) RowsAffected() (int64, error) {
- return 0, errNoRowsAffected
-}
-
-// Decides which column formats to use for a prepared statement. The input is
-// an array of type oids, one element per result column.
-func decideColumnFormats(
- colTyps []fieldDesc, forceText bool,
-) (colFmts []format, colFmtData []byte) {
- if len(colTyps) == 0 {
- return nil, colFmtDataAllText
- }
-
- colFmts = make([]format, len(colTyps))
- if forceText {
- return colFmts, colFmtDataAllText
- }
-
- allBinary := true
- allText := true
- for i, t := range colTyps {
- switch t.OID {
- // This is the list of types to use binary mode for when receiving them
- // through a prepared statement. If a type appears in this list, it
- // must also be implemented in binaryDecode in encode.go.
- case oid.T_bytea:
- fallthrough
- case oid.T_int8:
- fallthrough
- case oid.T_int4:
- fallthrough
- case oid.T_int2:
- fallthrough
- case oid.T_uuid:
- colFmts[i] = formatBinary
- allText = false
-
- default:
- allBinary = false
- }
- }
-
- if allBinary {
- return colFmts, colFmtDataAllBinary
- } else if allText {
- return colFmts, colFmtDataAllText
- } else {
- colFmtData = make([]byte, 2+len(colFmts)*2)
- binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts)))
- for i, v := range colFmts {
- binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v))
- }
- return colFmts, colFmtData
- }
-}
-
-func (cn *conn) prepareTo(q, stmtName string) *stmt {
- st := &stmt{cn: cn, name: stmtName}
-
- b := cn.writeBuf('P')
- b.string(st.name)
- b.string(q)
- b.int16(0)
-
- b.next('D')
- b.byte('S')
- b.string(st.name)
-
- b.next('S')
- cn.send(b)
-
- cn.readParseResponse()
- st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse()
- st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult)
- cn.readReadyForQuery()
- return st
-}
-
-func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) {
- if err := cn.err.get(); err != nil {
- return nil, err
- }
- defer cn.errRecover(&err)
-
- if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") {
- s, err := cn.prepareCopyIn(q)
- if err == nil {
- cn.inCopy = true
- }
- return s, err
- }
- return cn.prepareTo(q, cn.gname()), nil
-}
-
-func (cn *conn) Close() (err error) {
- // Skip cn.bad return here because we always want to close a connection.
- defer cn.errRecover(&err)
-
- // Ensure that cn.c.Close is always run. Since error handling is done with
- // panics and cn.errRecover, the Close must be in a defer.
- defer func() {
- cerr := cn.c.Close()
- if err == nil {
- err = cerr
- }
- }()
-
- // Don't go through send(); ListenerConn relies on us not scribbling on the
- // scratch buffer of this connection.
- return cn.sendSimpleMessage('X')
-}
-
-// Implement the "Queryer" interface
-func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) {
- return cn.query(query, args)
-}
-
-func (cn *conn) query(query string, args []driver.Value) (_ *rows, err error) {
- if err := cn.err.get(); err != nil {
- return nil, err
- }
- if cn.inCopy {
- return nil, errCopyInProgress
- }
- defer cn.errRecover(&err)
-
- // Check to see if we can use the "simpleQuery" interface, which is
- // *much* faster than going through prepare/exec
- if len(args) == 0 {
- return cn.simpleQuery(query)
- }
-
- if cn.binaryParameters {
- cn.sendBinaryModeQuery(query, args)
-
- cn.readParseResponse()
- cn.readBindResponse()
- rows := &rows{cn: cn}
- rows.rowsHeader = cn.readPortalDescribeResponse()
- cn.postExecuteWorkaround()
- return rows, nil
- }
- st := cn.prepareTo(query, "")
- st.exec(args)
- return &rows{
- cn: cn,
- rowsHeader: st.rowsHeader,
- }, nil
-}
-
-// Implement the optional "Execer" interface for one-shot queries
-func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) {
- if err := cn.err.get(); err != nil {
- return nil, err
- }
- defer cn.errRecover(&err)
-
- // Check to see if we can use the "simpleExec" interface, which is
- // *much* faster than going through prepare/exec
- if len(args) == 0 {
- // ignore commandTag, our caller doesn't care
- r, _, err := cn.simpleExec(query)
- return r, err
- }
-
- if cn.binaryParameters {
- cn.sendBinaryModeQuery(query, args)
-
- cn.readParseResponse()
- cn.readBindResponse()
- cn.readPortalDescribeResponse()
- cn.postExecuteWorkaround()
- res, _, err = cn.readExecuteResponse("Execute")
- return res, err
- }
- // Use the unnamed statement to defer planning until bind
- // time, or else value-based selectivity estimates cannot be
- // used.
- st := cn.prepareTo(query, "")
- r, err := st.Exec(args)
- if err != nil {
- panic(err)
- }
- return r, err
-}
-
-type safeRetryError struct {
- Err error
-}
-
-func (se *safeRetryError) Error() string {
- return se.Err.Error()
-}
-
-func (cn *conn) send(m *writeBuf) {
- n, err := cn.c.Write(m.wrap())
- if err != nil {
- if n == 0 {
- err = &safeRetryError{Err: err}
- }
- panic(err)
- }
-}
-
-func (cn *conn) sendStartupPacket(m *writeBuf) error {
- _, err := cn.c.Write((m.wrap())[1:])
- return err
-}
-
-// Send a message of type typ to the server on the other end of cn. The
-// message should have no payload. This method does not use the scratch
-// buffer.
-func (cn *conn) sendSimpleMessage(typ byte) (err error) {
- _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'})
- return err
-}
-
-// saveMessage memorizes a message and its buffer in the conn struct.
-// recvMessage will then return these values on the next call to it. This
-// method is useful in cases where you have to see what the next message is
-// going to be (e.g. to see whether it's an error or not) but you can't handle
-// the message yourself.
-func (cn *conn) saveMessage(typ byte, buf *readBuf) {
- if cn.saveMessageType != 0 {
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected saveMessageType %d", cn.saveMessageType)
- }
- cn.saveMessageType = typ
- cn.saveMessageBuffer = *buf
-}
-
-// recvMessage receives any message from the backend, or returns an error if
-// a problem occurred while reading the message.
-func (cn *conn) recvMessage(r *readBuf) (byte, error) {
- // workaround for a QueryRow bug, see exec
- if cn.saveMessageType != 0 {
- t := cn.saveMessageType
- *r = cn.saveMessageBuffer
- cn.saveMessageType = 0
- cn.saveMessageBuffer = nil
- return t, nil
- }
-
- x := cn.scratch[:5]
- _, err := io.ReadFull(cn.buf, x)
- if err != nil {
- return 0, err
- }
-
- // read the type and length of the message that follows
- t := x[0]
- n := int(binary.BigEndian.Uint32(x[1:])) - 4
- var y []byte
- if n <= len(cn.scratch) {
- y = cn.scratch[:n]
- } else {
- y = make([]byte, n)
- }
- _, err = io.ReadFull(cn.buf, y)
- if err != nil {
- return 0, err
- }
- *r = y
- return t, nil
-}
-
-// recv receives a message from the backend, but if an error happened while
-// reading the message or the received message was an ErrorResponse, it panics.
-// NoticeResponses are ignored. This function should generally be used only
-// during the startup sequence.
-func (cn *conn) recv() (t byte, r *readBuf) {
- for {
- var err error
- r = &readBuf{}
- t, err = cn.recvMessage(r)
- if err != nil {
- panic(err)
- }
- switch t {
- case 'E':
- panic(parseError(r))
- case 'N':
- if n := cn.noticeHandler; n != nil {
- n(parseError(r))
- }
- case 'A':
- if n := cn.notificationHandler; n != nil {
- n(recvNotification(r))
- }
- default:
- return
- }
- }
-}
-
-// recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by
-// the caller to avoid an allocation.
-func (cn *conn) recv1Buf(r *readBuf) byte {
- for {
- t, err := cn.recvMessage(r)
- if err != nil {
- panic(err)
- }
-
- switch t {
- case 'A':
- if n := cn.notificationHandler; n != nil {
- n(recvNotification(r))
- }
- case 'N':
- if n := cn.noticeHandler; n != nil {
- n(parseError(r))
- }
- case 'S':
- cn.processParameterStatus(r)
- default:
- return t
- }
- }
-}
-
-// recv1 receives a message from the backend, panicking if an error occurs
-// while attempting to read it. All asynchronous messages are ignored, with
-// the exception of ErrorResponse.
-func (cn *conn) recv1() (t byte, r *readBuf) {
- r = &readBuf{}
- t = cn.recv1Buf(r)
- return t, r
-}
-
-func (cn *conn) ssl(o values) error {
- upgrade, err := ssl(o)
- if err != nil {
- return err
- }
-
- if upgrade == nil {
- // Nothing to do
- return nil
- }
-
- w := cn.writeBuf(0)
- w.int32(80877103)
- if err = cn.sendStartupPacket(w); err != nil {
- return err
- }
-
- b := cn.scratch[:1]
- _, err = io.ReadFull(cn.c, b)
- if err != nil {
- return err
- }
-
- if b[0] != 'S' {
- return ErrSSLNotSupported
- }
-
- cn.c, err = upgrade(cn.c)
- return err
-}
-
-// isDriverSetting returns true iff a setting is purely for configuring the
-// driver's options and should not be sent to the server in the connection
-// startup packet.
-func isDriverSetting(key string) bool {
- switch key {
- case "host", "port":
- return true
- case "password":
- return true
- case "sslmode", "sslcert", "sslkey", "sslrootcert", "sslinline", "sslsni":
- return true
- case "fallback_application_name":
- return true
- case "connect_timeout":
- return true
- case "disable_prepared_binary_result":
- return true
- case "binary_parameters":
- return true
- case "krbsrvname":
- return true
- case "krbspn":
- return true
- default:
- return false
- }
-}
-
-func (cn *conn) startup(o values) {
- w := cn.writeBuf(0)
- w.int32(196608)
- // Send the backend the name of the database we want to connect to, and the
- // user we want to connect as. Additionally, we send over any run-time
- // parameters potentially included in the connection string. If the server
- // doesn't recognize any of them, it will reply with an error.
- for k, v := range o {
- if isDriverSetting(k) {
- // skip options which can't be run-time parameters
- continue
- }
- // The protocol requires us to supply the database name as "database"
- // instead of "dbname".
- if k == "dbname" {
- k = "database"
- }
- w.string(k)
- w.string(v)
- }
- w.string("")
- if err := cn.sendStartupPacket(w); err != nil {
- panic(err)
- }
-
- for {
- t, r := cn.recv()
- switch t {
- case 'K':
- cn.processBackendKeyData(r)
- case 'S':
- cn.processParameterStatus(r)
- case 'R':
- cn.auth(r, o)
- case 'Z':
- cn.processReadyForQuery(r)
- return
- default:
- errorf("unknown response for startup: %q", t)
- }
- }
-}
-
-func (cn *conn) auth(r *readBuf, o values) {
- switch code := r.int32(); code {
- case 0:
- // OK
- case 3:
- w := cn.writeBuf('p')
- w.string(o["password"])
- cn.send(w)
-
- t, r := cn.recv()
- if t != 'R' {
- errorf("unexpected password response: %q", t)
- }
-
- if r.int32() != 0 {
- errorf("unexpected authentication response: %q", t)
- }
- case 5:
- s := string(r.next(4))
- w := cn.writeBuf('p')
- w.string("md5" + md5s(md5s(o["password"]+o["user"])+s))
- cn.send(w)
-
- t, r := cn.recv()
- if t != 'R' {
- errorf("unexpected password response: %q", t)
- }
-
- if r.int32() != 0 {
- errorf("unexpected authentication response: %q", t)
- }
- case 7: // GSSAPI, startup
- if newGss == nil {
- errorf("kerberos error: no GSSAPI provider registered (import github.com/lib/pq/auth/kerberos if you need Kerberos support)")
- }
- cli, err := newGss()
- if err != nil {
- errorf("kerberos error: %s", err.Error())
- }
-
- var token []byte
-
- if spn, ok := o["krbspn"]; ok {
- // Use the supplied SPN if provided..
- token, err = cli.GetInitTokenFromSpn(spn)
- } else {
- // Allow the kerberos service name to be overridden
- service := "postgres"
- if val, ok := o["krbsrvname"]; ok {
- service = val
- }
-
- token, err = cli.GetInitToken(o["host"], service)
- }
-
- if err != nil {
- errorf("failed to get Kerberos ticket: %q", err)
- }
-
- w := cn.writeBuf('p')
- w.bytes(token)
- cn.send(w)
-
- // Store for GSSAPI continue message
- cn.gss = cli
-
- case 8: // GSSAPI continue
-
- if cn.gss == nil {
- errorf("GSSAPI protocol error")
- }
-
- b := []byte(*r)
-
- done, tokOut, err := cn.gss.Continue(b)
- if err == nil && !done {
- w := cn.writeBuf('p')
- w.bytes(tokOut)
- cn.send(w)
- }
-
- // Errors fall through and read the more detailed message
- // from the server..
-
- case 10:
- sc := scram.NewClient(sha256.New, o["user"], o["password"])
- sc.Step(nil)
- if sc.Err() != nil {
- errorf("SCRAM-SHA-256 error: %s", sc.Err().Error())
- }
- scOut := sc.Out()
-
- w := cn.writeBuf('p')
- w.string("SCRAM-SHA-256")
- w.int32(len(scOut))
- w.bytes(scOut)
- cn.send(w)
-
- t, r := cn.recv()
- if t != 'R' {
- errorf("unexpected password response: %q", t)
- }
-
- if r.int32() != 11 {
- errorf("unexpected authentication response: %q", t)
- }
-
- nextStep := r.next(len(*r))
- sc.Step(nextStep)
- if sc.Err() != nil {
- errorf("SCRAM-SHA-256 error: %s", sc.Err().Error())
- }
-
- scOut = sc.Out()
- w = cn.writeBuf('p')
- w.bytes(scOut)
- cn.send(w)
-
- t, r = cn.recv()
- if t != 'R' {
- errorf("unexpected password response: %q", t)
- }
-
- if r.int32() != 12 {
- errorf("unexpected authentication response: %q", t)
- }
-
- nextStep = r.next(len(*r))
- sc.Step(nextStep)
- if sc.Err() != nil {
- errorf("SCRAM-SHA-256 error: %s", sc.Err().Error())
- }
-
- default:
- errorf("unknown authentication response: %d", code)
- }
-}
-
-type format int
-
-const formatText format = 0
-const formatBinary format = 1
-
-// One result-column format code with the value 1 (i.e. all binary).
-var colFmtDataAllBinary = []byte{0, 1, 0, 1}
-
-// No result-column format codes (i.e. all text).
-var colFmtDataAllText = []byte{0, 0}
-
-type stmt struct {
- cn *conn
- name string
- rowsHeader
- colFmtData []byte
- paramTyps []oid.Oid
- closed bool
-}
-
-func (st *stmt) Close() (err error) {
- if st.closed {
- return nil
- }
- if err := st.cn.err.get(); err != nil {
- return err
- }
- defer st.cn.errRecover(&err)
-
- w := st.cn.writeBuf('C')
- w.byte('S')
- w.string(st.name)
- st.cn.send(w)
-
- st.cn.send(st.cn.writeBuf('S'))
-
- t, _ := st.cn.recv1()
- if t != '3' {
- st.cn.err.set(driver.ErrBadConn)
- errorf("unexpected close response: %q", t)
- }
- st.closed = true
-
- t, r := st.cn.recv1()
- if t != 'Z' {
- st.cn.err.set(driver.ErrBadConn)
- errorf("expected ready for query, but got: %q", t)
- }
- st.cn.processReadyForQuery(r)
-
- return nil
-}
-
-func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) {
- return st.query(v)
-}
-
-func (st *stmt) query(v []driver.Value) (r *rows, err error) {
- if err := st.cn.err.get(); err != nil {
- return nil, err
- }
- defer st.cn.errRecover(&err)
-
- st.exec(v)
- return &rows{
- cn: st.cn,
- rowsHeader: st.rowsHeader,
- }, nil
-}
-
-func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) {
- if err := st.cn.err.get(); err != nil {
- return nil, err
- }
- defer st.cn.errRecover(&err)
-
- st.exec(v)
- res, _, err = st.cn.readExecuteResponse("simple query")
- return res, err
-}
-
-func (st *stmt) exec(v []driver.Value) {
- if len(v) >= 65536 {
- errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v))
- }
- if len(v) != len(st.paramTyps) {
- errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps))
- }
-
- cn := st.cn
- w := cn.writeBuf('B')
- w.byte(0) // unnamed portal
- w.string(st.name)
-
- if cn.binaryParameters {
- cn.sendBinaryParameters(w, v)
- } else {
- w.int16(0)
- w.int16(len(v))
- for i, x := range v {
- if x == nil {
- w.int32(-1)
- } else {
- b := encode(&cn.parameterStatus, x, st.paramTyps[i])
- w.int32(len(b))
- w.bytes(b)
- }
- }
- }
- w.bytes(st.colFmtData)
-
- w.next('E')
- w.byte(0)
- w.int32(0)
-
- w.next('S')
- cn.send(w)
-
- cn.readBindResponse()
- cn.postExecuteWorkaround()
-
-}
-
-func (st *stmt) NumInput() int {
- return len(st.paramTyps)
-}
-
-// parseComplete parses the "command tag" from a CommandComplete message, and
-// returns the number of rows affected (if applicable) and a string
-// identifying only the command that was executed, e.g. "ALTER TABLE". If the
-// command tag could not be parsed, parseComplete panics.
-func (cn *conn) parseComplete(commandTag string) (driver.Result, string) {
- commandsWithAffectedRows := []string{
- "SELECT ",
- // INSERT is handled below
- "UPDATE ",
- "DELETE ",
- "FETCH ",
- "MOVE ",
- "COPY ",
- }
-
- var affectedRows *string
- for _, tag := range commandsWithAffectedRows {
- if strings.HasPrefix(commandTag, tag) {
- t := commandTag[len(tag):]
- affectedRows = &t
- commandTag = tag[:len(tag)-1]
- break
- }
- }
- // INSERT also includes the oid of the inserted row in its command tag.
- // Oids in user tables are deprecated, and the oid is only returned when
- // exactly one row is inserted, so it's unlikely to be of value to any
- // real-world application and we can ignore it.
- if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") {
- parts := strings.Split(commandTag, " ")
- if len(parts) != 3 {
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected INSERT command tag %s", commandTag)
- }
- affectedRows = &parts[len(parts)-1]
- commandTag = "INSERT"
- }
- // There should be no affected rows attached to the tag, just return it
- if affectedRows == nil {
- return driver.RowsAffected(0), commandTag
- }
- n, err := strconv.ParseInt(*affectedRows, 10, 64)
- if err != nil {
- cn.err.set(driver.ErrBadConn)
- errorf("could not parse commandTag: %s", err)
- }
- return driver.RowsAffected(n), commandTag
-}
-
-type rowsHeader struct {
- colNames []string
- colTyps []fieldDesc
- colFmts []format
-}
-
-type rows struct {
- cn *conn
- finish func()
- rowsHeader
- done bool
- rb readBuf
- result driver.Result
- tag string
-
- next *rowsHeader
-}
-
-func (rs *rows) Close() error {
- if finish := rs.finish; finish != nil {
- defer finish()
- }
- // no need to look at cn.bad as Next() will
- for {
- err := rs.Next(nil)
- switch err {
- case nil:
- case io.EOF:
- // rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row
- // description, used with HasNextResultSet). We need to fetch messages until
- // we hit a 'Z', which is done by waiting for done to be set.
- if rs.done {
- return nil
- }
- default:
- return err
- }
- }
-}
-
-func (rs *rows) Columns() []string {
- return rs.colNames
-}
-
-func (rs *rows) Result() driver.Result {
- if rs.result == nil {
- return emptyRows
- }
- return rs.result
-}
-
-func (rs *rows) Tag() string {
- return rs.tag
-}
-
-func (rs *rows) Next(dest []driver.Value) (err error) {
- if rs.done {
- return io.EOF
- }
-
- conn := rs.cn
- if err := conn.err.getForNext(); err != nil {
- return err
- }
- defer conn.errRecover(&err)
-
- for {
- t := conn.recv1Buf(&rs.rb)
- switch t {
- case 'E':
- err = parseError(&rs.rb)
- case 'C', 'I':
- if t == 'C' {
- rs.result, rs.tag = conn.parseComplete(rs.rb.string())
- }
- continue
- case 'Z':
- conn.processReadyForQuery(&rs.rb)
- rs.done = true
- if err != nil {
- return err
- }
- return io.EOF
- case 'D':
- n := rs.rb.int16()
- if err != nil {
- conn.err.set(driver.ErrBadConn)
- errorf("unexpected DataRow after error %s", err)
- }
- if n < len(dest) {
- dest = dest[:n]
- }
- for i := range dest {
- l := rs.rb.int32()
- if l == -1 {
- dest[i] = nil
- continue
- }
- dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i])
- }
- return
- case 'T':
- next := parsePortalRowDescribe(&rs.rb)
- rs.next = &next
- return io.EOF
- default:
- errorf("unexpected message after execute: %q", t)
- }
- }
-}
-
-func (rs *rows) HasNextResultSet() bool {
- hasNext := rs.next != nil && !rs.done
- return hasNext
-}
-
-func (rs *rows) NextResultSet() error {
- if rs.next == nil {
- return io.EOF
- }
- rs.rowsHeader = *rs.next
- rs.next = nil
- return nil
-}
-
-// QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be
-// used as part of an SQL statement. For example:
-//
-// tblname := "my_table"
-// data := "my_data"
-// quoted := pq.QuoteIdentifier(tblname)
-// err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data)
-//
-// Any double quotes in name will be escaped. The quoted identifier will be
-// case sensitive when used in a query. If the input string contains a zero
-// byte, the result will be truncated immediately before it.
-func QuoteIdentifier(name string) string {
- end := strings.IndexRune(name, 0)
- if end > -1 {
- name = name[:end]
- }
- return `"` + strings.Replace(name, `"`, `""`, -1) + `"`
-}
-
-// BufferQuoteIdentifier satisfies the same purpose as QuoteIdentifier, but backed by a
-// byte buffer.
-func BufferQuoteIdentifier(name string, buffer *bytes.Buffer) {
- end := strings.IndexRune(name, 0)
- if end > -1 {
- name = name[:end]
- }
- buffer.WriteRune('"')
- buffer.WriteString(strings.Replace(name, `"`, `""`, -1))
- buffer.WriteRune('"')
-}
-
-// QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literal
-// to DDL and other statements that do not accept parameters) to be used as part
-// of an SQL statement. For example:
-//
-// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
-// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
-//
-// Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be
-// replaced by two backslashes (i.e. "\\") and the C-style escape identifier
-// that PostgreSQL provides ('E') will be prepended to the string.
-func QuoteLiteral(literal string) string {
- // This follows the PostgreSQL internal algorithm for handling quoted literals
- // from libpq, which can be found in the "PQEscapeStringInternal" function,
- // which is found in the libpq/fe-exec.c source file:
- // https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/interfaces/libpq/fe-exec.c
- //
- // substitute any single-quotes (') with two single-quotes ('')
- literal = strings.Replace(literal, `'`, `''`, -1)
- // determine if the string has any backslashes (\) in it.
- // if it does, replace any backslashes (\) with two backslashes (\\)
- // then, we need to wrap the entire string with a PostgreSQL
- // C-style escape. Per how "PQEscapeStringInternal" handles this case, we
- // also add a space before the "E"
- if strings.Contains(literal, `\`) {
- literal = strings.Replace(literal, `\`, `\\`, -1)
- literal = ` E'` + literal + `'`
- } else {
- // otherwise, we can just wrap the literal with a pair of single quotes
- literal = `'` + literal + `'`
- }
- return literal
-}
-
-func md5s(s string) string {
- h := md5.New()
- h.Write([]byte(s))
- return fmt.Sprintf("%x", h.Sum(nil))
-}
-
-func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) {
- // Do one pass over the parameters to see if we're going to send any of
- // them over in binary. If we are, create a paramFormats array at the
- // same time.
- var paramFormats []int
- for i, x := range args {
- _, ok := x.([]byte)
- if ok {
- if paramFormats == nil {
- paramFormats = make([]int, len(args))
- }
- paramFormats[i] = 1
- }
- }
- if paramFormats == nil {
- b.int16(0)
- } else {
- b.int16(len(paramFormats))
- for _, x := range paramFormats {
- b.int16(x)
- }
- }
-
- b.int16(len(args))
- for _, x := range args {
- if x == nil {
- b.int32(-1)
- } else {
- datum := binaryEncode(&cn.parameterStatus, x)
- b.int32(len(datum))
- b.bytes(datum)
- }
- }
-}
-
-func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) {
- if len(args) >= 65536 {
- errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args))
- }
-
- b := cn.writeBuf('P')
- b.byte(0) // unnamed statement
- b.string(query)
- b.int16(0)
-
- b.next('B')
- b.int16(0) // unnamed portal and statement
- cn.sendBinaryParameters(b, args)
- b.bytes(colFmtDataAllText)
-
- b.next('D')
- b.byte('P')
- b.byte(0) // unnamed portal
-
- b.next('E')
- b.byte(0)
- b.int32(0)
-
- b.next('S')
- cn.send(b)
-}
-
-func (cn *conn) processParameterStatus(r *readBuf) {
- var err error
-
- param := r.string()
- switch param {
- case "server_version":
- var major1 int
- var major2 int
- _, err = fmt.Sscanf(r.string(), "%d.%d", &major1, &major2)
- if err == nil {
- cn.parameterStatus.serverVersion = major1*10000 + major2*100
- }
-
- case "TimeZone":
- cn.parameterStatus.currentLocation, err = time.LoadLocation(r.string())
- if err != nil {
- cn.parameterStatus.currentLocation = nil
- }
-
- default:
- // ignore
- }
-}
-
-func (cn *conn) processReadyForQuery(r *readBuf) {
- cn.txnStatus = transactionStatus(r.byte())
-}
-
-func (cn *conn) readReadyForQuery() {
- t, r := cn.recv1()
- switch t {
- case 'Z':
- cn.processReadyForQuery(r)
- return
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected message %q; expected ReadyForQuery", t)
- }
-}
-
-func (cn *conn) processBackendKeyData(r *readBuf) {
- cn.processID = r.int32()
- cn.secretKey = r.int32()
-}
-
-func (cn *conn) readParseResponse() {
- t, r := cn.recv1()
- switch t {
- case '1':
- return
- case 'E':
- err := parseError(r)
- cn.readReadyForQuery()
- panic(err)
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected Parse response %q", t)
- }
-}
-
-func (cn *conn) readStatementDescribeResponse() (
- paramTyps []oid.Oid,
- colNames []string,
- colTyps []fieldDesc,
-) {
- for {
- t, r := cn.recv1()
- switch t {
- case 't':
- nparams := r.int16()
- paramTyps = make([]oid.Oid, nparams)
- for i := range paramTyps {
- paramTyps[i] = r.oid()
- }
- case 'n':
- return paramTyps, nil, nil
- case 'T':
- colNames, colTyps = parseStatementRowDescribe(r)
- return paramTyps, colNames, colTyps
- case 'E':
- err := parseError(r)
- cn.readReadyForQuery()
- panic(err)
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected Describe statement response %q", t)
- }
- }
-}
-
-func (cn *conn) readPortalDescribeResponse() rowsHeader {
- t, r := cn.recv1()
- switch t {
- case 'T':
- return parsePortalRowDescribe(r)
- case 'n':
- return rowsHeader{}
- case 'E':
- err := parseError(r)
- cn.readReadyForQuery()
- panic(err)
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected Describe response %q", t)
- }
- panic("not reached")
-}
-
-func (cn *conn) readBindResponse() {
- t, r := cn.recv1()
- switch t {
- case '2':
- return
- case 'E':
- err := parseError(r)
- cn.readReadyForQuery()
- panic(err)
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected Bind response %q", t)
- }
-}
-
-func (cn *conn) postExecuteWorkaround() {
- // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores
- // any errors from rows.Next, which masks errors that happened during the
- // execution of the query. To avoid the problem in common cases, we wait
- // here for one more message from the database. If it's not an error the
- // query will likely succeed (or perhaps has already, if it's a
- // CommandComplete), so we push the message into the conn struct; recv1
- // will return it as the next message for rows.Next or rows.Close.
- // However, if it's an error, we wait until ReadyForQuery and then return
- // the error to our caller.
- for {
- t, r := cn.recv1()
- switch t {
- case 'E':
- err := parseError(r)
- cn.readReadyForQuery()
- panic(err)
- case 'C', 'D', 'I':
- // the query didn't fail, but we can't process this message
- cn.saveMessage(t, r)
- return
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected message during extended query execution: %q", t)
- }
- }
-}
-
-// Only for Exec(), since we ignore the returned data
-func (cn *conn) readExecuteResponse(
- protocolState string,
-) (res driver.Result, commandTag string, err error) {
- for {
- t, r := cn.recv1()
- switch t {
- case 'C':
- if err != nil {
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected CommandComplete after error %s", err)
- }
- res, commandTag = cn.parseComplete(r.string())
- case 'Z':
- cn.processReadyForQuery(r)
- if res == nil && err == nil {
- err = errUnexpectedReady
- }
- return res, commandTag, err
- case 'E':
- err = parseError(r)
- case 'T', 'D', 'I':
- if err != nil {
- cn.err.set(driver.ErrBadConn)
- errorf("unexpected %q after error %s", t, err)
- }
- if t == 'I' {
- res = emptyRows
- }
- // ignore any results
- default:
- cn.err.set(driver.ErrBadConn)
- errorf("unknown %s response: %q", protocolState, t)
- }
- }
-}
-
-func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) {
- n := r.int16()
- colNames = make([]string, n)
- colTyps = make([]fieldDesc, n)
- for i := range colNames {
- colNames[i] = r.string()
- r.next(6)
- colTyps[i].OID = r.oid()
- colTyps[i].Len = r.int16()
- colTyps[i].Mod = r.int32()
- // format code not known when describing a statement; always 0
- r.next(2)
- }
- return
-}
-
-func parsePortalRowDescribe(r *readBuf) rowsHeader {
- n := r.int16()
- colNames := make([]string, n)
- colFmts := make([]format, n)
- colTyps := make([]fieldDesc, n)
- for i := range colNames {
- colNames[i] = r.string()
- r.next(6)
- colTyps[i].OID = r.oid()
- colTyps[i].Len = r.int16()
- colTyps[i].Mod = r.int32()
- colFmts[i] = format(r.int16())
- }
- return rowsHeader{
- colNames: colNames,
- colFmts: colFmts,
- colTyps: colTyps,
- }
-}
-
-// parseEnviron tries to mimic some of libpq's environment handling
-//
-// To ease testing, it does not directly reference os.Environ, but is
-// designed to accept its output.
-//
-// Environment-set connection information is intended to have a higher
-// precedence than a library default but lower than any explicitly
-// passed information (such as in the URL or connection string).
-func parseEnviron(env []string) (out map[string]string) {
- out = make(map[string]string)
-
- for _, v := range env {
- parts := strings.SplitN(v, "=", 2)
-
- accrue := func(keyname string) {
- out[keyname] = parts[1]
- }
- unsupported := func() {
- panic(fmt.Sprintf("setting %v not supported", parts[0]))
- }
-
- // The order of these is the same as is seen in the
- // PostgreSQL 9.1 manual. Unsupported but well-defined
- // keys cause a panic; these should be unset prior to
- // execution. Options which pq expects to be set to a
- // certain value are allowed, but must be set to that
- // value if present (they can, of course, be absent).
- switch parts[0] {
- case "PGHOST":
- accrue("host")
- case "PGHOSTADDR":
- unsupported()
- case "PGPORT":
- accrue("port")
- case "PGDATABASE":
- accrue("dbname")
- case "PGUSER":
- accrue("user")
- case "PGPASSWORD":
- accrue("password")
- case "PGSERVICE", "PGSERVICEFILE", "PGREALM":
- unsupported()
- case "PGOPTIONS":
- accrue("options")
- case "PGAPPNAME":
- accrue("application_name")
- case "PGSSLMODE":
- accrue("sslmode")
- case "PGSSLCERT":
- accrue("sslcert")
- case "PGSSLKEY":
- accrue("sslkey")
- case "PGSSLROOTCERT":
- accrue("sslrootcert")
- case "PGSSLSNI":
- accrue("sslsni")
- case "PGREQUIRESSL", "PGSSLCRL":
- unsupported()
- case "PGREQUIREPEER":
- unsupported()
- case "PGKRBSRVNAME", "PGGSSLIB":
- unsupported()
- case "PGCONNECT_TIMEOUT":
- accrue("connect_timeout")
- case "PGCLIENTENCODING":
- accrue("client_encoding")
- case "PGDATESTYLE":
- accrue("datestyle")
- case "PGTZ":
- accrue("timezone")
- case "PGGEQO":
- accrue("geqo")
- case "PGSYSCONFDIR", "PGLOCALEDIR":
- unsupported()
- }
- }
-
- return out
-}
-
-// isUTF8 returns whether name is a fuzzy variation of the string "UTF-8".
-func isUTF8(name string) bool {
- // Recognize all sorts of silly things as "UTF-8", like Postgres does
- s := strings.Map(alnumLowerASCII, name)
- return s == "utf8" || s == "unicode"
-}
-
-func alnumLowerASCII(ch rune) rune {
- if 'A' <= ch && ch <= 'Z' {
- return ch + ('a' - 'A')
- }
- if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' {
- return ch
- }
- return -1 // discard
-}
-
-// The database/sql/driver package says:
-// All Conn implementations should implement the following interfaces: Pinger, SessionResetter, and Validator.
-var _ driver.Pinger = &conn{}
-var _ driver.SessionResetter = &conn{}
-
-func (cn *conn) ResetSession(ctx context.Context) error {
- // Ensure bad connections are reported: From database/sql/driver:
- // If a connection is never returned to the connection pool but immediately reused, then
- // ResetSession is called prior to reuse but IsValid is not called.
- return cn.err.get()
-}
-
-func (cn *conn) IsValid() bool {
- return cn.err.get() == nil
-}
diff --git a/vendor/github.com/lib/pq/conn_go115.go b/vendor/github.com/lib/pq/conn_go115.go
deleted file mode 100644
index f4ef030..0000000
--- a/vendor/github.com/lib/pq/conn_go115.go
+++ /dev/null
@@ -1,8 +0,0 @@
-//go:build go1.15
-// +build go1.15
-
-package pq
-
-import "database/sql/driver"
-
-var _ driver.Validator = &conn{}
diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go
deleted file mode 100644
index 63d4ca6..0000000
--- a/vendor/github.com/lib/pq/conn_go18.go
+++ /dev/null
@@ -1,247 +0,0 @@
-package pq
-
-import (
- "context"
- "database/sql"
- "database/sql/driver"
- "fmt"
- "io"
- "io/ioutil"
- "time"
-)
-
-const (
- watchCancelDialContextTimeout = time.Second * 10
-)
-
-// Implement the "QueryerContext" interface
-func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
- list := make([]driver.Value, len(args))
- for i, nv := range args {
- list[i] = nv.Value
- }
- finish := cn.watchCancel(ctx)
- r, err := cn.query(query, list)
- if err != nil {
- if finish != nil {
- finish()
- }
- return nil, err
- }
- r.finish = finish
- return r, nil
-}
-
-// Implement the "ExecerContext" interface
-func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
- list := make([]driver.Value, len(args))
- for i, nv := range args {
- list[i] = nv.Value
- }
-
- if finish := cn.watchCancel(ctx); finish != nil {
- defer finish()
- }
-
- return cn.Exec(query, list)
-}
-
-// Implement the "ConnPrepareContext" interface
-func (cn *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
- if finish := cn.watchCancel(ctx); finish != nil {
- defer finish()
- }
- return cn.Prepare(query)
-}
-
-// Implement the "ConnBeginTx" interface
-func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
- var mode string
-
- switch sql.IsolationLevel(opts.Isolation) {
- case sql.LevelDefault:
- // Don't touch mode: use the server's default
- case sql.LevelReadUncommitted:
- mode = " ISOLATION LEVEL READ UNCOMMITTED"
- case sql.LevelReadCommitted:
- mode = " ISOLATION LEVEL READ COMMITTED"
- case sql.LevelRepeatableRead:
- mode = " ISOLATION LEVEL REPEATABLE READ"
- case sql.LevelSerializable:
- mode = " ISOLATION LEVEL SERIALIZABLE"
- default:
- return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation)
- }
-
- if opts.ReadOnly {
- mode += " READ ONLY"
- } else {
- mode += " READ WRITE"
- }
-
- tx, err := cn.begin(mode)
- if err != nil {
- return nil, err
- }
- cn.txnFinish = cn.watchCancel(ctx)
- return tx, nil
-}
-
-func (cn *conn) Ping(ctx context.Context) error {
- if finish := cn.watchCancel(ctx); finish != nil {
- defer finish()
- }
- rows, err := cn.simpleQuery(";")
- if err != nil {
- return driver.ErrBadConn // https://golang.org/pkg/database/sql/driver/#Pinger
- }
- rows.Close()
- return nil
-}
-
-func (cn *conn) watchCancel(ctx context.Context) func() {
- if done := ctx.Done(); done != nil {
- finished := make(chan struct{}, 1)
- go func() {
- select {
- case <-done:
- select {
- case finished <- struct{}{}:
- default:
- // We raced with the finish func, let the next query handle this with the
- // context.
- return
- }
-
- // Set the connection state to bad so it does not get reused.
- cn.err.set(ctx.Err())
-
- // At this point the function level context is canceled,
- // so it must not be used for the additional network
- // request to cancel the query.
- // Create a new context to pass into the dial.
- ctxCancel, cancel := context.WithTimeout(context.Background(), watchCancelDialContextTimeout)
- defer cancel()
-
- _ = cn.cancel(ctxCancel)
- case <-finished:
- }
- }()
- return func() {
- select {
- case <-finished:
- cn.err.set(ctx.Err())
- cn.Close()
- case finished <- struct{}{}:
- }
- }
- }
- return nil
-}
-
-func (cn *conn) cancel(ctx context.Context) error {
- // Create a new values map (copy). This makes sure the connection created
- // in this method cannot write to the same underlying data, which could
- // cause a concurrent map write panic. This is necessary because cancel
- // is called from a goroutine in watchCancel.
- o := make(values)
- for k, v := range cn.opts {
- o[k] = v
- }
-
- c, err := dial(ctx, cn.dialer, o)
- if err != nil {
- return err
- }
- defer c.Close()
-
- {
- can := conn{
- c: c,
- }
- err = can.ssl(o)
- if err != nil {
- return err
- }
-
- w := can.writeBuf(0)
- w.int32(80877102) // cancel request code
- w.int32(cn.processID)
- w.int32(cn.secretKey)
-
- if err := can.sendStartupPacket(w); err != nil {
- return err
- }
- }
-
- // Read until EOF to ensure that the server received the cancel.
- {
- _, err := io.Copy(ioutil.Discard, c)
- return err
- }
-}
-
-// Implement the "StmtQueryContext" interface
-func (st *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
- list := make([]driver.Value, len(args))
- for i, nv := range args {
- list[i] = nv.Value
- }
- finish := st.watchCancel(ctx)
- r, err := st.query(list)
- if err != nil {
- if finish != nil {
- finish()
- }
- return nil, err
- }
- r.finish = finish
- return r, nil
-}
-
-// Implement the "StmtExecContext" interface
-func (st *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
- list := make([]driver.Value, len(args))
- for i, nv := range args {
- list[i] = nv.Value
- }
-
- if finish := st.watchCancel(ctx); finish != nil {
- defer finish()
- }
-
- return st.Exec(list)
-}
-
-// watchCancel is implemented on stmt in order to not mark the parent conn as bad
-func (st *stmt) watchCancel(ctx context.Context) func() {
- if done := ctx.Done(); done != nil {
- finished := make(chan struct{})
- go func() {
- select {
- case <-done:
- // At this point the function level context is canceled,
- // so it must not be used for the additional network
- // request to cancel the query.
- // Create a new context to pass into the dial.
- ctxCancel, cancel := context.WithTimeout(context.Background(), watchCancelDialContextTimeout)
- defer cancel()
-
- _ = st.cancel(ctxCancel)
- finished <- struct{}{}
- case <-finished:
- }
- }()
- return func() {
- select {
- case <-finished:
- case finished <- struct{}{}:
- }
- }
- }
- return nil
-}
-
-func (st *stmt) cancel(ctx context.Context) error {
- return st.cn.cancel(ctx)
-}
diff --git a/vendor/github.com/lib/pq/connector.go b/vendor/github.com/lib/pq/connector.go
deleted file mode 100644
index 1145e12..0000000
--- a/vendor/github.com/lib/pq/connector.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package pq
-
-import (
- "context"
- "database/sql/driver"
- "errors"
- "fmt"
- "os"
- "strings"
-)
-
-// Connector represents a fixed configuration for the pq driver with a given
-// name. Connector satisfies the database/sql/driver Connector interface and
-// can be used to create any number of DB Conn's via the database/sql OpenDB
-// function.
-//
-// See https://golang.org/pkg/database/sql/driver/#Connector.
-// See https://golang.org/pkg/database/sql/#OpenDB.
-type Connector struct {
- opts values
- dialer Dialer
-}
-
-// Connect returns a connection to the database using the fixed configuration
-// of this Connector. Context is not used.
-func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) {
- return c.open(ctx)
-}
-
-// Dialer allows change the dialer used to open connections.
-func (c *Connector) Dialer(dialer Dialer) {
- c.dialer = dialer
-}
-
-// Driver returns the underlying driver of this Connector.
-func (c *Connector) Driver() driver.Driver {
- return &Driver{}
-}
-
-// NewConnector returns a connector for the pq driver in a fixed configuration
-// with the given dsn. The returned connector can be used to create any number
-// of equivalent Conn's. The returned connector is intended to be used with
-// database/sql.OpenDB.
-//
-// See https://golang.org/pkg/database/sql/driver/#Connector.
-// See https://golang.org/pkg/database/sql/#OpenDB.
-func NewConnector(dsn string) (*Connector, error) {
- var err error
- o := make(values)
-
- // A number of defaults are applied here, in this order:
- //
- // * Very low precedence defaults applied in every situation
- // * Environment variables
- // * Explicitly passed connection information
- o["host"] = "localhost"
- o["port"] = "5432"
- // N.B.: Extra float digits should be set to 3, but that breaks
- // Postgres 8.4 and older, where the max is 2.
- o["extra_float_digits"] = "2"
- for k, v := range parseEnviron(os.Environ()) {
- o[k] = v
- }
-
- if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
- dsn, err = ParseURL(dsn)
- if err != nil {
- return nil, err
- }
- }
-
- if err := parseOpts(dsn, o); err != nil {
- return nil, err
- }
-
- // Use the "fallback" application name if necessary
- if fallback, ok := o["fallback_application_name"]; ok {
- if _, ok := o["application_name"]; !ok {
- o["application_name"] = fallback
- }
- }
-
- // We can't work with any client_encoding other than UTF-8 currently.
- // However, we have historically allowed the user to set it to UTF-8
- // explicitly, and there's no reason to break such programs, so allow that.
- // Note that the "options" setting could also set client_encoding, but
- // parsing its value is not worth it. Instead, we always explicitly send
- // client_encoding as a separate run-time parameter, which should override
- // anything set in options.
- if enc, ok := o["client_encoding"]; ok && !isUTF8(enc) {
- return nil, errors.New("client_encoding must be absent or 'UTF8'")
- }
- o["client_encoding"] = "UTF8"
- // DateStyle needs a similar treatment.
- if datestyle, ok := o["datestyle"]; ok {
- if datestyle != "ISO, MDY" {
- return nil, fmt.Errorf("setting datestyle must be absent or %v; got %v", "ISO, MDY", datestyle)
- }
- } else {
- o["datestyle"] = "ISO, MDY"
- }
-
- // If a user is not provided by any other means, the last
- // resort is to use the current operating system provided user
- // name.
- if _, ok := o["user"]; !ok {
- u, err := userCurrent()
- if err != nil {
- return nil, err
- }
- o["user"] = u
- }
-
- // SSL is not necessary or supported over UNIX domain sockets
- if network, _ := network(o); network == "unix" {
- o["sslmode"] = "disable"
- }
-
- return &Connector{opts: o, dialer: defaultDialer{}}, nil
-}
diff --git a/vendor/github.com/lib/pq/copy.go b/vendor/github.com/lib/pq/copy.go
deleted file mode 100644
index a8f16b2..0000000
--- a/vendor/github.com/lib/pq/copy.go
+++ /dev/null
@@ -1,348 +0,0 @@
-package pq
-
-import (
- "bytes"
- "context"
- "database/sql/driver"
- "encoding/binary"
- "errors"
- "fmt"
- "sync"
-)
-
-var (
- errCopyInClosed = errors.New("pq: copyin statement has already been closed")
- errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY")
- errCopyToNotSupported = errors.New("pq: COPY TO is not supported")
- errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction")
- errCopyInProgress = errors.New("pq: COPY in progress")
-)
-
-// CopyIn creates a COPY FROM statement which can be prepared with
-// Tx.Prepare(). The target table should be visible in search_path.
-func CopyIn(table string, columns ...string) string {
- buffer := bytes.NewBufferString("COPY ")
- BufferQuoteIdentifier(table, buffer)
- buffer.WriteString(" (")
- makeStmt(buffer, columns...)
- return buffer.String()
-}
-
-// MakeStmt makes the stmt string for CopyIn and CopyInSchema.
-func makeStmt(buffer *bytes.Buffer, columns ...string) {
- //s := bytes.NewBufferString()
- for i, col := range columns {
- if i != 0 {
- buffer.WriteString(", ")
- }
- BufferQuoteIdentifier(col, buffer)
- }
- buffer.WriteString(") FROM STDIN")
-}
-
-// CopyInSchema creates a COPY FROM statement which can be prepared with
-// Tx.Prepare().
-func CopyInSchema(schema, table string, columns ...string) string {
- buffer := bytes.NewBufferString("COPY ")
- BufferQuoteIdentifier(schema, buffer)
- buffer.WriteRune('.')
- BufferQuoteIdentifier(table, buffer)
- buffer.WriteString(" (")
- makeStmt(buffer, columns...)
- return buffer.String()
-}
-
-type copyin struct {
- cn *conn
- buffer []byte
- rowData chan []byte
- done chan bool
-
- closed bool
-
- mu struct {
- sync.Mutex
- err error
- driver.Result
- }
-}
-
-const ciBufferSize = 64 * 1024
-
-// flush buffer before the buffer is filled up and needs reallocation
-const ciBufferFlushSize = 63 * 1024
-
-func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, err error) {
- if !cn.isInTransaction() {
- return nil, errCopyNotSupportedOutsideTxn
- }
-
- ci := &copyin{
- cn: cn,
- buffer: make([]byte, 0, ciBufferSize),
- rowData: make(chan []byte),
- done: make(chan bool, 1),
- }
- // add CopyData identifier + 4 bytes for message length
- ci.buffer = append(ci.buffer, 'd', 0, 0, 0, 0)
-
- b := cn.writeBuf('Q')
- b.string(q)
- cn.send(b)
-
-awaitCopyInResponse:
- for {
- t, r := cn.recv1()
- switch t {
- case 'G':
- if r.byte() != 0 {
- err = errBinaryCopyNotSupported
- break awaitCopyInResponse
- }
- go ci.resploop()
- return ci, nil
- case 'H':
- err = errCopyToNotSupported
- break awaitCopyInResponse
- case 'E':
- err = parseError(r)
- case 'Z':
- if err == nil {
- ci.setBad(driver.ErrBadConn)
- errorf("unexpected ReadyForQuery in response to COPY")
- }
- cn.processReadyForQuery(r)
- return nil, err
- default:
- ci.setBad(driver.ErrBadConn)
- errorf("unknown response for copy query: %q", t)
- }
- }
-
- // something went wrong, abort COPY before we return
- b = cn.writeBuf('f')
- b.string(err.Error())
- cn.send(b)
-
- for {
- t, r := cn.recv1()
- switch t {
- case 'c', 'C', 'E':
- case 'Z':
- // correctly aborted, we're done
- cn.processReadyForQuery(r)
- return nil, err
- default:
- ci.setBad(driver.ErrBadConn)
- errorf("unknown response for CopyFail: %q", t)
- }
- }
-}
-
-func (ci *copyin) flush(buf []byte) {
- // set message length (without message identifier)
- binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1))
-
- _, err := ci.cn.c.Write(buf)
- if err != nil {
- panic(err)
- }
-}
-
-func (ci *copyin) resploop() {
- for {
- var r readBuf
- t, err := ci.cn.recvMessage(&r)
- if err != nil {
- ci.setBad(driver.ErrBadConn)
- ci.setError(err)
- ci.done <- true
- return
- }
- switch t {
- case 'C':
- // complete
- res, _ := ci.cn.parseComplete(r.string())
- ci.setResult(res)
- case 'N':
- if n := ci.cn.noticeHandler; n != nil {
- n(parseError(&r))
- }
- case 'Z':
- ci.cn.processReadyForQuery(&r)
- ci.done <- true
- return
- case 'E':
- err := parseError(&r)
- ci.setError(err)
- default:
- ci.setBad(driver.ErrBadConn)
- ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t))
- ci.done <- true
- return
- }
- }
-}
-
-func (ci *copyin) setBad(err error) {
- ci.cn.err.set(err)
-}
-
-func (ci *copyin) getBad() error {
- return ci.cn.err.get()
-}
-
-func (ci *copyin) err() error {
- ci.mu.Lock()
- err := ci.mu.err
- ci.mu.Unlock()
- return err
-}
-
-// setError() sets ci.err if one has not been set already. Caller must not be
-// holding ci.Mutex.
-func (ci *copyin) setError(err error) {
- ci.mu.Lock()
- if ci.mu.err == nil {
- ci.mu.err = err
- }
- ci.mu.Unlock()
-}
-
-func (ci *copyin) setResult(result driver.Result) {
- ci.mu.Lock()
- ci.mu.Result = result
- ci.mu.Unlock()
-}
-
-func (ci *copyin) getResult() driver.Result {
- ci.mu.Lock()
- result := ci.mu.Result
- ci.mu.Unlock()
- if result == nil {
- return driver.RowsAffected(0)
- }
- return result
-}
-
-func (ci *copyin) NumInput() int {
- return -1
-}
-
-func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) {
- return nil, ErrNotSupported
-}
-
-// Exec inserts values into the COPY stream. The insert is asynchronous
-// and Exec can return errors from previous Exec calls to the same
-// COPY stmt.
-//
-// You need to call Exec(nil) to sync the COPY stream and to get any
-// errors from pending data, since Stmt.Close() doesn't return errors
-// to the user.
-func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) {
- if ci.closed {
- return nil, errCopyInClosed
- }
-
- if err := ci.getBad(); err != nil {
- return nil, err
- }
- defer ci.cn.errRecover(&err)
-
- if err := ci.err(); err != nil {
- return nil, err
- }
-
- if len(v) == 0 {
- if err := ci.Close(); err != nil {
- return driver.RowsAffected(0), err
- }
-
- return ci.getResult(), nil
- }
-
- numValues := len(v)
- for i, value := range v {
- ci.buffer = appendEncodedText(&ci.cn.parameterStatus, ci.buffer, value)
- if i < numValues-1 {
- ci.buffer = append(ci.buffer, '\t')
- }
- }
-
- ci.buffer = append(ci.buffer, '\n')
-
- if len(ci.buffer) > ciBufferFlushSize {
- ci.flush(ci.buffer)
- // reset buffer, keep bytes for message identifier and length
- ci.buffer = ci.buffer[:5]
- }
-
- return driver.RowsAffected(0), nil
-}
-
-// CopyData inserts a raw string into the COPY stream. The insert is
-// asynchronous and CopyData can return errors from previous CopyData calls to
-// the same COPY stmt.
-//
-// You need to call Exec(nil) to sync the COPY stream and to get any
-// errors from pending data, since Stmt.Close() doesn't return errors
-// to the user.
-func (ci *copyin) CopyData(ctx context.Context, line string) (r driver.Result, err error) {
- if ci.closed {
- return nil, errCopyInClosed
- }
-
- if finish := ci.cn.watchCancel(ctx); finish != nil {
- defer finish()
- }
-
- if err := ci.getBad(); err != nil {
- return nil, err
- }
- defer ci.cn.errRecover(&err)
-
- if err := ci.err(); err != nil {
- return nil, err
- }
-
- ci.buffer = append(ci.buffer, []byte(line)...)
- ci.buffer = append(ci.buffer, '\n')
-
- if len(ci.buffer) > ciBufferFlushSize {
- ci.flush(ci.buffer)
- // reset buffer, keep bytes for message identifier and length
- ci.buffer = ci.buffer[:5]
- }
-
- return driver.RowsAffected(0), nil
-}
-
-func (ci *copyin) Close() (err error) {
- if ci.closed { // Don't do anything, we're already closed
- return nil
- }
- ci.closed = true
-
- if err := ci.getBad(); err != nil {
- return err
- }
- defer ci.cn.errRecover(&err)
-
- if len(ci.buffer) > 0 {
- ci.flush(ci.buffer)
- }
- // Avoid touching the scratch buffer as resploop could be using it.
- err = ci.cn.sendSimpleMessage('c')
- if err != nil {
- return err
- }
-
- <-ci.done
- ci.cn.inCopy = false
-
- if err := ci.err(); err != nil {
- return err
- }
- return nil
-}
diff --git a/vendor/github.com/lib/pq/doc.go b/vendor/github.com/lib/pq/doc.go
deleted file mode 100644
index b571848..0000000
--- a/vendor/github.com/lib/pq/doc.go
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
-Package pq is a pure Go Postgres driver for the database/sql package.
-
-In most cases clients will use the database/sql package instead of
-using this package directly. For example:
-
- import (
- "database/sql"
-
- _ "github.com/lib/pq"
- )
-
- func main() {
- connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full"
- db, err := sql.Open("postgres", connStr)
- if err != nil {
- log.Fatal(err)
- }
-
- age := 21
- rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)
- …
- }
-
-You can also connect to a database using a URL. For example:
-
- connStr := "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full"
- db, err := sql.Open("postgres", connStr)
-
-
-Connection String Parameters
-
-
-Similarly to libpq, when establishing a connection using pq you are expected to
-supply a connection string containing zero or more parameters.
-A subset of the connection parameters supported by libpq are also supported by pq.
-Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem)
-directly in the connection string. This is different from libpq, which does not allow
-run-time parameters in the connection string, instead requiring you to supply
-them in the options parameter.
-
-For compatibility with libpq, the following special connection parameters are
-supported:
-
- * dbname - The name of the database to connect to
- * user - The user to sign in as
- * password - The user's password
- * host - The host to connect to. Values that start with / are for unix
- domain sockets. (default is localhost)
- * port - The port to bind to. (default is 5432)
- * sslmode - Whether or not to use SSL (default is require, this is not
- the default for libpq)
- * fallback_application_name - An application_name to fall back to if one isn't provided.
- * connect_timeout - Maximum wait for connection, in seconds. Zero or
- not specified means wait indefinitely.
- * sslcert - Cert file location. The file must contain PEM encoded data.
- * sslkey - Key file location. The file must contain PEM encoded data.
- * sslrootcert - The location of the root certificate file. The file
- must contain PEM encoded data.
-
-Valid values for sslmode are:
-
- * disable - No SSL
- * require - Always SSL (skip verification)
- * verify-ca - Always SSL (verify that the certificate presented by the
- server was signed by a trusted CA)
- * verify-full - Always SSL (verify that the certification presented by
- the server was signed by a trusted CA and the server host name
- matches the one in the certificate)
-
-See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
-for more information about connection string parameters.
-
-Use single quotes for values that contain whitespace:
-
- "user=pqgotest password='with spaces'"
-
-A backslash will escape the next character in values:
-
- "user=space\ man password='it\'s valid'"
-
-Note that the connection parameter client_encoding (which sets the
-text encoding for the connection) may be set but must be "UTF8",
-matching with the same rules as Postgres. It is an error to provide
-any other value.
-
-In addition to the parameters listed above, any run-time parameter that can be
-set at backend start time can be set in the connection string. For more
-information, see
-http://www.postgresql.org/docs/current/static/runtime-config.html.
-
-Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html
-supported by libpq are also supported by pq. If any of the environment
-variables not supported by pq are set, pq will panic during connection
-establishment. Environment variables have a lower precedence than explicitly
-provided connection parameters.
-
-The pgpass mechanism as described in http://www.postgresql.org/docs/current/static/libpq-pgpass.html
-is supported, but on Windows PGPASSFILE must be specified explicitly.
-
-
-Queries
-
-
-database/sql does not dictate any specific format for parameter
-markers in query strings, and pq uses the Postgres-native ordinal markers,
-as shown above. The same marker can be reused for the same parameter:
-
- rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1
- OR age BETWEEN $2 AND $2 + 3`, "orange", 64)
-
-pq does not support the LastInsertId() method of the Result type in database/sql.
-To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres
-RETURNING clause with a standard Query or QueryRow call:
-
- var userid int
- err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
- VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)
-
-For more details on RETURNING, see the Postgres documentation:
-
- http://www.postgresql.org/docs/current/static/sql-insert.html
- http://www.postgresql.org/docs/current/static/sql-update.html
- http://www.postgresql.org/docs/current/static/sql-delete.html
-
-For additional instructions on querying see the documentation for the database/sql package.
-
-
-Data Types
-
-
-Parameters pass through driver.DefaultParameterConverter before they are handled
-by this package. When the binary_parameters connection option is enabled,
-[]byte values are sent directly to the backend as data in binary format.
-
-This package returns the following types for values from the PostgreSQL backend:
-
- - integer types smallint, integer, and bigint are returned as int64
- - floating-point types real and double precision are returned as float64
- - character types char, varchar, and text are returned as string
- - temporal types date, time, timetz, timestamp, and timestamptz are
- returned as time.Time
- - the boolean type is returned as bool
- - the bytea type is returned as []byte
-
-All other types are returned directly from the backend as []byte values in text format.
-
-
-Errors
-
-
-pq may return errors of type *pq.Error which can be interrogated for error details:
-
- if err, ok := err.(*pq.Error); ok {
- fmt.Println("pq error:", err.Code.Name())
- }
-
-See the pq.Error type for details.
-
-
-Bulk imports
-
-You can perform bulk imports by preparing a statement returned by pq.CopyIn (or
-pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement
-handle can then be repeatedly "executed" to copy data into the target table.
-After all data has been processed you should call Exec() once with no arguments
-to flush all buffered data. Any call to Exec() might return an error which
-should be handled appropriately, but because of the internal buffering an error
-returned by Exec() might not be related to the data passed in the call that
-failed.
-
-CopyIn uses COPY FROM internally. It is not possible to COPY outside of an
-explicit transaction in pq.
-
-Usage example:
-
- txn, err := db.Begin()
- if err != nil {
- log.Fatal(err)
- }
-
- stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age"))
- if err != nil {
- log.Fatal(err)
- }
-
- for _, user := range users {
- _, err = stmt.Exec(user.Name, int64(user.Age))
- if err != nil {
- log.Fatal(err)
- }
- }
-
- _, err = stmt.Exec()
- if err != nil {
- log.Fatal(err)
- }
-
- err = stmt.Close()
- if err != nil {
- log.Fatal(err)
- }
-
- err = txn.Commit()
- if err != nil {
- log.Fatal(err)
- }
-
-
-Notifications
-
-
-PostgreSQL supports a simple publish/subscribe model over database
-connections. See http://www.postgresql.org/docs/current/static/sql-notify.html
-for more information about the general mechanism.
-
-To start listening for notifications, you first have to open a new connection
-to the database by calling NewListener. This connection can not be used for
-anything other than LISTEN / NOTIFY. Calling Listen will open a "notification
-channel"; once a notification channel is open, a notification generated on that
-channel will effect a send on the Listener.Notify channel. A notification
-channel will remain open until Unlisten is called, though connection loss might
-result in some notifications being lost. To solve this problem, Listener sends
-a nil pointer over the Notify channel any time the connection is re-established
-following a connection loss. The application can get information about the
-state of the underlying connection by setting an event callback in the call to
-NewListener.
-
-A single Listener can safely be used from concurrent goroutines, which means
-that there is often no need to create more than one Listener in your
-application. However, a Listener is always connected to a single database, so
-you will need to create a new Listener instance for every database you want to
-receive notifications in.
-
-The channel name in both Listen and Unlisten is case sensitive, and can contain
-any characters legal in an identifier (see
-http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
-for more information). Note that the channel name will be truncated to 63
-bytes by the PostgreSQL server.
-
-You can find a complete, working example of Listener usage at
-https://godoc.org/github.com/lib/pq/example/listen.
-
-
-Kerberos Support
-
-
-If you need support for Kerberos authentication, add the following to your main
-package:
-
- import "github.com/lib/pq/auth/kerberos"
-
- func init() {
- pq.RegisterGSSProvider(func() (pq.Gss, error) { return kerberos.NewGSS() })
- }
-
-This package is in a separate module so that users who don't need Kerberos
-don't have to download unnecessary dependencies.
-
-When imported, additional connection string parameters are supported:
-
- * krbsrvname - GSS (Kerberos) service name when constructing the
- SPN (default is `postgres`). This will be combined with the host
- to form the full SPN: `krbsrvname/host`.
- * krbspn - GSS (Kerberos) SPN. This takes priority over
- `krbsrvname` if present.
-*/
-package pq
diff --git a/vendor/github.com/lib/pq/encode.go b/vendor/github.com/lib/pq/encode.go
deleted file mode 100644
index bffe609..0000000
--- a/vendor/github.com/lib/pq/encode.go
+++ /dev/null
@@ -1,632 +0,0 @@
-package pq
-
-import (
- "bytes"
- "database/sql/driver"
- "encoding/binary"
- "encoding/hex"
- "errors"
- "fmt"
- "math"
- "regexp"
- "strconv"
- "strings"
- "sync"
- "time"
-
- "github.com/lib/pq/oid"
-)
-
-var time2400Regex = regexp.MustCompile(`^(24:00(?::00(?:\.0+)?)?)(?:[Z+-].*)?$`)
-
-func binaryEncode(parameterStatus *parameterStatus, x interface{}) []byte {
- switch v := x.(type) {
- case []byte:
- return v
- default:
- return encode(parameterStatus, x, oid.T_unknown)
- }
-}
-
-func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte {
- switch v := x.(type) {
- case int64:
- return strconv.AppendInt(nil, v, 10)
- case float64:
- return strconv.AppendFloat(nil, v, 'f', -1, 64)
- case []byte:
- if pgtypOid == oid.T_bytea {
- return encodeBytea(parameterStatus.serverVersion, v)
- }
-
- return v
- case string:
- if pgtypOid == oid.T_bytea {
- return encodeBytea(parameterStatus.serverVersion, []byte(v))
- }
-
- return []byte(v)
- case bool:
- return strconv.AppendBool(nil, v)
- case time.Time:
- return formatTs(v)
-
- default:
- errorf("encode: unknown type for %T", v)
- }
-
- panic("not reached")
-}
-
-func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} {
- switch f {
- case formatBinary:
- return binaryDecode(parameterStatus, s, typ)
- case formatText:
- return textDecode(parameterStatus, s, typ)
- default:
- panic("not reached")
- }
-}
-
-func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} {
- switch typ {
- case oid.T_bytea:
- return s
- case oid.T_int8:
- return int64(binary.BigEndian.Uint64(s))
- case oid.T_int4:
- return int64(int32(binary.BigEndian.Uint32(s)))
- case oid.T_int2:
- return int64(int16(binary.BigEndian.Uint16(s)))
- case oid.T_uuid:
- b, err := decodeUUIDBinary(s)
- if err != nil {
- panic(err)
- }
- return b
-
- default:
- errorf("don't know how to decode binary parameter of type %d", uint32(typ))
- }
-
- panic("not reached")
-}
-
-func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} {
- switch typ {
- case oid.T_char, oid.T_varchar, oid.T_text:
- return string(s)
- case oid.T_bytea:
- b, err := parseBytea(s)
- if err != nil {
- errorf("%s", err)
- }
- return b
- case oid.T_timestamptz:
- return parseTs(parameterStatus.currentLocation, string(s))
- case oid.T_timestamp, oid.T_date:
- return parseTs(nil, string(s))
- case oid.T_time:
- return mustParse("15:04:05", typ, s)
- case oid.T_timetz:
- return mustParse("15:04:05-07", typ, s)
- case oid.T_bool:
- return s[0] == 't'
- case oid.T_int8, oid.T_int4, oid.T_int2:
- i, err := strconv.ParseInt(string(s), 10, 64)
- if err != nil {
- errorf("%s", err)
- }
- return i
- case oid.T_float4, oid.T_float8:
- // We always use 64 bit parsing, regardless of whether the input text is for
- // a float4 or float8, because clients expect float64s for all float datatypes
- // and returning a 32-bit parsed float64 produces lossy results.
- f, err := strconv.ParseFloat(string(s), 64)
- if err != nil {
- errorf("%s", err)
- }
- return f
- }
-
- return s
-}
-
-// appendEncodedText encodes item in text format as required by COPY
-// and appends to buf
-func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte {
- switch v := x.(type) {
- case int64:
- return strconv.AppendInt(buf, v, 10)
- case float64:
- return strconv.AppendFloat(buf, v, 'f', -1, 64)
- case []byte:
- encodedBytea := encodeBytea(parameterStatus.serverVersion, v)
- return appendEscapedText(buf, string(encodedBytea))
- case string:
- return appendEscapedText(buf, v)
- case bool:
- return strconv.AppendBool(buf, v)
- case time.Time:
- return append(buf, formatTs(v)...)
- case nil:
- return append(buf, "\\N"...)
- default:
- errorf("encode: unknown type for %T", v)
- }
-
- panic("not reached")
-}
-
-func appendEscapedText(buf []byte, text string) []byte {
- escapeNeeded := false
- startPos := 0
- var c byte
-
- // check if we need to escape
- for i := 0; i < len(text); i++ {
- c = text[i]
- if c == '\\' || c == '\n' || c == '\r' || c == '\t' {
- escapeNeeded = true
- startPos = i
- break
- }
- }
- if !escapeNeeded {
- return append(buf, text...)
- }
-
- // copy till first char to escape, iterate the rest
- result := append(buf, text[:startPos]...)
- for i := startPos; i < len(text); i++ {
- c = text[i]
- switch c {
- case '\\':
- result = append(result, '\\', '\\')
- case '\n':
- result = append(result, '\\', 'n')
- case '\r':
- result = append(result, '\\', 'r')
- case '\t':
- result = append(result, '\\', 't')
- default:
- result = append(result, c)
- }
- }
- return result
-}
-
-func mustParse(f string, typ oid.Oid, s []byte) time.Time {
- str := string(s)
-
- // Check for a minute and second offset in the timezone.
- if typ == oid.T_timestamptz || typ == oid.T_timetz {
- for i := 3; i <= 6; i += 3 {
- if str[len(str)-i] == ':' {
- f += ":00"
- continue
- }
- break
- }
- }
-
- // Special case for 24:00 time.
- // Unfortunately, golang does not parse 24:00 as a proper time.
- // In this case, we want to try "round to the next day", to differentiate.
- // As such, we find if the 24:00 time matches at the beginning; if so,
- // we default it back to 00:00 but add a day later.
- var is2400Time bool
- switch typ {
- case oid.T_timetz, oid.T_time:
- if matches := time2400Regex.FindStringSubmatch(str); matches != nil {
- // Concatenate timezone information at the back.
- str = "00:00:00" + str[len(matches[1]):]
- is2400Time = true
- }
- }
- t, err := time.Parse(f, str)
- if err != nil {
- errorf("decode: %s", err)
- }
- if is2400Time {
- t = t.Add(24 * time.Hour)
- }
- return t
-}
-
-var errInvalidTimestamp = errors.New("invalid timestamp")
-
-type timestampParser struct {
- err error
-}
-
-func (p *timestampParser) expect(str string, char byte, pos int) {
- if p.err != nil {
- return
- }
- if pos+1 > len(str) {
- p.err = errInvalidTimestamp
- return
- }
- if c := str[pos]; c != char && p.err == nil {
- p.err = fmt.Errorf("expected '%v' at position %v; got '%v'", char, pos, c)
- }
-}
-
-func (p *timestampParser) mustAtoi(str string, begin int, end int) int {
- if p.err != nil {
- return 0
- }
- if begin < 0 || end < 0 || begin > end || end > len(str) {
- p.err = errInvalidTimestamp
- return 0
- }
- result, err := strconv.Atoi(str[begin:end])
- if err != nil {
- if p.err == nil {
- p.err = fmt.Errorf("expected number; got '%v'", str)
- }
- return 0
- }
- return result
-}
-
-// The location cache caches the time zones typically used by the client.
-type locationCache struct {
- cache map[int]*time.Location
- lock sync.Mutex
-}
-
-// All connections share the same list of timezones. Benchmarking shows that
-// about 5% speed could be gained by putting the cache in the connection and
-// losing the mutex, at the cost of a small amount of memory and a somewhat
-// significant increase in code complexity.
-var globalLocationCache = newLocationCache()
-
-func newLocationCache() *locationCache {
- return &locationCache{cache: make(map[int]*time.Location)}
-}
-
-// Returns the cached timezone for the specified offset, creating and caching
-// it if necessary.
-func (c *locationCache) getLocation(offset int) *time.Location {
- c.lock.Lock()
- defer c.lock.Unlock()
-
- location, ok := c.cache[offset]
- if !ok {
- location = time.FixedZone("", offset)
- c.cache[offset] = location
- }
-
- return location
-}
-
-var infinityTsEnabled = false
-var infinityTsNegative time.Time
-var infinityTsPositive time.Time
-
-const (
- infinityTsEnabledAlready = "pq: infinity timestamp enabled already"
- infinityTsNegativeMustBeSmaller = "pq: infinity timestamp: negative value must be smaller (before) than positive"
-)
-
-// EnableInfinityTs controls the handling of Postgres' "-infinity" and
-// "infinity" "timestamp"s.
-//
-// If EnableInfinityTs is not called, "-infinity" and "infinity" will return
-// []byte("-infinity") and []byte("infinity") respectively, and potentially
-// cause error "sql: Scan error on column index 0: unsupported driver -> Scan
-// pair: []uint8 -> *time.Time", when scanning into a time.Time value.
-//
-// Once EnableInfinityTs has been called, all connections created using this
-// driver will decode Postgres' "-infinity" and "infinity" for "timestamp",
-// "timestamp with time zone" and "date" types to the predefined minimum and
-// maximum times, respectively. When encoding time.Time values, any time which
-// equals or precedes the predefined minimum time will be encoded to
-// "-infinity". Any values at or past the maximum time will similarly be
-// encoded to "infinity".
-//
-// If EnableInfinityTs is called with negative >= positive, it will panic.
-// Calling EnableInfinityTs after a connection has been established results in
-// undefined behavior. If EnableInfinityTs is called more than once, it will
-// panic.
-func EnableInfinityTs(negative time.Time, positive time.Time) {
- if infinityTsEnabled {
- panic(infinityTsEnabledAlready)
- }
- if !negative.Before(positive) {
- panic(infinityTsNegativeMustBeSmaller)
- }
- infinityTsEnabled = true
- infinityTsNegative = negative
- infinityTsPositive = positive
-}
-
-/*
- * Testing might want to toggle infinityTsEnabled
- */
-func disableInfinityTs() {
- infinityTsEnabled = false
-}
-
-// This is a time function specific to the Postgres default DateStyle
-// setting ("ISO, MDY"), the only one we currently support. This
-// accounts for the discrepancies between the parsing available with
-// time.Parse and the Postgres date formatting quirks.
-func parseTs(currentLocation *time.Location, str string) interface{} {
- switch str {
- case "-infinity":
- if infinityTsEnabled {
- return infinityTsNegative
- }
- return []byte(str)
- case "infinity":
- if infinityTsEnabled {
- return infinityTsPositive
- }
- return []byte(str)
- }
- t, err := ParseTimestamp(currentLocation, str)
- if err != nil {
- panic(err)
- }
- return t
-}
-
-// ParseTimestamp parses Postgres' text format. It returns a time.Time in
-// currentLocation iff that time's offset agrees with the offset sent from the
-// Postgres server. Otherwise, ParseTimestamp returns a time.Time with the
-// fixed offset offset provided by the Postgres server.
-func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error) {
- p := timestampParser{}
-
- monSep := strings.IndexRune(str, '-')
- // this is Gregorian year, not ISO Year
- // In Gregorian system, the year 1 BC is followed by AD 1
- year := p.mustAtoi(str, 0, monSep)
- daySep := monSep + 3
- month := p.mustAtoi(str, monSep+1, daySep)
- p.expect(str, '-', daySep)
- timeSep := daySep + 3
- day := p.mustAtoi(str, daySep+1, timeSep)
-
- minLen := monSep + len("01-01") + 1
-
- isBC := strings.HasSuffix(str, " BC")
- if isBC {
- minLen += 3
- }
-
- var hour, minute, second int
- if len(str) > minLen {
- p.expect(str, ' ', timeSep)
- minSep := timeSep + 3
- p.expect(str, ':', minSep)
- hour = p.mustAtoi(str, timeSep+1, minSep)
- secSep := minSep + 3
- p.expect(str, ':', secSep)
- minute = p.mustAtoi(str, minSep+1, secSep)
- secEnd := secSep + 3
- second = p.mustAtoi(str, secSep+1, secEnd)
- }
- remainderIdx := monSep + len("01-01 00:00:00") + 1
- // Three optional (but ordered) sections follow: the
- // fractional seconds, the time zone offset, and the BC
- // designation. We set them up here and adjust the other
- // offsets if the preceding sections exist.
-
- nanoSec := 0
- tzOff := 0
-
- if remainderIdx < len(str) && str[remainderIdx] == '.' {
- fracStart := remainderIdx + 1
- fracOff := strings.IndexAny(str[fracStart:], "-+Z ")
- if fracOff < 0 {
- fracOff = len(str) - fracStart
- }
- fracSec := p.mustAtoi(str, fracStart, fracStart+fracOff)
- nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff))))
-
- remainderIdx += fracOff + 1
- }
- if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart] == '-' || str[tzStart] == '+') {
- // time zone separator is always '-' or '+' or 'Z' (UTC is +00)
- var tzSign int
- switch c := str[tzStart]; c {
- case '-':
- tzSign = -1
- case '+':
- tzSign = +1
- default:
- return time.Time{}, fmt.Errorf("expected '-' or '+' at position %v; got %v", tzStart, c)
- }
- tzHours := p.mustAtoi(str, tzStart+1, tzStart+3)
- remainderIdx += 3
- var tzMin, tzSec int
- if remainderIdx < len(str) && str[remainderIdx] == ':' {
- tzMin = p.mustAtoi(str, remainderIdx+1, remainderIdx+3)
- remainderIdx += 3
- }
- if remainderIdx < len(str) && str[remainderIdx] == ':' {
- tzSec = p.mustAtoi(str, remainderIdx+1, remainderIdx+3)
- remainderIdx += 3
- }
- tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec)
- } else if tzStart < len(str) && str[tzStart] == 'Z' {
- // time zone Z separator indicates UTC is +00
- remainderIdx += 1
- }
-
- var isoYear int
-
- if isBC {
- isoYear = 1 - year
- remainderIdx += 3
- } else {
- isoYear = year
- }
- if remainderIdx < len(str) {
- return time.Time{}, fmt.Errorf("expected end of input, got %v", str[remainderIdx:])
- }
- t := time.Date(isoYear, time.Month(month), day,
- hour, minute, second, nanoSec,
- globalLocationCache.getLocation(tzOff))
-
- if currentLocation != nil {
- // Set the location of the returned Time based on the session's
- // TimeZone value, but only if the local time zone database agrees with
- // the remote database on the offset.
- lt := t.In(currentLocation)
- _, newOff := lt.Zone()
- if newOff == tzOff {
- t = lt
- }
- }
-
- return t, p.err
-}
-
-// formatTs formats t into a format postgres understands.
-func formatTs(t time.Time) []byte {
- if infinityTsEnabled {
- // t <= -infinity : ! (t > -infinity)
- if !t.After(infinityTsNegative) {
- return []byte("-infinity")
- }
- // t >= infinity : ! (!t < infinity)
- if !t.Before(infinityTsPositive) {
- return []byte("infinity")
- }
- }
- return FormatTimestamp(t)
-}
-
-// FormatTimestamp formats t into Postgres' text format for timestamps.
-func FormatTimestamp(t time.Time) []byte {
- // Need to send dates before 0001 A.D. with " BC" suffix, instead of the
- // minus sign preferred by Go.
- // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on
- bc := false
- if t.Year() <= 0 {
- // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11"
- t = t.AddDate((-t.Year())*2+1, 0, 0)
- bc = true
- }
- b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00"))
-
- _, offset := t.Zone()
- offset %= 60
- if offset != 0 {
- // RFC3339Nano already printed the minus sign
- if offset < 0 {
- offset = -offset
- }
-
- b = append(b, ':')
- if offset < 10 {
- b = append(b, '0')
- }
- b = strconv.AppendInt(b, int64(offset), 10)
- }
-
- if bc {
- b = append(b, " BC"...)
- }
- return b
-}
-
-// Parse a bytea value received from the server. Both "hex" and the legacy
-// "escape" format are supported.
-func parseBytea(s []byte) (result []byte, err error) {
- if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) {
- // bytea_output = hex
- s = s[2:] // trim off leading "\\x"
- result = make([]byte, hex.DecodedLen(len(s)))
- _, err := hex.Decode(result, s)
- if err != nil {
- return nil, err
- }
- } else {
- // bytea_output = escape
- for len(s) > 0 {
- if s[0] == '\\' {
- // escaped '\\'
- if len(s) >= 2 && s[1] == '\\' {
- result = append(result, '\\')
- s = s[2:]
- continue
- }
-
- // '\\' followed by an octal number
- if len(s) < 4 {
- return nil, fmt.Errorf("invalid bytea sequence %v", s)
- }
- r, err := strconv.ParseUint(string(s[1:4]), 8, 8)
- if err != nil {
- return nil, fmt.Errorf("could not parse bytea value: %s", err.Error())
- }
- result = append(result, byte(r))
- s = s[4:]
- } else {
- // We hit an unescaped, raw byte. Try to read in as many as
- // possible in one go.
- i := bytes.IndexByte(s, '\\')
- if i == -1 {
- result = append(result, s...)
- break
- }
- result = append(result, s[:i]...)
- s = s[i:]
- }
- }
- }
-
- return result, nil
-}
-
-func encodeBytea(serverVersion int, v []byte) (result []byte) {
- if serverVersion >= 90000 {
- // Use the hex format if we know that the server supports it
- result = make([]byte, 2+hex.EncodedLen(len(v)))
- result[0] = '\\'
- result[1] = 'x'
- hex.Encode(result[2:], v)
- } else {
- // .. or resort to "escape"
- for _, b := range v {
- if b == '\\' {
- result = append(result, '\\', '\\')
- } else if b < 0x20 || b > 0x7e {
- result = append(result, []byte(fmt.Sprintf("\\%03o", b))...)
- } else {
- result = append(result, b)
- }
- }
- }
-
- return result
-}
-
-// NullTime represents a time.Time that may be null. NullTime implements the
-// sql.Scanner interface so it can be used as a scan destination, similar to
-// sql.NullString.
-type NullTime struct {
- Time time.Time
- Valid bool // Valid is true if Time is not NULL
-}
-
-// Scan implements the Scanner interface.
-func (nt *NullTime) Scan(value interface{}) error {
- nt.Time, nt.Valid = value.(time.Time)
- return nil
-}
-
-// Value implements the driver Valuer interface.
-func (nt NullTime) Value() (driver.Value, error) {
- if !nt.Valid {
- return nil, nil
- }
- return nt.Time, nil
-}
diff --git a/vendor/github.com/lib/pq/error.go b/vendor/github.com/lib/pq/error.go
deleted file mode 100644
index f67c5a5..0000000
--- a/vendor/github.com/lib/pq/error.go
+++ /dev/null
@@ -1,523 +0,0 @@
-package pq
-
-import (
- "database/sql/driver"
- "fmt"
- "io"
- "net"
- "runtime"
-)
-
-// Error severities
-const (
- Efatal = "FATAL"
- Epanic = "PANIC"
- Ewarning = "WARNING"
- Enotice = "NOTICE"
- Edebug = "DEBUG"
- Einfo = "INFO"
- Elog = "LOG"
-)
-
-// Error represents an error communicating with the server.
-//
-// See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields
-type Error struct {
- Severity string
- Code ErrorCode
- Message string
- Detail string
- Hint string
- Position string
- InternalPosition string
- InternalQuery string
- Where string
- Schema string
- Table string
- Column string
- DataTypeName string
- Constraint string
- File string
- Line string
- Routine string
-}
-
-// ErrorCode is a five-character error code.
-type ErrorCode string
-
-// Name returns a more human friendly rendering of the error code, namely the
-// "condition name".
-//
-// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for
-// details.
-func (ec ErrorCode) Name() string {
- return errorCodeNames[ec]
-}
-
-// ErrorClass is only the class part of an error code.
-type ErrorClass string
-
-// Name returns the condition name of an error class. It is equivalent to the
-// condition name of the "standard" error code (i.e. the one having the last
-// three characters "000").
-func (ec ErrorClass) Name() string {
- return errorCodeNames[ErrorCode(ec+"000")]
-}
-
-// Class returns the error class, e.g. "28".
-//
-// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for
-// details.
-func (ec ErrorCode) Class() ErrorClass {
- return ErrorClass(ec[0:2])
-}
-
-// errorCodeNames is a mapping between the five-character error codes and the
-// human readable "condition names". It is derived from the list at
-// http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html
-var errorCodeNames = map[ErrorCode]string{
- // Class 00 - Successful Completion
- "00000": "successful_completion",
- // Class 01 - Warning
- "01000": "warning",
- "0100C": "dynamic_result_sets_returned",
- "01008": "implicit_zero_bit_padding",
- "01003": "null_value_eliminated_in_set_function",
- "01007": "privilege_not_granted",
- "01006": "privilege_not_revoked",
- "01004": "string_data_right_truncation",
- "01P01": "deprecated_feature",
- // Class 02 - No Data (this is also a warning class per the SQL standard)
- "02000": "no_data",
- "02001": "no_additional_dynamic_result_sets_returned",
- // Class 03 - SQL Statement Not Yet Complete
- "03000": "sql_statement_not_yet_complete",
- // Class 08 - Connection Exception
- "08000": "connection_exception",
- "08003": "connection_does_not_exist",
- "08006": "connection_failure",
- "08001": "sqlclient_unable_to_establish_sqlconnection",
- "08004": "sqlserver_rejected_establishment_of_sqlconnection",
- "08007": "transaction_resolution_unknown",
- "08P01": "protocol_violation",
- // Class 09 - Triggered Action Exception
- "09000": "triggered_action_exception",
- // Class 0A - Feature Not Supported
- "0A000": "feature_not_supported",
- // Class 0B - Invalid Transaction Initiation
- "0B000": "invalid_transaction_initiation",
- // Class 0F - Locator Exception
- "0F000": "locator_exception",
- "0F001": "invalid_locator_specification",
- // Class 0L - Invalid Grantor
- "0L000": "invalid_grantor",
- "0LP01": "invalid_grant_operation",
- // Class 0P - Invalid Role Specification
- "0P000": "invalid_role_specification",
- // Class 0Z - Diagnostics Exception
- "0Z000": "diagnostics_exception",
- "0Z002": "stacked_diagnostics_accessed_without_active_handler",
- // Class 20 - Case Not Found
- "20000": "case_not_found",
- // Class 21 - Cardinality Violation
- "21000": "cardinality_violation",
- // Class 22 - Data Exception
- "22000": "data_exception",
- "2202E": "array_subscript_error",
- "22021": "character_not_in_repertoire",
- "22008": "datetime_field_overflow",
- "22012": "division_by_zero",
- "22005": "error_in_assignment",
- "2200B": "escape_character_conflict",
- "22022": "indicator_overflow",
- "22015": "interval_field_overflow",
- "2201E": "invalid_argument_for_logarithm",
- "22014": "invalid_argument_for_ntile_function",
- "22016": "invalid_argument_for_nth_value_function",
- "2201F": "invalid_argument_for_power_function",
- "2201G": "invalid_argument_for_width_bucket_function",
- "22018": "invalid_character_value_for_cast",
- "22007": "invalid_datetime_format",
- "22019": "invalid_escape_character",
- "2200D": "invalid_escape_octet",
- "22025": "invalid_escape_sequence",
- "22P06": "nonstandard_use_of_escape_character",
- "22010": "invalid_indicator_parameter_value",
- "22023": "invalid_parameter_value",
- "2201B": "invalid_regular_expression",
- "2201W": "invalid_row_count_in_limit_clause",
- "2201X": "invalid_row_count_in_result_offset_clause",
- "22009": "invalid_time_zone_displacement_value",
- "2200C": "invalid_use_of_escape_character",
- "2200G": "most_specific_type_mismatch",
- "22004": "null_value_not_allowed",
- "22002": "null_value_no_indicator_parameter",
- "22003": "numeric_value_out_of_range",
- "2200H": "sequence_generator_limit_exceeded",
- "22026": "string_data_length_mismatch",
- "22001": "string_data_right_truncation",
- "22011": "substring_error",
- "22027": "trim_error",
- "22024": "unterminated_c_string",
- "2200F": "zero_length_character_string",
- "22P01": "floating_point_exception",
- "22P02": "invalid_text_representation",
- "22P03": "invalid_binary_representation",
- "22P04": "bad_copy_file_format",
- "22P05": "untranslatable_character",
- "2200L": "not_an_xml_document",
- "2200M": "invalid_xml_document",
- "2200N": "invalid_xml_content",
- "2200S": "invalid_xml_comment",
- "2200T": "invalid_xml_processing_instruction",
- // Class 23 - Integrity Constraint Violation
- "23000": "integrity_constraint_violation",
- "23001": "restrict_violation",
- "23502": "not_null_violation",
- "23503": "foreign_key_violation",
- "23505": "unique_violation",
- "23514": "check_violation",
- "23P01": "exclusion_violation",
- // Class 24 - Invalid Cursor State
- "24000": "invalid_cursor_state",
- // Class 25 - Invalid Transaction State
- "25000": "invalid_transaction_state",
- "25001": "active_sql_transaction",
- "25002": "branch_transaction_already_active",
- "25008": "held_cursor_requires_same_isolation_level",
- "25003": "inappropriate_access_mode_for_branch_transaction",
- "25004": "inappropriate_isolation_level_for_branch_transaction",
- "25005": "no_active_sql_transaction_for_branch_transaction",
- "25006": "read_only_sql_transaction",
- "25007": "schema_and_data_statement_mixing_not_supported",
- "25P01": "no_active_sql_transaction",
- "25P02": "in_failed_sql_transaction",
- // Class 26 - Invalid SQL Statement Name
- "26000": "invalid_sql_statement_name",
- // Class 27 - Triggered Data Change Violation
- "27000": "triggered_data_change_violation",
- // Class 28 - Invalid Authorization Specification
- "28000": "invalid_authorization_specification",
- "28P01": "invalid_password",
- // Class 2B - Dependent Privilege Descriptors Still Exist
- "2B000": "dependent_privilege_descriptors_still_exist",
- "2BP01": "dependent_objects_still_exist",
- // Class 2D - Invalid Transaction Termination
- "2D000": "invalid_transaction_termination",
- // Class 2F - SQL Routine Exception
- "2F000": "sql_routine_exception",
- "2F005": "function_executed_no_return_statement",
- "2F002": "modifying_sql_data_not_permitted",
- "2F003": "prohibited_sql_statement_attempted",
- "2F004": "reading_sql_data_not_permitted",
- // Class 34 - Invalid Cursor Name
- "34000": "invalid_cursor_name",
- // Class 38 - External Routine Exception
- "38000": "external_routine_exception",
- "38001": "containing_sql_not_permitted",
- "38002": "modifying_sql_data_not_permitted",
- "38003": "prohibited_sql_statement_attempted",
- "38004": "reading_sql_data_not_permitted",
- // Class 39 - External Routine Invocation Exception
- "39000": "external_routine_invocation_exception",
- "39001": "invalid_sqlstate_returned",
- "39004": "null_value_not_allowed",
- "39P01": "trigger_protocol_violated",
- "39P02": "srf_protocol_violated",
- // Class 3B - Savepoint Exception
- "3B000": "savepoint_exception",
- "3B001": "invalid_savepoint_specification",
- // Class 3D - Invalid Catalog Name
- "3D000": "invalid_catalog_name",
- // Class 3F - Invalid Schema Name
- "3F000": "invalid_schema_name",
- // Class 40 - Transaction Rollback
- "40000": "transaction_rollback",
- "40002": "transaction_integrity_constraint_violation",
- "40001": "serialization_failure",
- "40003": "statement_completion_unknown",
- "40P01": "deadlock_detected",
- // Class 42 - Syntax Error or Access Rule Violation
- "42000": "syntax_error_or_access_rule_violation",
- "42601": "syntax_error",
- "42501": "insufficient_privilege",
- "42846": "cannot_coerce",
- "42803": "grouping_error",
- "42P20": "windowing_error",
- "42P19": "invalid_recursion",
- "42830": "invalid_foreign_key",
- "42602": "invalid_name",
- "42622": "name_too_long",
- "42939": "reserved_name",
- "42804": "datatype_mismatch",
- "42P18": "indeterminate_datatype",
- "42P21": "collation_mismatch",
- "42P22": "indeterminate_collation",
- "42809": "wrong_object_type",
- "42703": "undefined_column",
- "42883": "undefined_function",
- "42P01": "undefined_table",
- "42P02": "undefined_parameter",
- "42704": "undefined_object",
- "42701": "duplicate_column",
- "42P03": "duplicate_cursor",
- "42P04": "duplicate_database",
- "42723": "duplicate_function",
- "42P05": "duplicate_prepared_statement",
- "42P06": "duplicate_schema",
- "42P07": "duplicate_table",
- "42712": "duplicate_alias",
- "42710": "duplicate_object",
- "42702": "ambiguous_column",
- "42725": "ambiguous_function",
- "42P08": "ambiguous_parameter",
- "42P09": "ambiguous_alias",
- "42P10": "invalid_column_reference",
- "42611": "invalid_column_definition",
- "42P11": "invalid_cursor_definition",
- "42P12": "invalid_database_definition",
- "42P13": "invalid_function_definition",
- "42P14": "invalid_prepared_statement_definition",
- "42P15": "invalid_schema_definition",
- "42P16": "invalid_table_definition",
- "42P17": "invalid_object_definition",
- // Class 44 - WITH CHECK OPTION Violation
- "44000": "with_check_option_violation",
- // Class 53 - Insufficient Resources
- "53000": "insufficient_resources",
- "53100": "disk_full",
- "53200": "out_of_memory",
- "53300": "too_many_connections",
- "53400": "configuration_limit_exceeded",
- // Class 54 - Program Limit Exceeded
- "54000": "program_limit_exceeded",
- "54001": "statement_too_complex",
- "54011": "too_many_columns",
- "54023": "too_many_arguments",
- // Class 55 - Object Not In Prerequisite State
- "55000": "object_not_in_prerequisite_state",
- "55006": "object_in_use",
- "55P02": "cant_change_runtime_param",
- "55P03": "lock_not_available",
- // Class 57 - Operator Intervention
- "57000": "operator_intervention",
- "57014": "query_canceled",
- "57P01": "admin_shutdown",
- "57P02": "crash_shutdown",
- "57P03": "cannot_connect_now",
- "57P04": "database_dropped",
- // Class 58 - System Error (errors external to PostgreSQL itself)
- "58000": "system_error",
- "58030": "io_error",
- "58P01": "undefined_file",
- "58P02": "duplicate_file",
- // Class F0 - Configuration File Error
- "F0000": "config_file_error",
- "F0001": "lock_file_exists",
- // Class HV - Foreign Data Wrapper Error (SQL/MED)
- "HV000": "fdw_error",
- "HV005": "fdw_column_name_not_found",
- "HV002": "fdw_dynamic_parameter_value_needed",
- "HV010": "fdw_function_sequence_error",
- "HV021": "fdw_inconsistent_descriptor_information",
- "HV024": "fdw_invalid_attribute_value",
- "HV007": "fdw_invalid_column_name",
- "HV008": "fdw_invalid_column_number",
- "HV004": "fdw_invalid_data_type",
- "HV006": "fdw_invalid_data_type_descriptors",
- "HV091": "fdw_invalid_descriptor_field_identifier",
- "HV00B": "fdw_invalid_handle",
- "HV00C": "fdw_invalid_option_index",
- "HV00D": "fdw_invalid_option_name",
- "HV090": "fdw_invalid_string_length_or_buffer_length",
- "HV00A": "fdw_invalid_string_format",
- "HV009": "fdw_invalid_use_of_null_pointer",
- "HV014": "fdw_too_many_handles",
- "HV001": "fdw_out_of_memory",
- "HV00P": "fdw_no_schemas",
- "HV00J": "fdw_option_name_not_found",
- "HV00K": "fdw_reply_handle",
- "HV00Q": "fdw_schema_not_found",
- "HV00R": "fdw_table_not_found",
- "HV00L": "fdw_unable_to_create_execution",
- "HV00M": "fdw_unable_to_create_reply",
- "HV00N": "fdw_unable_to_establish_connection",
- // Class P0 - PL/pgSQL Error
- "P0000": "plpgsql_error",
- "P0001": "raise_exception",
- "P0002": "no_data_found",
- "P0003": "too_many_rows",
- // Class XX - Internal Error
- "XX000": "internal_error",
- "XX001": "data_corrupted",
- "XX002": "index_corrupted",
-}
-
-func parseError(r *readBuf) *Error {
- err := new(Error)
- for t := r.byte(); t != 0; t = r.byte() {
- msg := r.string()
- switch t {
- case 'S':
- err.Severity = msg
- case 'C':
- err.Code = ErrorCode(msg)
- case 'M':
- err.Message = msg
- case 'D':
- err.Detail = msg
- case 'H':
- err.Hint = msg
- case 'P':
- err.Position = msg
- case 'p':
- err.InternalPosition = msg
- case 'q':
- err.InternalQuery = msg
- case 'W':
- err.Where = msg
- case 's':
- err.Schema = msg
- case 't':
- err.Table = msg
- case 'c':
- err.Column = msg
- case 'd':
- err.DataTypeName = msg
- case 'n':
- err.Constraint = msg
- case 'F':
- err.File = msg
- case 'L':
- err.Line = msg
- case 'R':
- err.Routine = msg
- }
- }
- return err
-}
-
-// Fatal returns true if the Error Severity is fatal.
-func (err *Error) Fatal() bool {
- return err.Severity == Efatal
-}
-
-// SQLState returns the SQLState of the error.
-func (err *Error) SQLState() string {
- return string(err.Code)
-}
-
-// Get implements the legacy PGError interface. New code should use the fields
-// of the Error struct directly.
-func (err *Error) Get(k byte) (v string) {
- switch k {
- case 'S':
- return err.Severity
- case 'C':
- return string(err.Code)
- case 'M':
- return err.Message
- case 'D':
- return err.Detail
- case 'H':
- return err.Hint
- case 'P':
- return err.Position
- case 'p':
- return err.InternalPosition
- case 'q':
- return err.InternalQuery
- case 'W':
- return err.Where
- case 's':
- return err.Schema
- case 't':
- return err.Table
- case 'c':
- return err.Column
- case 'd':
- return err.DataTypeName
- case 'n':
- return err.Constraint
- case 'F':
- return err.File
- case 'L':
- return err.Line
- case 'R':
- return err.Routine
- }
- return ""
-}
-
-func (err *Error) Error() string {
- return "pq: " + err.Message
-}
-
-// PGError is an interface used by previous versions of pq. It is provided
-// only to support legacy code. New code should use the Error type.
-type PGError interface {
- Error() string
- Fatal() bool
- Get(k byte) (v string)
-}
-
-func errorf(s string, args ...interface{}) {
- panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...)))
-}
-
-// TODO(ainar-g) Rename to errorf after removing panics.
-func fmterrorf(s string, args ...interface{}) error {
- return fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))
-}
-
-func errRecoverNoErrBadConn(err *error) {
- e := recover()
- if e == nil {
- // Do nothing
- return
- }
- var ok bool
- *err, ok = e.(error)
- if !ok {
- *err = fmt.Errorf("pq: unexpected error: %#v", e)
- }
-}
-
-func (cn *conn) errRecover(err *error) {
- e := recover()
- switch v := e.(type) {
- case nil:
- // Do nothing
- case runtime.Error:
- cn.err.set(driver.ErrBadConn)
- panic(v)
- case *Error:
- if v.Fatal() {
- *err = driver.ErrBadConn
- } else {
- *err = v
- }
- case *net.OpError:
- cn.err.set(driver.ErrBadConn)
- *err = v
- case *safeRetryError:
- cn.err.set(driver.ErrBadConn)
- *err = driver.ErrBadConn
- case error:
- if v == io.EOF || v.Error() == "remote error: handshake failure" {
- *err = driver.ErrBadConn
- } else {
- *err = v
- }
-
- default:
- cn.err.set(driver.ErrBadConn)
- panic(fmt.Sprintf("unknown error: %#v", e))
- }
-
- // Any time we return ErrBadConn, we need to remember it since *Tx doesn't
- // mark the connection bad in database/sql.
- if *err == driver.ErrBadConn {
- cn.err.set(driver.ErrBadConn)
- }
-}
diff --git a/vendor/github.com/lib/pq/krb.go b/vendor/github.com/lib/pq/krb.go
deleted file mode 100644
index 408ec01..0000000
--- a/vendor/github.com/lib/pq/krb.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package pq
-
-// NewGSSFunc creates a GSS authentication provider, for use with
-// RegisterGSSProvider.
-type NewGSSFunc func() (GSS, error)
-
-var newGss NewGSSFunc
-
-// RegisterGSSProvider registers a GSS authentication provider. For example, if
-// you need to use Kerberos to authenticate with your server, add this to your
-// main package:
-//
-// import "github.com/lib/pq/auth/kerberos"
-//
-// func init() {
-// pq.RegisterGSSProvider(func() (pq.GSS, error) { return kerberos.NewGSS() })
-// }
-func RegisterGSSProvider(newGssArg NewGSSFunc) {
- newGss = newGssArg
-}
-
-// GSS provides GSSAPI authentication (e.g., Kerberos).
-type GSS interface {
- GetInitToken(host string, service string) ([]byte, error)
- GetInitTokenFromSpn(spn string) ([]byte, error)
- Continue(inToken []byte) (done bool, outToken []byte, err error)
-}
diff --git a/vendor/github.com/lib/pq/notice.go b/vendor/github.com/lib/pq/notice.go
deleted file mode 100644
index 70ad122..0000000
--- a/vendor/github.com/lib/pq/notice.go
+++ /dev/null
@@ -1,72 +0,0 @@
-//go:build go1.10
-// +build go1.10
-
-package pq
-
-import (
- "context"
- "database/sql/driver"
-)
-
-// NoticeHandler returns the notice handler on the given connection, if any. A
-// runtime panic occurs if c is not a pq connection. This is rarely used
-// directly, use ConnectorNoticeHandler and ConnectorWithNoticeHandler instead.
-func NoticeHandler(c driver.Conn) func(*Error) {
- return c.(*conn).noticeHandler
-}
-
-// SetNoticeHandler sets the given notice handler on the given connection. A
-// runtime panic occurs if c is not a pq connection. A nil handler may be used
-// to unset it. This is rarely used directly, use ConnectorNoticeHandler and
-// ConnectorWithNoticeHandler instead.
-//
-// Note: Notice handlers are executed synchronously by pq meaning commands
-// won't continue to be processed until the handler returns.
-func SetNoticeHandler(c driver.Conn, handler func(*Error)) {
- c.(*conn).noticeHandler = handler
-}
-
-// NoticeHandlerConnector wraps a regular connector and sets a notice handler
-// on it.
-type NoticeHandlerConnector struct {
- driver.Connector
- noticeHandler func(*Error)
-}
-
-// Connect calls the underlying connector's connect method and then sets the
-// notice handler.
-func (n *NoticeHandlerConnector) Connect(ctx context.Context) (driver.Conn, error) {
- c, err := n.Connector.Connect(ctx)
- if err == nil {
- SetNoticeHandler(c, n.noticeHandler)
- }
- return c, err
-}
-
-// ConnectorNoticeHandler returns the currently set notice handler, if any. If
-// the given connector is not a result of ConnectorWithNoticeHandler, nil is
-// returned.
-func ConnectorNoticeHandler(c driver.Connector) func(*Error) {
- if c, ok := c.(*NoticeHandlerConnector); ok {
- return c.noticeHandler
- }
- return nil
-}
-
-// ConnectorWithNoticeHandler creates or sets the given handler for the given
-// connector. If the given connector is a result of calling this function
-// previously, it is simply set on the given connector and returned. Otherwise,
-// this returns a new connector wrapping the given one and setting the notice
-// handler. A nil notice handler may be used to unset it.
-//
-// The returned connector is intended to be used with database/sql.OpenDB.
-//
-// Note: Notice handlers are executed synchronously by pq meaning commands
-// won't continue to be processed until the handler returns.
-func ConnectorWithNoticeHandler(c driver.Connector, handler func(*Error)) *NoticeHandlerConnector {
- if c, ok := c.(*NoticeHandlerConnector); ok {
- c.noticeHandler = handler
- return c
- }
- return &NoticeHandlerConnector{Connector: c, noticeHandler: handler}
-}
diff --git a/vendor/github.com/lib/pq/notify.go b/vendor/github.com/lib/pq/notify.go
deleted file mode 100644
index 5c421fd..0000000
--- a/vendor/github.com/lib/pq/notify.go
+++ /dev/null
@@ -1,858 +0,0 @@
-package pq
-
-// Package pq is a pure Go Postgres driver for the database/sql package.
-// This module contains support for Postgres LISTEN/NOTIFY.
-
-import (
- "context"
- "database/sql/driver"
- "errors"
- "fmt"
- "sync"
- "sync/atomic"
- "time"
-)
-
-// Notification represents a single notification from the database.
-type Notification struct {
- // Process ID (PID) of the notifying postgres backend.
- BePid int
- // Name of the channel the notification was sent on.
- Channel string
- // Payload, or the empty string if unspecified.
- Extra string
-}
-
-func recvNotification(r *readBuf) *Notification {
- bePid := r.int32()
- channel := r.string()
- extra := r.string()
-
- return &Notification{bePid, channel, extra}
-}
-
-// SetNotificationHandler sets the given notification handler on the given
-// connection. A runtime panic occurs if c is not a pq connection. A nil handler
-// may be used to unset it.
-//
-// Note: Notification handlers are executed synchronously by pq meaning commands
-// won't continue to be processed until the handler returns.
-func SetNotificationHandler(c driver.Conn, handler func(*Notification)) {
- c.(*conn).notificationHandler = handler
-}
-
-// NotificationHandlerConnector wraps a regular connector and sets a notification handler
-// on it.
-type NotificationHandlerConnector struct {
- driver.Connector
- notificationHandler func(*Notification)
-}
-
-// Connect calls the underlying connector's connect method and then sets the
-// notification handler.
-func (n *NotificationHandlerConnector) Connect(ctx context.Context) (driver.Conn, error) {
- c, err := n.Connector.Connect(ctx)
- if err == nil {
- SetNotificationHandler(c, n.notificationHandler)
- }
- return c, err
-}
-
-// ConnectorNotificationHandler returns the currently set notification handler, if any. If
-// the given connector is not a result of ConnectorWithNotificationHandler, nil is
-// returned.
-func ConnectorNotificationHandler(c driver.Connector) func(*Notification) {
- if c, ok := c.(*NotificationHandlerConnector); ok {
- return c.notificationHandler
- }
- return nil
-}
-
-// ConnectorWithNotificationHandler creates or sets the given handler for the given
-// connector. If the given connector is a result of calling this function
-// previously, it is simply set on the given connector and returned. Otherwise,
-// this returns a new connector wrapping the given one and setting the notification
-// handler. A nil notification handler may be used to unset it.
-//
-// The returned connector is intended to be used with database/sql.OpenDB.
-//
-// Note: Notification handlers are executed synchronously by pq meaning commands
-// won't continue to be processed until the handler returns.
-func ConnectorWithNotificationHandler(c driver.Connector, handler func(*Notification)) *NotificationHandlerConnector {
- if c, ok := c.(*NotificationHandlerConnector); ok {
- c.notificationHandler = handler
- return c
- }
- return &NotificationHandlerConnector{Connector: c, notificationHandler: handler}
-}
-
-const (
- connStateIdle int32 = iota
- connStateExpectResponse
- connStateExpectReadyForQuery
-)
-
-type message struct {
- typ byte
- err error
-}
-
-var errListenerConnClosed = errors.New("pq: ListenerConn has been closed")
-
-// ListenerConn is a low-level interface for waiting for notifications. You
-// should use Listener instead.
-type ListenerConn struct {
- // guards cn and err
- connectionLock sync.Mutex
- cn *conn
- err error
-
- connState int32
-
- // the sending goroutine will be holding this lock
- senderLock sync.Mutex
-
- notificationChan chan<- *Notification
-
- replyChan chan message
-}
-
-// NewListenerConn creates a new ListenerConn. Use NewListener instead.
-func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) {
- return newDialListenerConn(defaultDialer{}, name, notificationChan)
-}
-
-func newDialListenerConn(d Dialer, name string, c chan<- *Notification) (*ListenerConn, error) {
- cn, err := DialOpen(d, name)
- if err != nil {
- return nil, err
- }
-
- l := &ListenerConn{
- cn: cn.(*conn),
- notificationChan: c,
- connState: connStateIdle,
- replyChan: make(chan message, 2),
- }
-
- go l.listenerConnMain()
-
- return l, nil
-}
-
-// We can only allow one goroutine at a time to be running a query on the
-// connection for various reasons, so the goroutine sending on the connection
-// must be holding senderLock.
-//
-// Returns an error if an unrecoverable error has occurred and the ListenerConn
-// should be abandoned.
-func (l *ListenerConn) acquireSenderLock() error {
- // we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery
- l.senderLock.Lock()
-
- l.connectionLock.Lock()
- err := l.err
- l.connectionLock.Unlock()
- if err != nil {
- l.senderLock.Unlock()
- return err
- }
- return nil
-}
-
-func (l *ListenerConn) releaseSenderLock() {
- l.senderLock.Unlock()
-}
-
-// setState advances the protocol state to newState. Returns false if moving
-// to that state from the current state is not allowed.
-func (l *ListenerConn) setState(newState int32) bool {
- var expectedState int32
-
- switch newState {
- case connStateIdle:
- expectedState = connStateExpectReadyForQuery
- case connStateExpectResponse:
- expectedState = connStateIdle
- case connStateExpectReadyForQuery:
- expectedState = connStateExpectResponse
- default:
- panic(fmt.Sprintf("unexpected listenerConnState %d", newState))
- }
-
- return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState)
-}
-
-// Main logic is here: receive messages from the postgres backend, forward
-// notifications and query replies and keep the internal state in sync with the
-// protocol state. Returns when the connection has been lost, is about to go
-// away or should be discarded because we couldn't agree on the state with the
-// server backend.
-func (l *ListenerConn) listenerConnLoop() (err error) {
- defer errRecoverNoErrBadConn(&err)
-
- r := &readBuf{}
- for {
- t, err := l.cn.recvMessage(r)
- if err != nil {
- return err
- }
-
- switch t {
- case 'A':
- // recvNotification copies all the data so we don't need to worry
- // about the scratch buffer being overwritten.
- l.notificationChan <- recvNotification(r)
-
- case 'T', 'D':
- // only used by tests; ignore
-
- case 'E':
- // We might receive an ErrorResponse even when not in a query; it
- // is expected that the server will close the connection after
- // that, but we should make sure that the error we display is the
- // one from the stray ErrorResponse, not io.ErrUnexpectedEOF.
- if !l.setState(connStateExpectReadyForQuery) {
- return parseError(r)
- }
- l.replyChan <- message{t, parseError(r)}
-
- case 'C', 'I':
- if !l.setState(connStateExpectReadyForQuery) {
- // protocol out of sync
- return fmt.Errorf("unexpected CommandComplete")
- }
- // ExecSimpleQuery doesn't need to know about this message
-
- case 'Z':
- if !l.setState(connStateIdle) {
- // protocol out of sync
- return fmt.Errorf("unexpected ReadyForQuery")
- }
- l.replyChan <- message{t, nil}
-
- case 'S':
- // ignore
- case 'N':
- if n := l.cn.noticeHandler; n != nil {
- n(parseError(r))
- }
- default:
- return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t)
- }
- }
-}
-
-// This is the main routine for the goroutine receiving on the database
-// connection. Most of the main logic is in listenerConnLoop.
-func (l *ListenerConn) listenerConnMain() {
- err := l.listenerConnLoop()
-
- // listenerConnLoop terminated; we're done, but we still have to clean up.
- // Make sure nobody tries to start any new queries by making sure the err
- // pointer is set. It is important that we do not overwrite its value; a
- // connection could be closed by either this goroutine or one sending on
- // the connection -- whoever closes the connection is assumed to have the
- // more meaningful error message (as the other one will probably get
- // net.errClosed), so that goroutine sets the error we expose while the
- // other error is discarded. If the connection is lost while two
- // goroutines are operating on the socket, it probably doesn't matter which
- // error we expose so we don't try to do anything more complex.
- l.connectionLock.Lock()
- if l.err == nil {
- l.err = err
- }
- l.cn.Close()
- l.connectionLock.Unlock()
-
- // There might be a query in-flight; make sure nobody's waiting for a
- // response to it, since there's not going to be one.
- close(l.replyChan)
-
- // let the listener know we're done
- close(l.notificationChan)
-
- // this ListenerConn is done
-}
-
-// Listen sends a LISTEN query to the server. See ExecSimpleQuery.
-func (l *ListenerConn) Listen(channel string) (bool, error) {
- return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel))
-}
-
-// Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery.
-func (l *ListenerConn) Unlisten(channel string) (bool, error) {
- return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel))
-}
-
-// UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery.
-func (l *ListenerConn) UnlistenAll() (bool, error) {
- return l.ExecSimpleQuery("UNLISTEN *")
-}
-
-// Ping the remote server to make sure it's alive. Non-nil error means the
-// connection has failed and should be abandoned.
-func (l *ListenerConn) Ping() error {
- sent, err := l.ExecSimpleQuery("")
- if !sent {
- return err
- }
- if err != nil {
- // shouldn't happen
- panic(err)
- }
- return nil
-}
-
-// Attempt to send a query on the connection. Returns an error if sending the
-// query failed, and the caller should initiate closure of this connection.
-// The caller must be holding senderLock (see acquireSenderLock and
-// releaseSenderLock).
-func (l *ListenerConn) sendSimpleQuery(q string) (err error) {
- defer errRecoverNoErrBadConn(&err)
-
- // must set connection state before sending the query
- if !l.setState(connStateExpectResponse) {
- panic("two queries running at the same time")
- }
-
- // Can't use l.cn.writeBuf here because it uses the scratch buffer which
- // might get overwritten by listenerConnLoop.
- b := &writeBuf{
- buf: []byte("Q\x00\x00\x00\x00"),
- pos: 1,
- }
- b.string(q)
- l.cn.send(b)
-
- return nil
-}
-
-// ExecSimpleQuery executes a "simple query" (i.e. one with no bindable
-// parameters) on the connection. The possible return values are:
-// 1) "executed" is true; the query was executed to completion on the
-// database server. If the query failed, err will be set to the error
-// returned by the database, otherwise err will be nil.
-// 2) If "executed" is false, the query could not be executed on the remote
-// server. err will be non-nil.
-//
-// After a call to ExecSimpleQuery has returned an executed=false value, the
-// connection has either been closed or will be closed shortly thereafter, and
-// all subsequently executed queries will return an error.
-func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) {
- if err = l.acquireSenderLock(); err != nil {
- return false, err
- }
- defer l.releaseSenderLock()
-
- err = l.sendSimpleQuery(q)
- if err != nil {
- // We can't know what state the protocol is in, so we need to abandon
- // this connection.
- l.connectionLock.Lock()
- // Set the error pointer if it hasn't been set already; see
- // listenerConnMain.
- if l.err == nil {
- l.err = err
- }
- l.connectionLock.Unlock()
- l.cn.c.Close()
- return false, err
- }
-
- // now we just wait for a reply..
- for {
- m, ok := <-l.replyChan
- if !ok {
- // We lost the connection to server, don't bother waiting for a
- // a response. err should have been set already.
- l.connectionLock.Lock()
- err := l.err
- l.connectionLock.Unlock()
- return false, err
- }
- switch m.typ {
- case 'Z':
- // sanity check
- if m.err != nil {
- panic("m.err != nil")
- }
- // done; err might or might not be set
- return true, err
-
- case 'E':
- // sanity check
- if m.err == nil {
- panic("m.err == nil")
- }
- // server responded with an error; ReadyForQuery to follow
- err = m.err
-
- default:
- return false, fmt.Errorf("unknown response for simple query: %q", m.typ)
- }
- }
-}
-
-// Close closes the connection.
-func (l *ListenerConn) Close() error {
- l.connectionLock.Lock()
- if l.err != nil {
- l.connectionLock.Unlock()
- return errListenerConnClosed
- }
- l.err = errListenerConnClosed
- l.connectionLock.Unlock()
- // We can't send anything on the connection without holding senderLock.
- // Simply close the net.Conn to wake up everyone operating on it.
- return l.cn.c.Close()
-}
-
-// Err returns the reason the connection was closed. It is not safe to call
-// this function until l.Notify has been closed.
-func (l *ListenerConn) Err() error {
- return l.err
-}
-
-var errListenerClosed = errors.New("pq: Listener has been closed")
-
-// ErrChannelAlreadyOpen is returned from Listen when a channel is already
-// open.
-var ErrChannelAlreadyOpen = errors.New("pq: channel is already open")
-
-// ErrChannelNotOpen is returned from Unlisten when a channel is not open.
-var ErrChannelNotOpen = errors.New("pq: channel is not open")
-
-// ListenerEventType is an enumeration of listener event types.
-type ListenerEventType int
-
-const (
- // ListenerEventConnected is emitted only when the database connection
- // has been initially initialized. The err argument of the callback
- // will always be nil.
- ListenerEventConnected ListenerEventType = iota
-
- // ListenerEventDisconnected is emitted after a database connection has
- // been lost, either because of an error or because Close has been
- // called. The err argument will be set to the reason the database
- // connection was lost.
- ListenerEventDisconnected
-
- // ListenerEventReconnected is emitted after a database connection has
- // been re-established after connection loss. The err argument of the
- // callback will always be nil. After this event has been emitted, a
- // nil pq.Notification is sent on the Listener.Notify channel.
- ListenerEventReconnected
-
- // ListenerEventConnectionAttemptFailed is emitted after a connection
- // to the database was attempted, but failed. The err argument will be
- // set to an error describing why the connection attempt did not
- // succeed.
- ListenerEventConnectionAttemptFailed
-)
-
-// EventCallbackType is the event callback type. See also ListenerEventType
-// constants' documentation.
-type EventCallbackType func(event ListenerEventType, err error)
-
-// Listener provides an interface for listening to notifications from a
-// PostgreSQL database. For general usage information, see section
-// "Notifications".
-//
-// Listener can safely be used from concurrently running goroutines.
-type Listener struct {
- // Channel for receiving notifications from the database. In some cases a
- // nil value will be sent. See section "Notifications" above.
- Notify chan *Notification
-
- name string
- minReconnectInterval time.Duration
- maxReconnectInterval time.Duration
- dialer Dialer
- eventCallback EventCallbackType
-
- lock sync.Mutex
- isClosed bool
- reconnectCond *sync.Cond
- cn *ListenerConn
- connNotificationChan <-chan *Notification
- channels map[string]struct{}
-}
-
-// NewListener creates a new database connection dedicated to LISTEN / NOTIFY.
-//
-// name should be set to a connection string to be used to establish the
-// database connection (see section "Connection String Parameters" above).
-//
-// minReconnectInterval controls the duration to wait before trying to
-// re-establish the database connection after connection loss. After each
-// consecutive failure this interval is doubled, until maxReconnectInterval is
-// reached. Successfully completing the connection establishment procedure
-// resets the interval back to minReconnectInterval.
-//
-// The last parameter eventCallback can be set to a function which will be
-// called by the Listener when the state of the underlying database connection
-// changes. This callback will be called by the goroutine which dispatches the
-// notifications over the Notify channel, so you should try to avoid doing
-// potentially time-consuming operations from the callback.
-func NewListener(name string,
- minReconnectInterval time.Duration,
- maxReconnectInterval time.Duration,
- eventCallback EventCallbackType) *Listener {
- return NewDialListener(defaultDialer{}, name, minReconnectInterval, maxReconnectInterval, eventCallback)
-}
-
-// NewDialListener is like NewListener but it takes a Dialer.
-func NewDialListener(d Dialer,
- name string,
- minReconnectInterval time.Duration,
- maxReconnectInterval time.Duration,
- eventCallback EventCallbackType) *Listener {
-
- l := &Listener{
- name: name,
- minReconnectInterval: minReconnectInterval,
- maxReconnectInterval: maxReconnectInterval,
- dialer: d,
- eventCallback: eventCallback,
-
- channels: make(map[string]struct{}),
-
- Notify: make(chan *Notification, 32),
- }
- l.reconnectCond = sync.NewCond(&l.lock)
-
- go l.listenerMain()
-
- return l
-}
-
-// NotificationChannel returns the notification channel for this listener.
-// This is the same channel as Notify, and will not be recreated during the
-// life time of the Listener.
-func (l *Listener) NotificationChannel() <-chan *Notification {
- return l.Notify
-}
-
-// Listen starts listening for notifications on a channel. Calls to this
-// function will block until an acknowledgement has been received from the
-// server. Note that Listener automatically re-establishes the connection
-// after connection loss, so this function may block indefinitely if the
-// connection can not be re-established.
-//
-// Listen will only fail in three conditions:
-// 1) The channel is already open. The returned error will be
-// ErrChannelAlreadyOpen.
-// 2) The query was executed on the remote server, but PostgreSQL returned an
-// error message in response to the query. The returned error will be a
-// pq.Error containing the information the server supplied.
-// 3) Close is called on the Listener before the request could be completed.
-//
-// The channel name is case-sensitive.
-func (l *Listener) Listen(channel string) error {
- l.lock.Lock()
- defer l.lock.Unlock()
-
- if l.isClosed {
- return errListenerClosed
- }
-
- // The server allows you to issue a LISTEN on a channel which is already
- // open, but it seems useful to be able to detect this case to spot for
- // mistakes in application logic. If the application genuinely does't
- // care, it can check the exported error and ignore it.
- _, exists := l.channels[channel]
- if exists {
- return ErrChannelAlreadyOpen
- }
-
- if l.cn != nil {
- // If gotResponse is true but error is set, the query was executed on
- // the remote server, but resulted in an error. This should be
- // relatively rare, so it's fine if we just pass the error to our
- // caller. However, if gotResponse is false, we could not complete the
- // query on the remote server and our underlying connection is about
- // to go away, so we only add relname to l.channels, and wait for
- // resync() to take care of the rest.
- gotResponse, err := l.cn.Listen(channel)
- if gotResponse && err != nil {
- return err
- }
- }
-
- l.channels[channel] = struct{}{}
- for l.cn == nil {
- l.reconnectCond.Wait()
- // we let go of the mutex for a while
- if l.isClosed {
- return errListenerClosed
- }
- }
-
- return nil
-}
-
-// Unlisten removes a channel from the Listener's channel list. Returns
-// ErrChannelNotOpen if the Listener is not listening on the specified channel.
-// Returns immediately with no error if there is no connection. Note that you
-// might still get notifications for this channel even after Unlisten has
-// returned.
-//
-// The channel name is case-sensitive.
-func (l *Listener) Unlisten(channel string) error {
- l.lock.Lock()
- defer l.lock.Unlock()
-
- if l.isClosed {
- return errListenerClosed
- }
-
- // Similarly to LISTEN, this is not an error in Postgres, but it seems
- // useful to distinguish from the normal conditions.
- _, exists := l.channels[channel]
- if !exists {
- return ErrChannelNotOpen
- }
-
- if l.cn != nil {
- // Similarly to Listen (see comment in that function), the caller
- // should only be bothered with an error if it came from the backend as
- // a response to our query.
- gotResponse, err := l.cn.Unlisten(channel)
- if gotResponse && err != nil {
- return err
- }
- }
-
- // Don't bother waiting for resync if there's no connection.
- delete(l.channels, channel)
- return nil
-}
-
-// UnlistenAll removes all channels from the Listener's channel list. Returns
-// immediately with no error if there is no connection. Note that you might
-// still get notifications for any of the deleted channels even after
-// UnlistenAll has returned.
-func (l *Listener) UnlistenAll() error {
- l.lock.Lock()
- defer l.lock.Unlock()
-
- if l.isClosed {
- return errListenerClosed
- }
-
- if l.cn != nil {
- // Similarly to Listen (see comment in that function), the caller
- // should only be bothered with an error if it came from the backend as
- // a response to our query.
- gotResponse, err := l.cn.UnlistenAll()
- if gotResponse && err != nil {
- return err
- }
- }
-
- // Don't bother waiting for resync if there's no connection.
- l.channels = make(map[string]struct{})
- return nil
-}
-
-// Ping the remote server to make sure it's alive. Non-nil return value means
-// that there is no active connection.
-func (l *Listener) Ping() error {
- l.lock.Lock()
- defer l.lock.Unlock()
-
- if l.isClosed {
- return errListenerClosed
- }
- if l.cn == nil {
- return errors.New("no connection")
- }
-
- return l.cn.Ping()
-}
-
-// Clean up after losing the server connection. Returns l.cn.Err(), which
-// should have the reason the connection was lost.
-func (l *Listener) disconnectCleanup() error {
- l.lock.Lock()
- defer l.lock.Unlock()
-
- // sanity check; can't look at Err() until the channel has been closed
- select {
- case _, ok := <-l.connNotificationChan:
- if ok {
- panic("connNotificationChan not closed")
- }
- default:
- panic("connNotificationChan not closed")
- }
-
- err := l.cn.Err()
- l.cn.Close()
- l.cn = nil
- return err
-}
-
-// Synchronize the list of channels we want to be listening on with the server
-// after the connection has been established.
-func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error {
- doneChan := make(chan error)
- go func(notificationChan <-chan *Notification) {
- for channel := range l.channels {
- // If we got a response, return that error to our caller as it's
- // going to be more descriptive than cn.Err().
- gotResponse, err := cn.Listen(channel)
- if gotResponse && err != nil {
- doneChan <- err
- return
- }
-
- // If we couldn't reach the server, wait for notificationChan to
- // close and then return the error message from the connection, as
- // per ListenerConn's interface.
- if err != nil {
- for range notificationChan {
- }
- doneChan <- cn.Err()
- return
- }
- }
- doneChan <- nil
- }(notificationChan)
-
- // Ignore notifications while synchronization is going on to avoid
- // deadlocks. We have to send a nil notification over Notify anyway as
- // we can't possibly know which notifications (if any) were lost while
- // the connection was down, so there's no reason to try and process
- // these messages at all.
- for {
- select {
- case _, ok := <-notificationChan:
- if !ok {
- notificationChan = nil
- }
-
- case err := <-doneChan:
- return err
- }
- }
-}
-
-// caller should NOT be holding l.lock
-func (l *Listener) closed() bool {
- l.lock.Lock()
- defer l.lock.Unlock()
-
- return l.isClosed
-}
-
-func (l *Listener) connect() error {
- notificationChan := make(chan *Notification, 32)
- cn, err := newDialListenerConn(l.dialer, l.name, notificationChan)
- if err != nil {
- return err
- }
-
- l.lock.Lock()
- defer l.lock.Unlock()
-
- err = l.resync(cn, notificationChan)
- if err != nil {
- cn.Close()
- return err
- }
-
- l.cn = cn
- l.connNotificationChan = notificationChan
- l.reconnectCond.Broadcast()
-
- return nil
-}
-
-// Close disconnects the Listener from the database and shuts it down.
-// Subsequent calls to its methods will return an error. Close returns an
-// error if the connection has already been closed.
-func (l *Listener) Close() error {
- l.lock.Lock()
- defer l.lock.Unlock()
-
- if l.isClosed {
- return errListenerClosed
- }
-
- if l.cn != nil {
- l.cn.Close()
- }
- l.isClosed = true
-
- // Unblock calls to Listen()
- l.reconnectCond.Broadcast()
-
- return nil
-}
-
-func (l *Listener) emitEvent(event ListenerEventType, err error) {
- if l.eventCallback != nil {
- l.eventCallback(event, err)
- }
-}
-
-// Main logic here: maintain a connection to the server when possible, wait
-// for notifications and emit events.
-func (l *Listener) listenerConnLoop() {
- var nextReconnect time.Time
-
- reconnectInterval := l.minReconnectInterval
- for {
- for {
- err := l.connect()
- if err == nil {
- break
- }
-
- if l.closed() {
- return
- }
- l.emitEvent(ListenerEventConnectionAttemptFailed, err)
-
- time.Sleep(reconnectInterval)
- reconnectInterval *= 2
- if reconnectInterval > l.maxReconnectInterval {
- reconnectInterval = l.maxReconnectInterval
- }
- }
-
- if nextReconnect.IsZero() {
- l.emitEvent(ListenerEventConnected, nil)
- } else {
- l.emitEvent(ListenerEventReconnected, nil)
- l.Notify <- nil
- }
-
- reconnectInterval = l.minReconnectInterval
- nextReconnect = time.Now().Add(reconnectInterval)
-
- for {
- notification, ok := <-l.connNotificationChan
- if !ok {
- // lost connection, loop again
- break
- }
- l.Notify <- notification
- }
-
- err := l.disconnectCleanup()
- if l.closed() {
- return
- }
- l.emitEvent(ListenerEventDisconnected, err)
-
- time.Sleep(time.Until(nextReconnect))
- }
-}
-
-func (l *Listener) listenerMain() {
- l.listenerConnLoop()
- close(l.Notify)
-}
diff --git a/vendor/github.com/lib/pq/oid/doc.go b/vendor/github.com/lib/pq/oid/doc.go
deleted file mode 100644
index caaede2..0000000
--- a/vendor/github.com/lib/pq/oid/doc.go
+++ /dev/null
@@ -1,6 +0,0 @@
-// Package oid contains OID constants
-// as defined by the Postgres server.
-package oid
-
-// Oid is a Postgres Object ID.
-type Oid uint32
diff --git a/vendor/github.com/lib/pq/oid/types.go b/vendor/github.com/lib/pq/oid/types.go
deleted file mode 100644
index ecc84c2..0000000
--- a/vendor/github.com/lib/pq/oid/types.go
+++ /dev/null
@@ -1,343 +0,0 @@
-// Code generated by gen.go. DO NOT EDIT.
-
-package oid
-
-const (
- T_bool Oid = 16
- T_bytea Oid = 17
- T_char Oid = 18
- T_name Oid = 19
- T_int8 Oid = 20
- T_int2 Oid = 21
- T_int2vector Oid = 22
- T_int4 Oid = 23
- T_regproc Oid = 24
- T_text Oid = 25
- T_oid Oid = 26
- T_tid Oid = 27
- T_xid Oid = 28
- T_cid Oid = 29
- T_oidvector Oid = 30
- T_pg_ddl_command Oid = 32
- T_pg_type Oid = 71
- T_pg_attribute Oid = 75
- T_pg_proc Oid = 81
- T_pg_class Oid = 83
- T_json Oid = 114
- T_xml Oid = 142
- T__xml Oid = 143
- T_pg_node_tree Oid = 194
- T__json Oid = 199
- T_smgr Oid = 210
- T_index_am_handler Oid = 325
- T_point Oid = 600
- T_lseg Oid = 601
- T_path Oid = 602
- T_box Oid = 603
- T_polygon Oid = 604
- T_line Oid = 628
- T__line Oid = 629
- T_cidr Oid = 650
- T__cidr Oid = 651
- T_float4 Oid = 700
- T_float8 Oid = 701
- T_abstime Oid = 702
- T_reltime Oid = 703
- T_tinterval Oid = 704
- T_unknown Oid = 705
- T_circle Oid = 718
- T__circle Oid = 719
- T_money Oid = 790
- T__money Oid = 791
- T_macaddr Oid = 829
- T_inet Oid = 869
- T__bool Oid = 1000
- T__bytea Oid = 1001
- T__char Oid = 1002
- T__name Oid = 1003
- T__int2 Oid = 1005
- T__int2vector Oid = 1006
- T__int4 Oid = 1007
- T__regproc Oid = 1008
- T__text Oid = 1009
- T__tid Oid = 1010
- T__xid Oid = 1011
- T__cid Oid = 1012
- T__oidvector Oid = 1013
- T__bpchar Oid = 1014
- T__varchar Oid = 1015
- T__int8 Oid = 1016
- T__point Oid = 1017
- T__lseg Oid = 1018
- T__path Oid = 1019
- T__box Oid = 1020
- T__float4 Oid = 1021
- T__float8 Oid = 1022
- T__abstime Oid = 1023
- T__reltime Oid = 1024
- T__tinterval Oid = 1025
- T__polygon Oid = 1027
- T__oid Oid = 1028
- T_aclitem Oid = 1033
- T__aclitem Oid = 1034
- T__macaddr Oid = 1040
- T__inet Oid = 1041
- T_bpchar Oid = 1042
- T_varchar Oid = 1043
- T_date Oid = 1082
- T_time Oid = 1083
- T_timestamp Oid = 1114
- T__timestamp Oid = 1115
- T__date Oid = 1182
- T__time Oid = 1183
- T_timestamptz Oid = 1184
- T__timestamptz Oid = 1185
- T_interval Oid = 1186
- T__interval Oid = 1187
- T__numeric Oid = 1231
- T_pg_database Oid = 1248
- T__cstring Oid = 1263
- T_timetz Oid = 1266
- T__timetz Oid = 1270
- T_bit Oid = 1560
- T__bit Oid = 1561
- T_varbit Oid = 1562
- T__varbit Oid = 1563
- T_numeric Oid = 1700
- T_refcursor Oid = 1790
- T__refcursor Oid = 2201
- T_regprocedure Oid = 2202
- T_regoper Oid = 2203
- T_regoperator Oid = 2204
- T_regclass Oid = 2205
- T_regtype Oid = 2206
- T__regprocedure Oid = 2207
- T__regoper Oid = 2208
- T__regoperator Oid = 2209
- T__regclass Oid = 2210
- T__regtype Oid = 2211
- T_record Oid = 2249
- T_cstring Oid = 2275
- T_any Oid = 2276
- T_anyarray Oid = 2277
- T_void Oid = 2278
- T_trigger Oid = 2279
- T_language_handler Oid = 2280
- T_internal Oid = 2281
- T_opaque Oid = 2282
- T_anyelement Oid = 2283
- T__record Oid = 2287
- T_anynonarray Oid = 2776
- T_pg_authid Oid = 2842
- T_pg_auth_members Oid = 2843
- T__txid_snapshot Oid = 2949
- T_uuid Oid = 2950
- T__uuid Oid = 2951
- T_txid_snapshot Oid = 2970
- T_fdw_handler Oid = 3115
- T_pg_lsn Oid = 3220
- T__pg_lsn Oid = 3221
- T_tsm_handler Oid = 3310
- T_anyenum Oid = 3500
- T_tsvector Oid = 3614
- T_tsquery Oid = 3615
- T_gtsvector Oid = 3642
- T__tsvector Oid = 3643
- T__gtsvector Oid = 3644
- T__tsquery Oid = 3645
- T_regconfig Oid = 3734
- T__regconfig Oid = 3735
- T_regdictionary Oid = 3769
- T__regdictionary Oid = 3770
- T_jsonb Oid = 3802
- T__jsonb Oid = 3807
- T_anyrange Oid = 3831
- T_event_trigger Oid = 3838
- T_int4range Oid = 3904
- T__int4range Oid = 3905
- T_numrange Oid = 3906
- T__numrange Oid = 3907
- T_tsrange Oid = 3908
- T__tsrange Oid = 3909
- T_tstzrange Oid = 3910
- T__tstzrange Oid = 3911
- T_daterange Oid = 3912
- T__daterange Oid = 3913
- T_int8range Oid = 3926
- T__int8range Oid = 3927
- T_pg_shseclabel Oid = 4066
- T_regnamespace Oid = 4089
- T__regnamespace Oid = 4090
- T_regrole Oid = 4096
- T__regrole Oid = 4097
-)
-
-var TypeName = map[Oid]string{
- T_bool: "BOOL",
- T_bytea: "BYTEA",
- T_char: "CHAR",
- T_name: "NAME",
- T_int8: "INT8",
- T_int2: "INT2",
- T_int2vector: "INT2VECTOR",
- T_int4: "INT4",
- T_regproc: "REGPROC",
- T_text: "TEXT",
- T_oid: "OID",
- T_tid: "TID",
- T_xid: "XID",
- T_cid: "CID",
- T_oidvector: "OIDVECTOR",
- T_pg_ddl_command: "PG_DDL_COMMAND",
- T_pg_type: "PG_TYPE",
- T_pg_attribute: "PG_ATTRIBUTE",
- T_pg_proc: "PG_PROC",
- T_pg_class: "PG_CLASS",
- T_json: "JSON",
- T_xml: "XML",
- T__xml: "_XML",
- T_pg_node_tree: "PG_NODE_TREE",
- T__json: "_JSON",
- T_smgr: "SMGR",
- T_index_am_handler: "INDEX_AM_HANDLER",
- T_point: "POINT",
- T_lseg: "LSEG",
- T_path: "PATH",
- T_box: "BOX",
- T_polygon: "POLYGON",
- T_line: "LINE",
- T__line: "_LINE",
- T_cidr: "CIDR",
- T__cidr: "_CIDR",
- T_float4: "FLOAT4",
- T_float8: "FLOAT8",
- T_abstime: "ABSTIME",
- T_reltime: "RELTIME",
- T_tinterval: "TINTERVAL",
- T_unknown: "UNKNOWN",
- T_circle: "CIRCLE",
- T__circle: "_CIRCLE",
- T_money: "MONEY",
- T__money: "_MONEY",
- T_macaddr: "MACADDR",
- T_inet: "INET",
- T__bool: "_BOOL",
- T__bytea: "_BYTEA",
- T__char: "_CHAR",
- T__name: "_NAME",
- T__int2: "_INT2",
- T__int2vector: "_INT2VECTOR",
- T__int4: "_INT4",
- T__regproc: "_REGPROC",
- T__text: "_TEXT",
- T__tid: "_TID",
- T__xid: "_XID",
- T__cid: "_CID",
- T__oidvector: "_OIDVECTOR",
- T__bpchar: "_BPCHAR",
- T__varchar: "_VARCHAR",
- T__int8: "_INT8",
- T__point: "_POINT",
- T__lseg: "_LSEG",
- T__path: "_PATH",
- T__box: "_BOX",
- T__float4: "_FLOAT4",
- T__float8: "_FLOAT8",
- T__abstime: "_ABSTIME",
- T__reltime: "_RELTIME",
- T__tinterval: "_TINTERVAL",
- T__polygon: "_POLYGON",
- T__oid: "_OID",
- T_aclitem: "ACLITEM",
- T__aclitem: "_ACLITEM",
- T__macaddr: "_MACADDR",
- T__inet: "_INET",
- T_bpchar: "BPCHAR",
- T_varchar: "VARCHAR",
- T_date: "DATE",
- T_time: "TIME",
- T_timestamp: "TIMESTAMP",
- T__timestamp: "_TIMESTAMP",
- T__date: "_DATE",
- T__time: "_TIME",
- T_timestamptz: "TIMESTAMPTZ",
- T__timestamptz: "_TIMESTAMPTZ",
- T_interval: "INTERVAL",
- T__interval: "_INTERVAL",
- T__numeric: "_NUMERIC",
- T_pg_database: "PG_DATABASE",
- T__cstring: "_CSTRING",
- T_timetz: "TIMETZ",
- T__timetz: "_TIMETZ",
- T_bit: "BIT",
- T__bit: "_BIT",
- T_varbit: "VARBIT",
- T__varbit: "_VARBIT",
- T_numeric: "NUMERIC",
- T_refcursor: "REFCURSOR",
- T__refcursor: "_REFCURSOR",
- T_regprocedure: "REGPROCEDURE",
- T_regoper: "REGOPER",
- T_regoperator: "REGOPERATOR",
- T_regclass: "REGCLASS",
- T_regtype: "REGTYPE",
- T__regprocedure: "_REGPROCEDURE",
- T__regoper: "_REGOPER",
- T__regoperator: "_REGOPERATOR",
- T__regclass: "_REGCLASS",
- T__regtype: "_REGTYPE",
- T_record: "RECORD",
- T_cstring: "CSTRING",
- T_any: "ANY",
- T_anyarray: "ANYARRAY",
- T_void: "VOID",
- T_trigger: "TRIGGER",
- T_language_handler: "LANGUAGE_HANDLER",
- T_internal: "INTERNAL",
- T_opaque: "OPAQUE",
- T_anyelement: "ANYELEMENT",
- T__record: "_RECORD",
- T_anynonarray: "ANYNONARRAY",
- T_pg_authid: "PG_AUTHID",
- T_pg_auth_members: "PG_AUTH_MEMBERS",
- T__txid_snapshot: "_TXID_SNAPSHOT",
- T_uuid: "UUID",
- T__uuid: "_UUID",
- T_txid_snapshot: "TXID_SNAPSHOT",
- T_fdw_handler: "FDW_HANDLER",
- T_pg_lsn: "PG_LSN",
- T__pg_lsn: "_PG_LSN",
- T_tsm_handler: "TSM_HANDLER",
- T_anyenum: "ANYENUM",
- T_tsvector: "TSVECTOR",
- T_tsquery: "TSQUERY",
- T_gtsvector: "GTSVECTOR",
- T__tsvector: "_TSVECTOR",
- T__gtsvector: "_GTSVECTOR",
- T__tsquery: "_TSQUERY",
- T_regconfig: "REGCONFIG",
- T__regconfig: "_REGCONFIG",
- T_regdictionary: "REGDICTIONARY",
- T__regdictionary: "_REGDICTIONARY",
- T_jsonb: "JSONB",
- T__jsonb: "_JSONB",
- T_anyrange: "ANYRANGE",
- T_event_trigger: "EVENT_TRIGGER",
- T_int4range: "INT4RANGE",
- T__int4range: "_INT4RANGE",
- T_numrange: "NUMRANGE",
- T__numrange: "_NUMRANGE",
- T_tsrange: "TSRANGE",
- T__tsrange: "_TSRANGE",
- T_tstzrange: "TSTZRANGE",
- T__tstzrange: "_TSTZRANGE",
- T_daterange: "DATERANGE",
- T__daterange: "_DATERANGE",
- T_int8range: "INT8RANGE",
- T__int8range: "_INT8RANGE",
- T_pg_shseclabel: "PG_SHSECLABEL",
- T_regnamespace: "REGNAMESPACE",
- T__regnamespace: "_REGNAMESPACE",
- T_regrole: "REGROLE",
- T__regrole: "_REGROLE",
-}
diff --git a/vendor/github.com/lib/pq/rows.go b/vendor/github.com/lib/pq/rows.go
deleted file mode 100644
index c6aa5b9..0000000
--- a/vendor/github.com/lib/pq/rows.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package pq
-
-import (
- "math"
- "reflect"
- "time"
-
- "github.com/lib/pq/oid"
-)
-
-const headerSize = 4
-
-type fieldDesc struct {
- // The object ID of the data type.
- OID oid.Oid
- // The data type size (see pg_type.typlen).
- // Note that negative values denote variable-width types.
- Len int
- // The type modifier (see pg_attribute.atttypmod).
- // The meaning of the modifier is type-specific.
- Mod int
-}
-
-func (fd fieldDesc) Type() reflect.Type {
- switch fd.OID {
- case oid.T_int8:
- return reflect.TypeOf(int64(0))
- case oid.T_int4:
- return reflect.TypeOf(int32(0))
- case oid.T_int2:
- return reflect.TypeOf(int16(0))
- case oid.T_varchar, oid.T_text:
- return reflect.TypeOf("")
- case oid.T_bool:
- return reflect.TypeOf(false)
- case oid.T_date, oid.T_time, oid.T_timetz, oid.T_timestamp, oid.T_timestamptz:
- return reflect.TypeOf(time.Time{})
- case oid.T_bytea:
- return reflect.TypeOf([]byte(nil))
- default:
- return reflect.TypeOf(new(interface{})).Elem()
- }
-}
-
-func (fd fieldDesc) Name() string {
- return oid.TypeName[fd.OID]
-}
-
-func (fd fieldDesc) Length() (length int64, ok bool) {
- switch fd.OID {
- case oid.T_text, oid.T_bytea:
- return math.MaxInt64, true
- case oid.T_varchar, oid.T_bpchar:
- return int64(fd.Mod - headerSize), true
- default:
- return 0, false
- }
-}
-
-func (fd fieldDesc) PrecisionScale() (precision, scale int64, ok bool) {
- switch fd.OID {
- case oid.T_numeric, oid.T__numeric:
- mod := fd.Mod - headerSize
- precision = int64((mod >> 16) & 0xffff)
- scale = int64(mod & 0xffff)
- return precision, scale, true
- default:
- return 0, 0, false
- }
-}
-
-// ColumnTypeScanType returns the value type that can be used to scan types into.
-func (rs *rows) ColumnTypeScanType(index int) reflect.Type {
- return rs.colTyps[index].Type()
-}
-
-// ColumnTypeDatabaseTypeName return the database system type name.
-func (rs *rows) ColumnTypeDatabaseTypeName(index int) string {
- return rs.colTyps[index].Name()
-}
-
-// ColumnTypeLength returns the length of the column type if the column is a
-// variable length type. If the column is not a variable length type ok
-// should return false.
-func (rs *rows) ColumnTypeLength(index int) (length int64, ok bool) {
- return rs.colTyps[index].Length()
-}
-
-// ColumnTypePrecisionScale should return the precision and scale for decimal
-// types. If not applicable, ok should be false.
-func (rs *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
- return rs.colTyps[index].PrecisionScale()
-}
diff --git a/vendor/github.com/lib/pq/scram/scram.go b/vendor/github.com/lib/pq/scram/scram.go
deleted file mode 100644
index 477216b..0000000
--- a/vendor/github.com/lib/pq/scram/scram.go
+++ /dev/null
@@ -1,264 +0,0 @@
-// Copyright (c) 2014 - Gustavo Niemeyer <gustavo@niemeyer.net>
-//
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-// 2. 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 OWNER 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.
-
-// Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802.
-//
-// http://tools.ietf.org/html/rfc5802
-//
-package scram
-
-import (
- "bytes"
- "crypto/hmac"
- "crypto/rand"
- "encoding/base64"
- "fmt"
- "hash"
- "strconv"
- "strings"
-)
-
-// Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc).
-//
-// A Client may be used within a SASL conversation with logic resembling:
-//
-// var in []byte
-// var client = scram.NewClient(sha1.New, user, pass)
-// for client.Step(in) {
-// out := client.Out()
-// // send out to server
-// in := serverOut
-// }
-// if client.Err() != nil {
-// // auth failed
-// }
-//
-type Client struct {
- newHash func() hash.Hash
-
- user string
- pass string
- step int
- out bytes.Buffer
- err error
-
- clientNonce []byte
- serverNonce []byte
- saltedPass []byte
- authMsg bytes.Buffer
-}
-
-// NewClient returns a new SCRAM-* client with the provided hash algorithm.
-//
-// For SCRAM-SHA-256, for example, use:
-//
-// client := scram.NewClient(sha256.New, user, pass)
-//
-func NewClient(newHash func() hash.Hash, user, pass string) *Client {
- c := &Client{
- newHash: newHash,
- user: user,
- pass: pass,
- }
- c.out.Grow(256)
- c.authMsg.Grow(256)
- return c
-}
-
-// Out returns the data to be sent to the server in the current step.
-func (c *Client) Out() []byte {
- if c.out.Len() == 0 {
- return nil
- }
- return c.out.Bytes()
-}
-
-// Err returns the error that occurred, or nil if there were no errors.
-func (c *Client) Err() error {
- return c.err
-}
-
-// SetNonce sets the client nonce to the provided value.
-// If not set, the nonce is generated automatically out of crypto/rand on the first step.
-func (c *Client) SetNonce(nonce []byte) {
- c.clientNonce = nonce
-}
-
-var escaper = strings.NewReplacer("=", "=3D", ",", "=2C")
-
-// Step processes the incoming data from the server and makes the
-// next round of data for the server available via Client.Out.
-// Step returns false if there are no errors and more data is
-// still expected.
-func (c *Client) Step(in []byte) bool {
- c.out.Reset()
- if c.step > 2 || c.err != nil {
- return false
- }
- c.step++
- switch c.step {
- case 1:
- c.err = c.step1(in)
- case 2:
- c.err = c.step2(in)
- case 3:
- c.err = c.step3(in)
- }
- return c.step > 2 || c.err != nil
-}
-
-func (c *Client) step1(in []byte) error {
- if len(c.clientNonce) == 0 {
- const nonceLen = 16
- buf := make([]byte, nonceLen+b64.EncodedLen(nonceLen))
- if _, err := rand.Read(buf[:nonceLen]); err != nil {
- return fmt.Errorf("cannot read random SCRAM-SHA-256 nonce from operating system: %v", err)
- }
- c.clientNonce = buf[nonceLen:]
- b64.Encode(c.clientNonce, buf[:nonceLen])
- }
- c.authMsg.WriteString("n=")
- escaper.WriteString(&c.authMsg, c.user)
- c.authMsg.WriteString(",r=")
- c.authMsg.Write(c.clientNonce)
-
- c.out.WriteString("n,,")
- c.out.Write(c.authMsg.Bytes())
- return nil
-}
-
-var b64 = base64.StdEncoding
-
-func (c *Client) step2(in []byte) error {
- c.authMsg.WriteByte(',')
- c.authMsg.Write(in)
-
- fields := bytes.Split(in, []byte(","))
- if len(fields) != 3 {
- return fmt.Errorf("expected 3 fields in first SCRAM-SHA-256 server message, got %d: %q", len(fields), in)
- }
- if !bytes.HasPrefix(fields[0], []byte("r=")) || len(fields[0]) < 2 {
- return fmt.Errorf("server sent an invalid SCRAM-SHA-256 nonce: %q", fields[0])
- }
- if !bytes.HasPrefix(fields[1], []byte("s=")) || len(fields[1]) < 6 {
- return fmt.Errorf("server sent an invalid SCRAM-SHA-256 salt: %q", fields[1])
- }
- if !bytes.HasPrefix(fields[2], []byte("i=")) || len(fields[2]) < 6 {
- return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2])
- }
-
- c.serverNonce = fields[0][2:]
- if !bytes.HasPrefix(c.serverNonce, c.clientNonce) {
- return fmt.Errorf("server SCRAM-SHA-256 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", c.serverNonce, c.clientNonce)
- }
-
- salt := make([]byte, b64.DecodedLen(len(fields[1][2:])))
- n, err := b64.Decode(salt, fields[1][2:])
- if err != nil {
- return fmt.Errorf("cannot decode SCRAM-SHA-256 salt sent by server: %q", fields[1])
- }
- salt = salt[:n]
- iterCount, err := strconv.Atoi(string(fields[2][2:]))
- if err != nil {
- return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2])
- }
- c.saltPassword(salt, iterCount)
-
- c.authMsg.WriteString(",c=biws,r=")
- c.authMsg.Write(c.serverNonce)
-
- c.out.WriteString("c=biws,r=")
- c.out.Write(c.serverNonce)
- c.out.WriteString(",p=")
- c.out.Write(c.clientProof())
- return nil
-}
-
-func (c *Client) step3(in []byte) error {
- var isv, ise bool
- var fields = bytes.Split(in, []byte(","))
- if len(fields) == 1 {
- isv = bytes.HasPrefix(fields[0], []byte("v="))
- ise = bytes.HasPrefix(fields[0], []byte("e="))
- }
- if ise {
- return fmt.Errorf("SCRAM-SHA-256 authentication error: %s", fields[0][2:])
- } else if !isv {
- return fmt.Errorf("unsupported SCRAM-SHA-256 final message from server: %q", in)
- }
- if !bytes.Equal(c.serverSignature(), fields[0][2:]) {
- return fmt.Errorf("cannot authenticate SCRAM-SHA-256 server signature: %q", fields[0][2:])
- }
- return nil
-}
-
-func (c *Client) saltPassword(salt []byte, iterCount int) {
- mac := hmac.New(c.newHash, []byte(c.pass))
- mac.Write(salt)
- mac.Write([]byte{0, 0, 0, 1})
- ui := mac.Sum(nil)
- hi := make([]byte, len(ui))
- copy(hi, ui)
- for i := 1; i < iterCount; i++ {
- mac.Reset()
- mac.Write(ui)
- mac.Sum(ui[:0])
- for j, b := range ui {
- hi[j] ^= b
- }
- }
- c.saltedPass = hi
-}
-
-func (c *Client) clientProof() []byte {
- mac := hmac.New(c.newHash, c.saltedPass)
- mac.Write([]byte("Client Key"))
- clientKey := mac.Sum(nil)
- hash := c.newHash()
- hash.Write(clientKey)
- storedKey := hash.Sum(nil)
- mac = hmac.New(c.newHash, storedKey)
- mac.Write(c.authMsg.Bytes())
- clientProof := mac.Sum(nil)
- for i, b := range clientKey {
- clientProof[i] ^= b
- }
- clientProof64 := make([]byte, b64.EncodedLen(len(clientProof)))
- b64.Encode(clientProof64, clientProof)
- return clientProof64
-}
-
-func (c *Client) serverSignature() []byte {
- mac := hmac.New(c.newHash, c.saltedPass)
- mac.Write([]byte("Server Key"))
- serverKey := mac.Sum(nil)
-
- mac = hmac.New(c.newHash, serverKey)
- mac.Write(c.authMsg.Bytes())
- serverSignature := mac.Sum(nil)
-
- encoded := make([]byte, b64.EncodedLen(len(serverSignature)))
- b64.Encode(encoded, serverSignature)
- return encoded
-}
diff --git a/vendor/github.com/lib/pq/ssl.go b/vendor/github.com/lib/pq/ssl.go
deleted file mode 100644
index 36b61ba..0000000
--- a/vendor/github.com/lib/pq/ssl.go
+++ /dev/null
@@ -1,204 +0,0 @@
-package pq
-
-import (
- "crypto/tls"
- "crypto/x509"
- "io/ioutil"
- "net"
- "os"
- "os/user"
- "path/filepath"
- "strings"
-)
-
-// ssl generates a function to upgrade a net.Conn based on the "sslmode" and
-// related settings. The function is nil when no upgrade should take place.
-func ssl(o values) (func(net.Conn) (net.Conn, error), error) {
- verifyCaOnly := false
- tlsConf := tls.Config{}
- switch mode := o["sslmode"]; mode {
- // "require" is the default.
- case "", "require":
- // We must skip TLS's own verification since it requires full
- // verification since Go 1.3.
- tlsConf.InsecureSkipVerify = true
-
- // From http://www.postgresql.org/docs/current/static/libpq-ssl.html:
- //
- // Note: For backwards compatibility with earlier versions of
- // PostgreSQL, if a root CA file exists, the behavior of
- // sslmode=require will be the same as that of verify-ca, meaning the
- // server certificate is validated against the CA. Relying on this
- // behavior is discouraged, and applications that need certificate
- // validation should always use verify-ca or verify-full.
- if sslrootcert, ok := o["sslrootcert"]; ok {
- if _, err := os.Stat(sslrootcert); err == nil {
- verifyCaOnly = true
- } else {
- delete(o, "sslrootcert")
- }
- }
- case "verify-ca":
- // We must skip TLS's own verification since it requires full
- // verification since Go 1.3.
- tlsConf.InsecureSkipVerify = true
- verifyCaOnly = true
- case "verify-full":
- tlsConf.ServerName = o["host"]
- case "disable":
- return nil, nil
- default:
- return nil, fmterrorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode)
- }
-
- // Set Server Name Indication (SNI), if enabled by connection parameters.
- // By default SNI is on, any value which is not starting with "1" disables
- // SNI -- that is the same check vanilla libpq uses.
- if sslsni := o["sslsni"]; sslsni == "" || strings.HasPrefix(sslsni, "1") {
- // RFC 6066 asks to not set SNI if the host is a literal IP address (IPv4
- // or IPv6). This check is coded already crypto.tls.hostnameInSNI, so
- // just always set ServerName here and let crypto/tls do the filtering.
- tlsConf.ServerName = o["host"]
- }
-
- err := sslClientCertificates(&tlsConf, o)
- if err != nil {
- return nil, err
- }
- err = sslCertificateAuthority(&tlsConf, o)
- if err != nil {
- return nil, err
- }
-
- // Accept renegotiation requests initiated by the backend.
- //
- // Renegotiation was deprecated then removed from PostgreSQL 9.5, but
- // the default configuration of older versions has it enabled. Redshift
- // also initiates renegotiations and cannot be reconfigured.
- tlsConf.Renegotiation = tls.RenegotiateFreelyAsClient
-
- return func(conn net.Conn) (net.Conn, error) {
- client := tls.Client(conn, &tlsConf)
- if verifyCaOnly {
- err := sslVerifyCertificateAuthority(client, &tlsConf)
- if err != nil {
- return nil, err
- }
- }
- return client, nil
- }, nil
-}
-
-// sslClientCertificates adds the certificate specified in the "sslcert" and
-// "sslkey" settings, or if they aren't set, from the .postgresql directory
-// in the user's home directory. The configured files must exist and have
-// the correct permissions.
-func sslClientCertificates(tlsConf *tls.Config, o values) error {
- sslinline := o["sslinline"]
- if sslinline == "true" {
- cert, err := tls.X509KeyPair([]byte(o["sslcert"]), []byte(o["sslkey"]))
- if err != nil {
- return err
- }
- tlsConf.Certificates = []tls.Certificate{cert}
- return nil
- }
-
- // user.Current() might fail when cross-compiling. We have to ignore the
- // error and continue without home directory defaults, since we wouldn't
- // know from where to load them.
- user, _ := user.Current()
-
- // In libpq, the client certificate is only loaded if the setting is not blank.
- //
- // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1036-L1037
- sslcert := o["sslcert"]
- if len(sslcert) == 0 && user != nil {
- sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
- }
- // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045
- if len(sslcert) == 0 {
- return nil
- }
- // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054
- if _, err := os.Stat(sslcert); os.IsNotExist(err) {
- return nil
- } else if err != nil {
- return err
- }
-
- // In libpq, the ssl key is only loaded if the setting is not blank.
- //
- // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1123-L1222
- sslkey := o["sslkey"]
- if len(sslkey) == 0 && user != nil {
- sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
- }
-
- if len(sslkey) > 0 {
- if err := sslKeyPermissions(sslkey); err != nil {
- return err
- }
- }
-
- cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
- if err != nil {
- return err
- }
-
- tlsConf.Certificates = []tls.Certificate{cert}
- return nil
-}
-
-// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting.
-func sslCertificateAuthority(tlsConf *tls.Config, o values) error {
- // In libpq, the root certificate is only loaded if the setting is not blank.
- //
- // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951
- if sslrootcert := o["sslrootcert"]; len(sslrootcert) > 0 {
- tlsConf.RootCAs = x509.NewCertPool()
-
- sslinline := o["sslinline"]
-
- var cert []byte
- if sslinline == "true" {
- cert = []byte(sslrootcert)
- } else {
- var err error
- cert, err = ioutil.ReadFile(sslrootcert)
- if err != nil {
- return err
- }
- }
-
- if !tlsConf.RootCAs.AppendCertsFromPEM(cert) {
- return fmterrorf("couldn't parse pem in sslrootcert")
- }
- }
-
- return nil
-}
-
-// sslVerifyCertificateAuthority carries out a TLS handshake to the server and
-// verifies the presented certificate against the CA, i.e. the one specified in
-// sslrootcert or the system CA if sslrootcert was not specified.
-func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) error {
- err := client.Handshake()
- if err != nil {
- return err
- }
- certs := client.ConnectionState().PeerCertificates
- opts := x509.VerifyOptions{
- DNSName: client.ConnectionState().ServerName,
- Intermediates: x509.NewCertPool(),
- Roots: tlsConf.RootCAs,
- }
- for i, cert := range certs {
- if i == 0 {
- continue
- }
- opts.Intermediates.AddCert(cert)
- }
- _, err = certs[0].Verify(opts)
- return err
-}
diff --git a/vendor/github.com/lib/pq/ssl_permissions.go b/vendor/github.com/lib/pq/ssl_permissions.go
deleted file mode 100644
index d587f10..0000000
--- a/vendor/github.com/lib/pq/ssl_permissions.go
+++ /dev/null
@@ -1,93 +0,0 @@
-//go:build !windows
-// +build !windows
-
-package pq
-
-import (
- "errors"
- "os"
- "syscall"
-)
-
-const (
- rootUserID = uint32(0)
-
- // The maximum permissions that a private key file owned by a regular user
- // is allowed to have. This translates to u=rw.
- maxUserOwnedKeyPermissions os.FileMode = 0600
-
- // The maximum permissions that a private key file owned by root is allowed
- // to have. This translates to u=rw,g=r.
- maxRootOwnedKeyPermissions os.FileMode = 0640
-)
-
-var (
- errSSLKeyHasUnacceptableUserPermissions = errors.New("permissions for files not owned by root should be u=rw (0600) or less")
- errSSLKeyHasUnacceptableRootPermissions = errors.New("permissions for root owned files should be u=rw,g=r (0640) or less")
-)
-
-// sslKeyPermissions checks the permissions on user-supplied ssl key files.
-// The key file should have very little access.
-//
-// libpq does not check key file permissions on Windows.
-func sslKeyPermissions(sslkey string) error {
- info, err := os.Stat(sslkey)
- if err != nil {
- return err
- }
-
- err = hasCorrectPermissions(info)
-
- // return ErrSSLKeyHasWorldPermissions for backwards compatability with
- // existing code.
- if err == errSSLKeyHasUnacceptableUserPermissions || err == errSSLKeyHasUnacceptableRootPermissions {
- err = ErrSSLKeyHasWorldPermissions
- }
- return err
-}
-
-// hasCorrectPermissions checks the file info (and the unix-specific stat_t
-// output) to verify that the permissions on the file are correct.
-//
-// If the file is owned by the same user the process is running as,
-// the file should only have 0600 (u=rw). If the file is owned by root,
-// and the group matches the group that the process is running in, the
-// permissions cannot be more than 0640 (u=rw,g=r). The file should
-// never have world permissions.
-//
-// Returns an error when the permission check fails.
-func hasCorrectPermissions(info os.FileInfo) error {
- // if file's permission matches 0600, allow access.
- userPermissionMask := (os.FileMode(0777) ^ maxUserOwnedKeyPermissions)
-
- // regardless of if we're running as root or not, 0600 is acceptable,
- // so we return if we match the regular user permission mask.
- if info.Mode().Perm()&userPermissionMask == 0 {
- return nil
- }
-
- // We need to pull the Unix file information to get the file's owner.
- // If we can't access it, there's some sort of operating system level error
- // and we should fail rather than attempting to use faulty information.
- sysInfo := info.Sys()
- if sysInfo == nil {
- return ErrSSLKeyUnknownOwnership
- }
-
- unixStat, ok := sysInfo.(*syscall.Stat_t)
- if !ok {
- return ErrSSLKeyUnknownOwnership
- }
-
- // if the file is owned by root, we allow 0640 (u=rw,g=r) to match what
- // Postgres does.
- if unixStat.Uid == rootUserID {
- rootPermissionMask := (os.FileMode(0777) ^ maxRootOwnedKeyPermissions)
- if info.Mode().Perm()&rootPermissionMask != 0 {
- return errSSLKeyHasUnacceptableRootPermissions
- }
- return nil
- }
-
- return errSSLKeyHasUnacceptableUserPermissions
-}
diff --git a/vendor/github.com/lib/pq/ssl_windows.go b/vendor/github.com/lib/pq/ssl_windows.go
deleted file mode 100644
index 73663c8..0000000
--- a/vendor/github.com/lib/pq/ssl_windows.go
+++ /dev/null
@@ -1,10 +0,0 @@
-//go:build windows
-// +build windows
-
-package pq
-
-// sslKeyPermissions checks the permissions on user-supplied ssl key files.
-// The key file should have very little access.
-//
-// libpq does not check key file permissions on Windows.
-func sslKeyPermissions(string) error { return nil }
diff --git a/vendor/github.com/lib/pq/url.go b/vendor/github.com/lib/pq/url.go
deleted file mode 100644
index aec6e95..0000000
--- a/vendor/github.com/lib/pq/url.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package pq
-
-import (
- "fmt"
- "net"
- nurl "net/url"
- "sort"
- "strings"
-)
-
-// ParseURL no longer needs to be used by clients of this library since supplying a URL as a
-// connection string to sql.Open() is now supported:
-//
-// sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full")
-//
-// It remains exported here for backwards-compatibility.
-//
-// ParseURL converts a url to a connection string for driver.Open.
-// Example:
-//
-// "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full"
-//
-// converts to:
-//
-// "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full"
-//
-// A minimal example:
-//
-// "postgres://"
-//
-// This will be blank, causing driver.Open to use all of the defaults
-func ParseURL(url string) (string, error) {
- u, err := nurl.Parse(url)
- if err != nil {
- return "", err
- }
-
- if u.Scheme != "postgres" && u.Scheme != "postgresql" {
- return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme)
- }
-
- var kvs []string
- escaper := strings.NewReplacer(`'`, `\'`, `\`, `\\`)
- accrue := func(k, v string) {
- if v != "" {
- kvs = append(kvs, k+"='"+escaper.Replace(v)+"'")
- }
- }
-
- if u.User != nil {
- v := u.User.Username()
- accrue("user", v)
-
- v, _ = u.User.Password()
- accrue("password", v)
- }
-
- if host, port, err := net.SplitHostPort(u.Host); err != nil {
- accrue("host", u.Host)
- } else {
- accrue("host", host)
- accrue("port", port)
- }
-
- if u.Path != "" {
- accrue("dbname", u.Path[1:])
- }
-
- q := u.Query()
- for k := range q {
- accrue(k, q.Get(k))
- }
-
- sort.Strings(kvs) // Makes testing easier (not a performance concern)
- return strings.Join(kvs, " "), nil
-}
diff --git a/vendor/github.com/lib/pq/user_other.go b/vendor/github.com/lib/pq/user_other.go
deleted file mode 100644
index 3dae8f5..0000000
--- a/vendor/github.com/lib/pq/user_other.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// Package pq is a pure Go Postgres driver for the database/sql package.
-
-//go:build js || android || hurd || zos
-// +build js android hurd zos
-
-package pq
-
-func userCurrent() (string, error) {
- return "", ErrCouldNotDetectUsername
-}
diff --git a/vendor/github.com/lib/pq/user_posix.go b/vendor/github.com/lib/pq/user_posix.go
deleted file mode 100644
index 5f2d439..0000000
--- a/vendor/github.com/lib/pq/user_posix.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// Package pq is a pure Go Postgres driver for the database/sql package.
-
-//go:build aix || darwin || dragonfly || freebsd || (linux && !android) || nacl || netbsd || openbsd || plan9 || solaris || rumprun || illumos
-// +build aix darwin dragonfly freebsd linux,!android nacl netbsd openbsd plan9 solaris rumprun illumos
-
-package pq
-
-import (
- "os"
- "os/user"
-)
-
-func userCurrent() (string, error) {
- u, err := user.Current()
- if err == nil {
- return u.Username, nil
- }
-
- name := os.Getenv("USER")
- if name != "" {
- return name, nil
- }
-
- return "", ErrCouldNotDetectUsername
-}
diff --git a/vendor/github.com/lib/pq/user_windows.go b/vendor/github.com/lib/pq/user_windows.go
deleted file mode 100644
index 2b69126..0000000
--- a/vendor/github.com/lib/pq/user_windows.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Package pq is a pure Go Postgres driver for the database/sql package.
-package pq
-
-import (
- "path/filepath"
- "syscall"
-)
-
-// Perform Windows user name lookup identically to libpq.
-//
-// The PostgreSQL code makes use of the legacy Win32 function
-// GetUserName, and that function has not been imported into stock Go.
-// GetUserNameEx is available though, the difference being that a
-// wider range of names are available. To get the output to be the
-// same as GetUserName, only the base (or last) component of the
-// result is returned.
-func userCurrent() (string, error) {
- pw_name := make([]uint16, 128)
- pwname_size := uint32(len(pw_name)) - 1
- err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size)
- if err != nil {
- return "", ErrCouldNotDetectUsername
- }
- s := syscall.UTF16ToString(pw_name)
- u := filepath.Base(s)
- return u, nil
-}
diff --git a/vendor/github.com/lib/pq/uuid.go b/vendor/github.com/lib/pq/uuid.go
deleted file mode 100644
index 9a1b9e0..0000000
--- a/vendor/github.com/lib/pq/uuid.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package pq
-
-import (
- "encoding/hex"
- "fmt"
-)
-
-// decodeUUIDBinary interprets the binary format of a uuid, returning it in text format.
-func decodeUUIDBinary(src []byte) ([]byte, error) {
- if len(src) != 16 {
- return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src))
- }
-
- dst := make([]byte, 36)
- dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-'
- hex.Encode(dst[0:], src[0:4])
- hex.Encode(dst[9:], src[4:6])
- hex.Encode(dst[14:], src[6:8])
- hex.Encode(dst[19:], src[8:10])
- hex.Encode(dst[24:], src[10:16])
-
- return dst, nil
-}
diff --git a/vendor/gotest.tools/v3/LICENSE b/vendor/gotest.tools/v3/LICENSE
deleted file mode 100644
index aeaa2fa..0000000
--- a/vendor/gotest.tools/v3/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright 2018 gotest.tools authors
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/vendor/gotest.tools/v3/assert/assert.go b/vendor/gotest.tools/v3/assert/assert.go
deleted file mode 100644
index c418bd0..0000000
--- a/vendor/gotest.tools/v3/assert/assert.go
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
-Package assert provides assertions for comparing expected values to actual
-values in tests. When an assertion fails a helpful error message is printed.
-
-# Example usage
-
-All the assertions in this package use [testing.T.Helper] to mark themselves as
-test helpers. This allows the testing package to print the filename and line
-number of the file function that failed.
-
- assert.NilError(t, err)
- // filename_test.go:212: assertion failed: error is not nil: file not found
-
-If any assertion is called from a helper function, make sure to call t.Helper
-from the helper function so that the filename and line number remain correct.
-
-The examples below show assert used with some common types and the failure
-messages it produces. The filename and line number portion of the failure
-message is omitted from these examples for brevity.
-
- // booleans
-
- assert.Assert(t, ok)
- // assertion failed: ok is false
- assert.Assert(t, !missing)
- // assertion failed: missing is true
-
- // primitives
-
- assert.Equal(t, count, 1)
- // assertion failed: 0 (count int) != 1 (int)
- assert.Equal(t, msg, "the message")
- // assertion failed: my message (msg string) != the message (string)
- assert.Assert(t, total != 10) // use Assert for NotEqual
- // assertion failed: total is 10
- assert.Assert(t, count > 20, "count=%v", count)
- // assertion failed: count is <= 20: count=1
-
- // errors
-
- assert.NilError(t, closer.Close())
- // assertion failed: error is not nil: close /file: errno 11
- assert.Error(t, err, "the exact error message")
- // assertion failed: expected error "the exact error message", got "oops"
- assert.ErrorContains(t, err, "includes this")
- // assertion failed: expected error to contain "includes this", got "oops"
- assert.ErrorIs(t, err, os.ErrNotExist)
- // assertion failed: error is "oops", not "file does not exist" (os.ErrNotExist)
-
- // complex types
-
- assert.DeepEqual(t, result, myStruct{Name: "title"})
- // assertion failed: ... (diff of the two structs)
- assert.Assert(t, is.Len(items, 3))
- // assertion failed: expected [] (length 0) to have length 3
- assert.Assert(t, len(sequence) != 0) // use Assert for NotEmpty
- // assertion failed: len(sequence) is 0
- assert.Assert(t, is.Contains(mapping, "key"))
- // assertion failed: map[other:1] does not contain key
-
- // pointers and interface
-
- assert.Assert(t, ref == nil)
- // assertion failed: ref is not nil
- assert.Assert(t, ref != nil) // use Assert for NotNil
- // assertion failed: ref is nil
-
-# Assert and Check
-
-[Assert] and [Check] are very similar, they both accept a [cmp.Comparison], and fail
-the test when the comparison fails. The one difference is that Assert uses
-[testing.T.FailNow] to fail the test, which will end the test execution immediately.
-Check uses [testing.T.Fail] to fail the test, which allows it to return the
-result of the comparison, then proceed with the rest of the test case.
-
-Like [testing.T.FailNow], [Assert] must be called from the goroutine running the test,
-not from other goroutines created during the test. [Check] is safe to use from any
-goroutine.
-
-# Comparisons
-
-Package [gotest.tools/v3/assert/cmp] provides
-many common comparisons. Additional comparisons can be written to compare
-values in other ways. See the example Assert (CustomComparison).
-
-# Automated migration from testify
-
-gty-migrate-from-testify is a command which translates Go source code from
-testify assertions to the assertions provided by this package.
-
-See http://pkg.go.dev/gotest.tools/v3/assert/cmd/gty-migrate-from-testify.
-*/
-package assert // import "gotest.tools/v3/assert"
-
-import (
- gocmp "github.com/google/go-cmp/cmp"
- "gotest.tools/v3/assert/cmp"
- "gotest.tools/v3/internal/assert"
-)
-
-// BoolOrComparison can be a bool, [cmp.Comparison], or error. See [Assert] for
-// details about how this type is used.
-type BoolOrComparison interface{}
-
-// TestingT is the subset of [testing.T] (see also [testing.TB]) used by the assert package.
-type TestingT interface {
- FailNow()
- Fail()
- Log(args ...interface{})
-}
-
-type helperT interface {
- Helper()
-}
-
-// Assert performs a comparison. If the comparison fails, the test is marked as
-// failed, a failure message is logged, and execution is stopped immediately.
-//
-// The comparison argument may be one of three types:
-//
-// bool
-// True is success. False is a failure. The failure message will contain
-// the literal source code of the expression.
-//
-// cmp.Comparison
-// Uses cmp.Result.Success() to check for success or failure.
-// The comparison is responsible for producing a helpful failure message.
-// http://pkg.go.dev/gotest.tools/v3/assert/cmp provides many common comparisons.
-//
-// error
-// A nil value is considered success, and a non-nil error is a failure.
-// The return value of error.Error is used as the failure message.
-//
-// Extra details can be added to the failure message using msgAndArgs. msgAndArgs
-// may be either a single string, or a format string and args that will be
-// passed to [fmt.Sprintf].
-//
-// Assert uses [testing.TB.FailNow] to fail the test. Like t.FailNow, Assert must be called
-// from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] from other goroutines.
-func Assert(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsFromComparisonCall, comparison, msgAndArgs...) {
- t.FailNow()
- }
-}
-
-// Check performs a comparison. If the comparison fails the test is marked as
-// failed, a failure message is printed, and Check returns false. If the comparison
-// is successful Check returns true. Check may be called from any goroutine.
-//
-// See [Assert] for details about the comparison arg and failure messages.
-func Check(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) bool {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsFromComparisonCall, comparison, msgAndArgs...) {
- t.Fail()
- return false
- }
- return true
-}
-
-// NilError fails the test immediately if err is not nil, and includes err.Error
-// in the failure message.
-//
-// NilError uses [testing.TB.FailNow] to fail the test. Like t.FailNow, NilError must be
-// called from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] from other goroutines.
-func NilError(t TestingT, err error, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsAfterT, err, msgAndArgs...) {
- t.FailNow()
- }
-}
-
-// Equal uses the == operator to assert two values are equal and fails the test
-// if they are not equal.
-//
-// If the comparison fails Equal will use the variable names and types of
-// x and y as part of the failure message to identify the actual and expected
-// values.
-//
-// assert.Equal(t, actual, expected)
-// // main_test.go:41: assertion failed: 1 (actual int) != 21 (expected int32)
-//
-// If either x or y are a multi-line string the failure message will include a
-// unified diff of the two values. If the values only differ by whitespace
-// the unified diff will be augmented by replacing whitespace characters with
-// visible characters to identify the whitespace difference.
-//
-// Equal uses [testing.T.FailNow] to fail the test. Like t.FailNow, Equal must be
-// called from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] with [cmp.Equal] from other
-// goroutines.
-func Equal(t TestingT, x, y interface{}, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsAfterT, cmp.Equal(x, y), msgAndArgs...) {
- t.FailNow()
- }
-}
-
-// DeepEqual uses [github.com/google/go-cmp/cmp]
-// to assert two values are equal and fails the test if they are not equal.
-//
-// Package [gotest.tools/v3/assert/opt] provides some additional
-// commonly used Options.
-//
-// DeepEqual uses [testing.T.FailNow] to fail the test. Like t.FailNow, DeepEqual must be
-// called from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] with [cmp.DeepEqual] from other
-// goroutines.
-func DeepEqual(t TestingT, x, y interface{}, opts ...gocmp.Option) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsAfterT, cmp.DeepEqual(x, y, opts...)) {
- t.FailNow()
- }
-}
-
-// Error fails the test if err is nil, or if err.Error is not equal to expected.
-// Both err.Error and expected will be included in the failure message.
-// Error performs an exact match of the error text. Use [ErrorContains] if only
-// part of the error message is relevant. Use [ErrorType] or [ErrorIs] to compare
-// errors by type.
-//
-// Error uses [testing.T.FailNow] to fail the test. Like t.FailNow, Error must be
-// called from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] with [cmp.Error] from other
-// goroutines.
-func Error(t TestingT, err error, expected string, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsAfterT, cmp.Error(err, expected), msgAndArgs...) {
- t.FailNow()
- }
-}
-
-// ErrorContains fails the test if err is nil, or if err.Error does not
-// contain the expected substring. Both err.Error and the expected substring
-// will be included in the failure message.
-//
-// ErrorContains uses [testing.T.FailNow] to fail the test. Like t.FailNow, ErrorContains
-// must be called from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] with [cmp.ErrorContains] from other
-// goroutines.
-func ErrorContains(t TestingT, err error, substring string, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsAfterT, cmp.ErrorContains(err, substring), msgAndArgs...) {
- t.FailNow()
- }
-}
-
-// ErrorType fails the test if err is nil, or err is not the expected type.
-// New code should use ErrorIs instead.
-//
-// Expected can be one of:
-//
-// func(error) bool
-// The function should return true if the error is the expected type.
-//
-// struct{} or *struct{}
-// A struct or a pointer to a struct. The assertion fails if the error is
-// not of the same type.
-//
-// *interface{}
-// A pointer to an interface type. The assertion fails if err does not
-// implement the interface.
-//
-// reflect.Type
-// The assertion fails if err does not implement the reflect.Type.
-//
-// ErrorType uses [testing.T.FailNow] to fail the test. Like t.FailNow, ErrorType
-// must be called from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] with [cmp.ErrorType] from other
-// goroutines.
-//
-// Deprecated: Use [ErrorIs]
-func ErrorType(t TestingT, err error, expected interface{}, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsAfterT, cmp.ErrorType(err, expected), msgAndArgs...) {
- t.FailNow()
- }
-}
-
-// ErrorIs fails the test if err is nil, or the error does not match expected
-// when compared using errors.Is. See [errors.Is] for
-// accepted arguments.
-//
-// ErrorIs uses [testing.T.FailNow] to fail the test. Like t.FailNow, ErrorIs
-// must be called from the goroutine running the test function, not from other
-// goroutines created during the test. Use [Check] with [cmp.ErrorIs] from other
-// goroutines.
-func ErrorIs(t TestingT, err error, expected error, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if !assert.Eval(t, assert.ArgsAfterT, cmp.ErrorIs(err, expected), msgAndArgs...) {
- t.FailNow()
- }
-}
diff --git a/vendor/gotest.tools/v3/assert/cmp/compare.go b/vendor/gotest.tools/v3/assert/cmp/compare.go
deleted file mode 100644
index 118844f..0000000
--- a/vendor/gotest.tools/v3/assert/cmp/compare.go
+++ /dev/null
@@ -1,404 +0,0 @@
-/*Package cmp provides Comparisons for Assert and Check*/
-package cmp // import "gotest.tools/v3/assert/cmp"
-
-import (
- "errors"
- "fmt"
- "reflect"
- "regexp"
- "strings"
-
- "github.com/google/go-cmp/cmp"
- "gotest.tools/v3/internal/format"
-)
-
-// Comparison is a function which compares values and returns [ResultSuccess] if
-// the actual value matches the expected value. If the values do not match the
-// [Result] will contain a message about why it failed.
-type Comparison func() Result
-
-// DeepEqual compares two values using [github.com/google/go-cmp/cmp]
-// and succeeds if the values are equal.
-//
-// The comparison can be customized using comparison Options.
-// Package [gotest.tools/v3/assert/opt] provides some additional
-// commonly used Options.
-func DeepEqual(x, y interface{}, opts ...cmp.Option) Comparison {
- return func() (result Result) {
- defer func() {
- if panicmsg, handled := handleCmpPanic(recover()); handled {
- result = ResultFailure(panicmsg)
- }
- }()
- diff := cmp.Diff(x, y, opts...)
- if diff == "" {
- return ResultSuccess
- }
- return multiLineDiffResult(diff, x, y)
- }
-}
-
-func handleCmpPanic(r interface{}) (string, bool) {
- if r == nil {
- return "", false
- }
- panicmsg, ok := r.(string)
- if !ok {
- panic(r)
- }
- switch {
- case strings.HasPrefix(panicmsg, "cannot handle unexported field"):
- return panicmsg, true
- }
- panic(r)
-}
-
-func toResult(success bool, msg string) Result {
- if success {
- return ResultSuccess
- }
- return ResultFailure(msg)
-}
-
-// RegexOrPattern may be either a [*regexp.Regexp] or a string that is a valid
-// regexp pattern.
-type RegexOrPattern interface{}
-
-// Regexp succeeds if value v matches regular expression re.
-//
-// Example:
-//
-// assert.Assert(t, cmp.Regexp("^[0-9a-f]{32}$", str))
-// r := regexp.MustCompile("^[0-9a-f]{32}$")
-// assert.Assert(t, cmp.Regexp(r, str))
-func Regexp(re RegexOrPattern, v string) Comparison {
- match := func(re *regexp.Regexp) Result {
- return toResult(
- re.MatchString(v),
- fmt.Sprintf("value %q does not match regexp %q", v, re.String()))
- }
-
- return func() Result {
- switch regex := re.(type) {
- case *regexp.Regexp:
- return match(regex)
- case string:
- re, err := regexp.Compile(regex)
- if err != nil {
- return ResultFailure(err.Error())
- }
- return match(re)
- default:
- return ResultFailure(fmt.Sprintf("invalid type %T for regex pattern", regex))
- }
- }
-}
-
-// Equal succeeds if x == y. See [gotest.tools/v3/assert.Equal] for full documentation.
-func Equal(x, y interface{}) Comparison {
- return func() Result {
- switch {
- case x == y:
- return ResultSuccess
- case isMultiLineStringCompare(x, y):
- diff := format.UnifiedDiff(format.DiffConfig{A: x.(string), B: y.(string)})
- return multiLineDiffResult(diff, x, y)
- }
- return ResultFailureTemplate(`
- {{- printf "%v" .Data.x}} (
- {{- with callArg 0 }}{{ formatNode . }} {{end -}}
- {{- printf "%T" .Data.x -}}
- ) != {{ printf "%v" .Data.y}} (
- {{- with callArg 1 }}{{ formatNode . }} {{end -}}
- {{- printf "%T" .Data.y -}}
- )`,
- map[string]interface{}{"x": x, "y": y})
- }
-}
-
-func isMultiLineStringCompare(x, y interface{}) bool {
- strX, ok := x.(string)
- if !ok {
- return false
- }
- strY, ok := y.(string)
- if !ok {
- return false
- }
- return strings.Contains(strX, "\n") || strings.Contains(strY, "\n")
-}
-
-func multiLineDiffResult(diff string, x, y interface{}) Result {
- return ResultFailureTemplate(`
---- {{ with callArg 0 }}{{ formatNode . }}{{else}}←{{end}}
-+++ {{ with callArg 1 }}{{ formatNode . }}{{else}}→{{end}}
-{{ .Data.diff }}`,
- map[string]interface{}{"diff": diff, "x": x, "y": y})
-}
-
-// Len succeeds if the sequence has the expected length.
-func Len(seq interface{}, expected int) Comparison {
- return func() (result Result) {
- defer func() {
- if e := recover(); e != nil {
- result = ResultFailure(fmt.Sprintf("type %T does not have a length", seq))
- }
- }()
- value := reflect.ValueOf(seq)
- length := value.Len()
- if length == expected {
- return ResultSuccess
- }
- msg := fmt.Sprintf("expected %s (length %d) to have length %d", seq, length, expected)
- return ResultFailure(msg)
- }
-}
-
-// Contains succeeds if item is in collection. Collection may be a string, map,
-// slice, or array.
-//
-// If collection is a string, item must also be a string, and is compared using
-// [strings.Contains].
-// If collection is a Map, contains will succeed if item is a key in the map.
-// If collection is a slice or array, item is compared to each item in the
-// sequence using [reflect.DeepEqual].
-func Contains(collection interface{}, item interface{}) Comparison {
- return func() Result {
- colValue := reflect.ValueOf(collection)
- if !colValue.IsValid() {
- return ResultFailure("nil does not contain items")
- }
- msg := fmt.Sprintf("%v does not contain %v", collection, item)
-
- itemValue := reflect.ValueOf(item)
- switch colValue.Type().Kind() {
- case reflect.String:
- if itemValue.Type().Kind() != reflect.String {
- return ResultFailure("string may only contain strings")
- }
- return toResult(
- strings.Contains(colValue.String(), itemValue.String()),
- fmt.Sprintf("string %q does not contain %q", collection, item))
-
- case reflect.Map:
- if itemValue.Type() != colValue.Type().Key() {
- return ResultFailure(fmt.Sprintf(
- "%v can not contain a %v key", colValue.Type(), itemValue.Type()))
- }
- return toResult(colValue.MapIndex(itemValue).IsValid(), msg)
-
- case reflect.Slice, reflect.Array:
- for i := 0; i < colValue.Len(); i++ {
- if reflect.DeepEqual(colValue.Index(i).Interface(), item) {
- return ResultSuccess
- }
- }
- return ResultFailure(msg)
- default:
- return ResultFailure(fmt.Sprintf("type %T does not contain items", collection))
- }
- }
-}
-
-// Panics succeeds if f() panics.
-func Panics(f func()) Comparison {
- return func() (result Result) {
- defer func() {
- if err := recover(); err != nil {
- result = ResultSuccess
- }
- }()
- f()
- return ResultFailure("did not panic")
- }
-}
-
-// Error succeeds if err is a non-nil error, and the error message equals the
-// expected message.
-func Error(err error, message string) Comparison {
- return func() Result {
- switch {
- case err == nil:
- return ResultFailure("expected an error, got nil")
- case err.Error() != message:
- return ResultFailure(fmt.Sprintf(
- "expected error %q, got %s", message, formatErrorMessage(err)))
- }
- return ResultSuccess
- }
-}
-
-// ErrorContains succeeds if err is a non-nil error, and the error message contains
-// the expected substring.
-func ErrorContains(err error, substring string) Comparison {
- return func() Result {
- switch {
- case err == nil:
- return ResultFailure("expected an error, got nil")
- case !strings.Contains(err.Error(), substring):
- return ResultFailure(fmt.Sprintf(
- "expected error to contain %q, got %s", substring, formatErrorMessage(err)))
- }
- return ResultSuccess
- }
-}
-
-type causer interface {
- Cause() error
-}
-
-func formatErrorMessage(err error) string {
- //nolint:errorlint // unwrapping is not appropriate here
- if _, ok := err.(causer); ok {
- return fmt.Sprintf("%q\n%+v", err, err)
- }
- // This error was not wrapped with github.com/pkg/errors
- return fmt.Sprintf("%q", err)
-}
-
-// Nil succeeds if obj is a nil interface, pointer, or function.
-//
-// Use [gotest.tools/v3/assert.NilError] for comparing errors. Use Len(obj, 0) for comparing slices,
-// maps, and channels.
-func Nil(obj interface{}) Comparison {
- msgFunc := func(value reflect.Value) string {
- return fmt.Sprintf("%v (type %s) is not nil", reflect.Indirect(value), value.Type())
- }
- return isNil(obj, msgFunc)
-}
-
-func isNil(obj interface{}, msgFunc func(reflect.Value) string) Comparison {
- return func() Result {
- if obj == nil {
- return ResultSuccess
- }
- value := reflect.ValueOf(obj)
- kind := value.Type().Kind()
- if kind >= reflect.Chan && kind <= reflect.Slice {
- if value.IsNil() {
- return ResultSuccess
- }
- return ResultFailure(msgFunc(value))
- }
-
- return ResultFailure(fmt.Sprintf("%v (type %s) can not be nil", value, value.Type()))
- }
-}
-
-// ErrorType succeeds if err is not nil and is of the expected type.
-//
-// Expected can be one of:
-//
-// func(error) bool
-//
-// Function should return true if the error is the expected type.
-//
-// type struct{}, type &struct{}
-//
-// A struct or a pointer to a struct.
-// Fails if the error is not of the same type as expected.
-//
-// type &interface{}
-//
-// A pointer to an interface type.
-// Fails if err does not implement the interface.
-//
-// reflect.Type
-//
-// Fails if err does not implement the [reflect.Type].
-//
-// Deprecated: Use [ErrorIs]
-func ErrorType(err error, expected interface{}) Comparison {
- return func() Result {
- switch expectedType := expected.(type) {
- case func(error) bool:
- return cmpErrorTypeFunc(err, expectedType)
- case reflect.Type:
- if expectedType.Kind() == reflect.Interface {
- return cmpErrorTypeImplementsType(err, expectedType)
- }
- return cmpErrorTypeEqualType(err, expectedType)
- case nil:
- return ResultFailure("invalid type for expected: nil")
- }
-
- expectedType := reflect.TypeOf(expected)
- switch {
- case expectedType.Kind() == reflect.Struct, isPtrToStruct(expectedType):
- return cmpErrorTypeEqualType(err, expectedType)
- case isPtrToInterface(expectedType):
- return cmpErrorTypeImplementsType(err, expectedType.Elem())
- }
- return ResultFailure(fmt.Sprintf("invalid type for expected: %T", expected))
- }
-}
-
-func cmpErrorTypeFunc(err error, f func(error) bool) Result {
- if f(err) {
- return ResultSuccess
- }
- actual := "nil"
- if err != nil {
- actual = fmt.Sprintf("%s (%T)", err, err)
- }
- return ResultFailureTemplate(`error is {{ .Data.actual }}
- {{- with callArg 1 }}, not {{ formatNode . }}{{end -}}`,
- map[string]interface{}{"actual": actual})
-}
-
-func cmpErrorTypeEqualType(err error, expectedType reflect.Type) Result {
- if err == nil {
- return ResultFailure(fmt.Sprintf("error is nil, not %s", expectedType))
- }
- errValue := reflect.ValueOf(err)
- if errValue.Type() == expectedType {
- return ResultSuccess
- }
- return ResultFailure(fmt.Sprintf("error is %s (%T), not %s", err, err, expectedType))
-}
-
-func cmpErrorTypeImplementsType(err error, expectedType reflect.Type) Result {
- if err == nil {
- return ResultFailure(fmt.Sprintf("error is nil, not %s", expectedType))
- }
- errValue := reflect.ValueOf(err)
- if errValue.Type().Implements(expectedType) {
- return ResultSuccess
- }
- return ResultFailure(fmt.Sprintf("error is %s (%T), not %s", err, err, expectedType))
-}
-
-func isPtrToInterface(typ reflect.Type) bool {
- return typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Interface
-}
-
-func isPtrToStruct(typ reflect.Type) bool {
- return typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct
-}
-
-var (
- stdlibErrorNewType = reflect.TypeOf(errors.New(""))
- stdlibFmtErrorType = reflect.TypeOf(fmt.Errorf("%w", fmt.Errorf("")))
-)
-
-// ErrorIs succeeds if errors.Is(actual, expected) returns true. See
-// [errors.Is] for accepted argument values.
-func ErrorIs(actual error, expected error) Comparison {
- return func() Result {
- if errors.Is(actual, expected) {
- return ResultSuccess
- }
-
- // The type of stdlib errors is excluded because the type is not relevant
- // in those cases. The type is only important when it is a user defined
- // custom error type.
- return ResultFailureTemplate(`error is
- {{- if not .Data.a }} nil,{{ else }}
- {{- printf " \"%v\"" .Data.a }}
- {{- if notStdlibErrorType .Data.a }} ({{ printf "%T" .Data.a }}){{ end }},
- {{- end }} not {{ printf "\"%v\"" .Data.x }} (
- {{- with callArg 1 }}{{ formatNode . }}{{ end }}
- {{- if notStdlibErrorType .Data.x }}{{ printf " %T" .Data.x }}{{ end }})`,
- map[string]interface{}{"a": actual, "x": expected})
- }
-}
diff --git a/vendor/gotest.tools/v3/assert/cmp/result.go b/vendor/gotest.tools/v3/assert/cmp/result.go
deleted file mode 100644
index 9992ede..0000000
--- a/vendor/gotest.tools/v3/assert/cmp/result.go
+++ /dev/null
@@ -1,110 +0,0 @@
-package cmp
-
-import (
- "bytes"
- "fmt"
- "go/ast"
- "reflect"
- "text/template"
-
- "gotest.tools/v3/internal/source"
-)
-
-// A Result of a [Comparison].
-type Result interface {
- Success() bool
-}
-
-// StringResult is an implementation of [Result] that reports the error message
-// string verbatim and does not provide any templating or formatting of the
-// message.
-type StringResult struct {
- success bool
- message string
-}
-
-// Success returns true if the comparison was successful.
-func (r StringResult) Success() bool {
- return r.success
-}
-
-// FailureMessage returns the message used to provide additional information
-// about the failure.
-func (r StringResult) FailureMessage() string {
- return r.message
-}
-
-// ResultSuccess is a constant which is returned by a [Comparison] to
-// indicate success.
-var ResultSuccess = StringResult{success: true}
-
-// ResultFailure returns a failed [Result] with a failure message.
-func ResultFailure(message string) StringResult {
- return StringResult{message: message}
-}
-
-// ResultFromError returns [ResultSuccess] if err is nil. Otherwise [ResultFailure]
-// is returned with the error message as the failure message.
-func ResultFromError(err error) Result {
- if err == nil {
- return ResultSuccess
- }
- return ResultFailure(err.Error())
-}
-
-type templatedResult struct {
- template string
- data map[string]interface{}
-}
-
-func (r templatedResult) Success() bool {
- return false
-}
-
-func (r templatedResult) FailureMessage(args []ast.Expr) string {
- msg, err := renderMessage(r, args)
- if err != nil {
- return fmt.Sprintf("failed to render failure message: %s", err)
- }
- return msg
-}
-
-func (r templatedResult) UpdatedExpected(stackIndex int) error {
- // TODO: would be nice to have structured data instead of a map
- return source.UpdateExpectedValue(stackIndex+1, r.data["x"], r.data["y"])
-}
-
-// ResultFailureTemplate returns a [Result] with a template string and data which
-// can be used to format a failure message. The template may access data from .Data,
-// the comparison args with the callArg function, and the formatNode function may
-// be used to format the call args.
-func ResultFailureTemplate(template string, data map[string]interface{}) Result {
- return templatedResult{template: template, data: data}
-}
-
-func renderMessage(result templatedResult, args []ast.Expr) (string, error) {
- tmpl := template.New("failure").Funcs(template.FuncMap{
- "formatNode": source.FormatNode,
- "callArg": func(index int) ast.Expr {
- if index >= len(args) {
- return nil
- }
- return args[index]
- },
- // TODO: any way to include this from ErrorIS instead of here?
- "notStdlibErrorType": func(typ interface{}) bool {
- r := reflect.TypeOf(typ)
- return r != stdlibFmtErrorType && r != stdlibErrorNewType
- },
- })
- var err error
- tmpl, err = tmpl.Parse(result.template)
- if err != nil {
- return "", err
- }
- buf := new(bytes.Buffer)
- err = tmpl.Execute(buf, map[string]interface{}{
- "Data": result.data,
- })
- return buf.String(), err
-}
diff --git a/vendor/gotest.tools/v3/internal/assert/assert.go b/vendor/gotest.tools/v3/internal/assert/assert.go
deleted file mode 100644
index 2dd8025..0000000
--- a/vendor/gotest.tools/v3/internal/assert/assert.go
+++ /dev/null
@@ -1,161 +0,0 @@
-// Package assert provides internal utilties for assertions.
-package assert
-
-import (
- "fmt"
- "go/ast"
- "go/token"
- "reflect"
-
- "gotest.tools/v3/assert/cmp"
- "gotest.tools/v3/internal/format"
- "gotest.tools/v3/internal/source"
-)
-
-// LogT is the subset of testing.T used by the assert package.
-type LogT interface {
- Log(args ...interface{})
-}
-
-type helperT interface {
- Helper()
-}
-
-const failureMessage = "assertion failed: "
-
-// Eval the comparison and print a failure messages if the comparison has failed.
-func Eval(
- t LogT,
- argSelector argSelector,
- comparison interface{},
- msgAndArgs ...interface{},
-) bool {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- var success bool
- switch check := comparison.(type) {
- case bool:
- if check {
- return true
- }
- logFailureFromBool(t, msgAndArgs...)
-
- // Undocumented legacy comparison without Result type
- case func() (success bool, message string):
- success = runCompareFunc(t, check, msgAndArgs...)
-
- case nil:
- return true
-
- case error:
- msg := failureMsgFromError(check)
- t.Log(format.WithCustomMessage(failureMessage+msg, msgAndArgs...))
-
- case cmp.Comparison:
- success = RunComparison(t, argSelector, check, msgAndArgs...)
-
- case func() cmp.Result:
- success = RunComparison(t, argSelector, check, msgAndArgs...)
-
- default:
- t.Log(fmt.Sprintf("invalid Comparison: %v (%T)", check, check))
- }
- return success
-}
-
-func runCompareFunc(
- t LogT,
- f func() (success bool, message string),
- msgAndArgs ...interface{},
-) bool {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- if success, message := f(); !success {
- t.Log(format.WithCustomMessage(failureMessage+message, msgAndArgs...))
- return false
- }
- return true
-}
-
-func logFailureFromBool(t LogT, msgAndArgs ...interface{}) {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- const stackIndex = 3 // Assert()/Check(), assert(), logFailureFromBool()
- args, err := source.CallExprArgs(stackIndex)
- if err != nil {
- t.Log(err.Error())
- return
- }
-
- const comparisonArgIndex = 1 // Assert(t, comparison)
- if len(args) <= comparisonArgIndex {
- t.Log(failureMessage + "but assert failed to find the expression to print")
- return
- }
-
- msg, err := boolFailureMessage(args[comparisonArgIndex])
- if err != nil {
- t.Log(err.Error())
- msg = "expression is false"
- }
-
- t.Log(format.WithCustomMessage(failureMessage+msg, msgAndArgs...))
-}
-
-func failureMsgFromError(err error) string {
- // Handle errors with non-nil types
- v := reflect.ValueOf(err)
- if v.Kind() == reflect.Ptr && v.IsNil() {
- return fmt.Sprintf("error is not nil: error has type %T", err)
- }
- return "error is not nil: " + err.Error()
-}
-
-func boolFailureMessage(expr ast.Expr) (string, error) {
- if binaryExpr, ok := expr.(*ast.BinaryExpr); ok {
- x, err := source.FormatNode(binaryExpr.X)
- if err != nil {
- return "", err
- }
- y, err := source.FormatNode(binaryExpr.Y)
- if err != nil {
- return "", err
- }
-
- switch binaryExpr.Op {
- case token.NEQ:
- return x + " is " + y, nil
- case token.EQL:
- return x + " is not " + y, nil
- case token.GTR:
- return x + " is <= " + y, nil
- case token.LSS:
- return x + " is >= " + y, nil
- case token.GEQ:
- return x + " is less than " + y, nil
- case token.LEQ:
- return x + " is greater than " + y, nil
- }
- }
-
- if unaryExpr, ok := expr.(*ast.UnaryExpr); ok && unaryExpr.Op == token.NOT {
- x, err := source.FormatNode(unaryExpr.X)
- if err != nil {
- return "", err
- }
- return x + " is true", nil
- }
-
- if ident, ok := expr.(*ast.Ident); ok {
- return ident.Name + " is false", nil
- }
-
- formatted, err := source.FormatNode(expr)
- if err != nil {
- return "", err
- }
- return "expression is false: " + formatted, nil
-}
diff --git a/vendor/gotest.tools/v3/internal/assert/result.go b/vendor/gotest.tools/v3/internal/assert/result.go
deleted file mode 100644
index bb8741e..0000000
--- a/vendor/gotest.tools/v3/internal/assert/result.go
+++ /dev/null
@@ -1,146 +0,0 @@
-package assert
-
-import (
- "errors"
- "fmt"
- "go/ast"
-
- "gotest.tools/v3/assert/cmp"
- "gotest.tools/v3/internal/format"
- "gotest.tools/v3/internal/source"
-)
-
-// RunComparison and return Comparison.Success. If the comparison fails a messages
-// will be printed using t.Log.
-func RunComparison(
- t LogT,
- argSelector argSelector,
- f cmp.Comparison,
- msgAndArgs ...interface{},
-) bool {
- if ht, ok := t.(helperT); ok {
- ht.Helper()
- }
- result := f()
- if result.Success() {
- return true
- }
-
- if source.IsUpdate() {
- if updater, ok := result.(updateExpected); ok {
- const stackIndex = 3 // Assert/Check, assert, RunComparison
- err := updater.UpdatedExpected(stackIndex)
- switch {
- case err == nil:
- return true
- case errors.Is(err, source.ErrNotFound):
- // do nothing, fallthrough to regular failure message
- default:
- t.Log("failed to update source", err)
- return false
- }
- }
- }
-
- var message string
- switch typed := result.(type) {
- case resultWithComparisonArgs:
- const stackIndex = 3 // Assert/Check, assert, RunComparison
- args, err := source.CallExprArgs(stackIndex)
- if err != nil {
- t.Log(err.Error())
- }
- message = typed.FailureMessage(filterPrintableExpr(argSelector(args)))
- case resultBasic:
- message = typed.FailureMessage()
- default:
- message = fmt.Sprintf("comparison returned invalid Result type: %T", result)
- }
-
- t.Log(format.WithCustomMessage(failureMessage+message, msgAndArgs...))
- return false
-}
-
-type resultWithComparisonArgs interface {
- FailureMessage(args []ast.Expr) string
-}
-
-type resultBasic interface {
- FailureMessage() string
-}
-
-type updateExpected interface {
- UpdatedExpected(stackIndex int) error
-}
-
-// filterPrintableExpr filters the ast.Expr slice to only include Expr that are
-// easy to read when printed and contain relevant information to an assertion.
-//
-// Ident and SelectorExpr are included because they print nicely and the variable
-// names may provide additional context to their values.
-// BasicLit and CompositeLit are excluded because their source is equivalent to
-// their value, which is already available.
-// Other types are ignored for now, but could be added if they are relevant.
-func filterPrintableExpr(args []ast.Expr) []ast.Expr {
- result := make([]ast.Expr, len(args))
- for i, arg := range args {
- if isShortPrintableExpr(arg) {
- result[i] = arg
- continue
- }
-
- if starExpr, ok := arg.(*ast.StarExpr); ok {
- result[i] = starExpr.X
- continue
- }
- }
- return result
-}
-
-func isShortPrintableExpr(expr ast.Expr) bool {
- switch expr.(type) {
- case *ast.Ident, *ast.SelectorExpr, *ast.IndexExpr, *ast.SliceExpr:
- return true
- case *ast.BinaryExpr, *ast.UnaryExpr:
- return true
- default:
- // CallExpr, ParenExpr, TypeAssertExpr, KeyValueExpr, StarExpr
- return false
- }
-}
-
-type argSelector func([]ast.Expr) []ast.Expr
-
-// ArgsAfterT selects args starting at position 1. Used when the caller has a
-// testing.T as the first argument, and the args to select should follow it.
-func ArgsAfterT(args []ast.Expr) []ast.Expr {
- if len(args) < 1 {
- return nil
- }
- return args[1:]
-}
-
-// ArgsFromComparisonCall selects args from the CallExpression at position 1.
-// Used when the caller has a testing.T as the first argument, and the args to
-// select are passed to the cmp.Comparison at position 1.
-func ArgsFromComparisonCall(args []ast.Expr) []ast.Expr {
- if len(args) <= 1 {
- return nil
- }
- if callExpr, ok := args[1].(*ast.CallExpr); ok {
- return callExpr.Args
- }
- return nil
-}
-
-// ArgsAtZeroIndex selects args from the CallExpression at position 1.
-// Used when the caller accepts a single cmp.Comparison argument.
-func ArgsAtZeroIndex(args []ast.Expr) []ast.Expr {
- if len(args) == 0 {
- return nil
- }
- if callExpr, ok := args[0].(*ast.CallExpr); ok {
- return callExpr.Args
- }
- return nil
-}
diff --git a/vendor/gotest.tools/v3/internal/difflib/LICENSE b/vendor/gotest.tools/v3/internal/difflib/LICENSE
deleted file mode 100644
index c67dad6..0000000
--- a/vendor/gotest.tools/v3/internal/difflib/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2013, Patrick Mezard
-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.
- The names of its contributors may not be used to endorse or promote
-products derived from this software without specific prior written
-permission.
-
-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/gotest.tools/v3/internal/difflib/difflib.go b/vendor/gotest.tools/v3/internal/difflib/difflib.go
deleted file mode 100644
index 9bf506b..0000000
--- a/vendor/gotest.tools/v3/internal/difflib/difflib.go
+++ /dev/null
@@ -1,423 +0,0 @@
-/*Package difflib is a partial port of Python difflib module.
-
-Original source: https://github.com/pmezard/go-difflib
-
-This file is trimmed to only the parts used by this repository.
-*/
-package difflib // import "gotest.tools/v3/internal/difflib"
-
-func min(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
-
-func max(a, b int) int {
- if a > b {
- return a
- }
- return b
-}
-
-// Match stores line numbers of size of match
-type Match struct {
- A int
- B int
- Size int
-}
-
-// OpCode identifies the type of diff
-type OpCode struct {
- Tag byte
- I1 int
- I2 int
- J1 int
- J2 int
-}
-
-// SequenceMatcher compares sequence of strings. The basic
-// algorithm predates, and is a little fancier than, an algorithm
-// published in the late 1980's by Ratcliff and Obershelp under the
-// hyperbolic name "gestalt pattern matching". The basic idea is to find
-// the longest contiguous matching subsequence that contains no "junk"
-// elements (R-O doesn't address junk). The same idea is then applied
-// recursively to the pieces of the sequences to the left and to the right
-// of the matching subsequence. This does not yield minimal edit
-// sequences, but does tend to yield matches that "look right" to people.
-//
-// SequenceMatcher tries to compute a "human-friendly diff" between two
-// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
-// longest *contiguous* & junk-free matching subsequence. That's what
-// catches peoples' eyes. The Windows(tm) windiff has another interesting
-// notion, pairing up elements that appear uniquely in each sequence.
-// That, and the method here, appear to yield more intuitive difference
-// reports than does diff. This method appears to be the least vulnerable
-// to synching up on blocks of "junk lines", though (like blank lines in
-// ordinary text files, or maybe "<P>" lines in HTML files). That may be
-// because this is the only method of the 3 that has a *concept* of
-// "junk" <wink>.
-//
-// Timing: Basic R-O is cubic time worst case and quadratic time expected
-// case. SequenceMatcher is quadratic time for the worst case and has
-// expected-case behavior dependent in a complicated way on how many
-// elements the sequences have in common; best case time is linear.
-type SequenceMatcher struct {
- a []string
- b []string
- b2j map[string][]int
- IsJunk func(string) bool
- autoJunk bool
- bJunk map[string]struct{}
- matchingBlocks []Match
- fullBCount map[string]int
- bPopular map[string]struct{}
- opCodes []OpCode
-}
-
-// NewMatcher returns a new SequenceMatcher
-func NewMatcher(a, b []string) *SequenceMatcher {
- m := SequenceMatcher{autoJunk: true}
- m.SetSeqs(a, b)
- return &m
-}
-
-// SetSeqs sets two sequences to be compared.
-func (m *SequenceMatcher) SetSeqs(a, b []string) {
- m.SetSeq1(a)
- m.SetSeq2(b)
-}
-
-// SetSeq1 sets the first sequence to be compared. The second sequence to be compared is
-// not changed.
-//
-// SequenceMatcher computes and caches detailed information about the second
-// sequence, so if you want to compare one sequence S against many sequences,
-// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
-// sequences.
-//
-// See also SetSeqs() and SetSeq2().
-func (m *SequenceMatcher) SetSeq1(a []string) {
- if &a == &m.a {
- return
- }
- m.a = a
- m.matchingBlocks = nil
- m.opCodes = nil
-}
-
-// SetSeq2 sets the second sequence to be compared. The first sequence to be compared is
-// not changed.
-func (m *SequenceMatcher) SetSeq2(b []string) {
- if &b == &m.b {
- return
- }
- m.b = b
- m.matchingBlocks = nil
- m.opCodes = nil
- m.fullBCount = nil
- m.chainB()
-}
-
-func (m *SequenceMatcher) chainB() {
- // Populate line -> index mapping
- b2j := map[string][]int{}
- for i, s := range m.b {
- indices := b2j[s]
- indices = append(indices, i)
- b2j[s] = indices
- }
-
- // Purge junk elements
- m.bJunk = map[string]struct{}{}
- if m.IsJunk != nil {
- junk := m.bJunk
- for s := range b2j {
- if m.IsJunk(s) {
- junk[s] = struct{}{}
- }
- }
- for s := range junk {
- delete(b2j, s)
- }
- }
-
- // Purge remaining popular elements
- popular := map[string]struct{}{}
- n := len(m.b)
- if m.autoJunk && n >= 200 {
- ntest := n/100 + 1
- for s, indices := range b2j {
- if len(indices) > ntest {
- popular[s] = struct{}{}
- }
- }
- for s := range popular {
- delete(b2j, s)
- }
- }
- m.bPopular = popular
- m.b2j = b2j
-}
-
-func (m *SequenceMatcher) isBJunk(s string) bool {
- _, ok := m.bJunk[s]
- return ok
-}
-
-// Find longest matching block in a[alo:ahi] and b[blo:bhi].
-//
-// If IsJunk is not defined:
-//
-// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
-// alo <= i <= i+k <= ahi
-// blo <= j <= j+k <= bhi
-// and for all (i',j',k') meeting those conditions,
-// k >= k'
-// i <= i'
-// and if i == i', j <= j'
-//
-// In other words, of all maximal matching blocks, return one that
-// starts earliest in a, and of all those maximal matching blocks that
-// start earliest in a, return the one that starts earliest in b.
-//
-// If IsJunk is defined, first the longest matching block is
-// determined as above, but with the additional restriction that no
-// junk element appears in the block. Then that block is extended as
-// far as possible by matching (only) junk elements on both sides. So
-// the resulting block never matches on junk except as identical junk
-// happens to be adjacent to an "interesting" match.
-//
-// If no blocks match, return (alo, blo, 0).
-func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
- // CAUTION: stripping common prefix or suffix would be incorrect.
- // E.g.,
- // ab
- // acab
- // Longest matching block is "ab", but if common prefix is
- // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
- // strip, so ends up claiming that ab is changed to acab by
- // inserting "ca" in the middle. That's minimal but unintuitive:
- // "it's obvious" that someone inserted "ac" at the front.
- // Windiff ends up at the same place as diff, but by pairing up
- // the unique 'b's and then matching the first two 'a's.
- besti, bestj, bestsize := alo, blo, 0
-
- // find longest junk-free match
- // during an iteration of the loop, j2len[j] = length of longest
- // junk-free match ending with a[i-1] and b[j]
- j2len := map[int]int{}
- for i := alo; i != ahi; i++ {
- // look at all instances of a[i] in b; note that because
- // b2j has no junk keys, the loop is skipped if a[i] is junk
- newj2len := map[int]int{}
- for _, j := range m.b2j[m.a[i]] {
- // a[i] matches b[j]
- if j < blo {
- continue
- }
- if j >= bhi {
- break
- }
- k := j2len[j-1] + 1
- newj2len[j] = k
- if k > bestsize {
- besti, bestj, bestsize = i-k+1, j-k+1, k
- }
- }
- j2len = newj2len
- }
-
- // Extend the best by non-junk elements on each end. In particular,
- // "popular" non-junk elements aren't in b2j, which greatly speeds
- // the inner loop above, but also means "the best" match so far
- // doesn't contain any junk *or* popular non-junk elements.
- for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
- m.a[besti-1] == m.b[bestj-1] {
- besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
- }
- for besti+bestsize < ahi && bestj+bestsize < bhi &&
- !m.isBJunk(m.b[bestj+bestsize]) &&
- m.a[besti+bestsize] == m.b[bestj+bestsize] {
- bestsize += 1
- }
-
- // Now that we have a wholly interesting match (albeit possibly
- // empty!), we may as well suck up the matching junk on each
- // side of it too. Can't think of a good reason not to, and it
- // saves post-processing the (possibly considerable) expense of
- // figuring out what to do with it. In the case of an empty
- // interesting match, this is clearly the right thing to do,
- // because no other kind of match is possible in the regions.
- for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
- m.a[besti-1] == m.b[bestj-1] {
- besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
- }
- for besti+bestsize < ahi && bestj+bestsize < bhi &&
- m.isBJunk(m.b[bestj+bestsize]) &&
- m.a[besti+bestsize] == m.b[bestj+bestsize] {
- bestsize += 1
- }
-
- return Match{A: besti, B: bestj, Size: bestsize}
-}
-
-// GetMatchingBlocks returns a list of triples describing matching subsequences.
-//
-// Each triple is of the form (i, j, n), and means that
-// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
-// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
-// adjacent triples in the list, and the second is not the last triple in the
-// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
-// adjacent equal blocks.
-//
-// The last triple is a dummy, (len(a), len(b), 0), and is the only
-// triple with n==0.
-func (m *SequenceMatcher) GetMatchingBlocks() []Match {
- if m.matchingBlocks != nil {
- return m.matchingBlocks
- }
-
- var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
- matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
- match := m.findLongestMatch(alo, ahi, blo, bhi)
- i, j, k := match.A, match.B, match.Size
- if match.Size > 0 {
- if alo < i && blo < j {
- matched = matchBlocks(alo, i, blo, j, matched)
- }
- matched = append(matched, match)
- if i+k < ahi && j+k < bhi {
- matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
- }
- }
- return matched
- }
- matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
-
- // It's possible that we have adjacent equal blocks in the
- // matching_blocks list now.
- nonAdjacent := []Match{}
- i1, j1, k1 := 0, 0, 0
- for _, b := range matched {
- // Is this block adjacent to i1, j1, k1?
- i2, j2, k2 := b.A, b.B, b.Size
- if i1+k1 == i2 && j1+k1 == j2 {
- // Yes, so collapse them -- this just increases the length of
- // the first block by the length of the second, and the first
- // block so lengthened remains the block to compare against.
- k1 += k2
- } else {
- // Not adjacent. Remember the first block (k1==0 means it's
- // the dummy we started with), and make the second block the
- // new block to compare against.
- if k1 > 0 {
- nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
- }
- i1, j1, k1 = i2, j2, k2
- }
- }
- if k1 > 0 {
- nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
- }
-
- nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
- m.matchingBlocks = nonAdjacent
- return m.matchingBlocks
-}
-
-// GetOpCodes returns a list of 5-tuples describing how to turn a into b.
-//
-// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
-// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
-// tuple preceding it, and likewise for j1 == the previous j2.
-//
-// The tags are characters, with these meanings:
-//
-// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
-//
-// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
-//
-// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
-//
-// 'e' (equal): a[i1:i2] == b[j1:j2]
-func (m *SequenceMatcher) GetOpCodes() []OpCode {
- if m.opCodes != nil {
- return m.opCodes
- }
- i, j := 0, 0
- matching := m.GetMatchingBlocks()
- opCodes := make([]OpCode, 0, len(matching))
- for _, m := range matching {
- // invariant: we've pumped out correct diffs to change
- // a[:i] into b[:j], and the next matching block is
- // a[ai:ai+size] == b[bj:bj+size]. So we need to pump
- // out a diff to change a[i:ai] into b[j:bj], pump out
- // the matching block, and move (i,j) beyond the match
- ai, bj, size := m.A, m.B, m.Size
- tag := byte(0)
- if i < ai && j < bj {
- tag = 'r'
- } else if i < ai {
- tag = 'd'
- } else if j < bj {
- tag = 'i'
- }
- if tag > 0 {
- opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
- }
- i, j = ai+size, bj+size
- // the list of matching blocks is terminated by a
- // sentinel with size 0
- if size > 0 {
- opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
- }
- }
- m.opCodes = opCodes
- return m.opCodes
-}
-
-// GetGroupedOpCodes isolates change clusters by eliminating ranges with no changes.
-//
-// Return a generator of groups with up to n lines of context.
-// Each group is in the same format as returned by GetOpCodes().
-func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
- if n < 0 {
- n = 3
- }
- codes := m.GetOpCodes()
- if len(codes) == 0 {
- codes = []OpCode{{'e', 0, 1, 0, 1}}
- }
- // Fixup leading and trailing groups if they show no changes.
- if codes[0].Tag == 'e' {
- c := codes[0]
- i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
- codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
- }
- if codes[len(codes)-1].Tag == 'e' {
- c := codes[len(codes)-1]
- i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
- codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
- }
- nn := n + n
- groups := [][]OpCode{}
- group := []OpCode{}
- for _, c := range codes {
- i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
- // End the current group and start a new one whenever
- // there is a large range with no changes.
- if c.Tag == 'e' && i2-i1 > nn {
- group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
- j1, min(j2, j1+n)})
- groups = append(groups, group)
- group = []OpCode{}
- i1, j1 = max(i1, i2-n), max(j1, j2-n)
- }
- group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
- }
- if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
- groups = append(groups, group)
- }
- return groups
-}
diff --git a/vendor/gotest.tools/v3/internal/format/diff.go b/vendor/gotest.tools/v3/internal/format/diff.go
deleted file mode 100644
index 4f6c07a..0000000
--- a/vendor/gotest.tools/v3/internal/format/diff.go
+++ /dev/null
@@ -1,162 +0,0 @@
-// Package format provides utilities for formatting diffs and messages.
-package format
-
-import (
- "bytes"
- "fmt"
- "strings"
- "unicode"
-
- "gotest.tools/v3/internal/difflib"
-)
-
-const (
- contextLines = 2
-)
-
-// DiffConfig for a unified diff
-type DiffConfig struct {
- A string
- B string
- From string
- To string
-}
-
-// UnifiedDiff is a modified version of difflib.WriteUnifiedDiff with better
-// support for showing the whitespace differences.
-func UnifiedDiff(conf DiffConfig) string {
- a := strings.SplitAfter(conf.A, "\n")
- b := strings.SplitAfter(conf.B, "\n")
- groups := difflib.NewMatcher(a, b).GetGroupedOpCodes(contextLines)
- if len(groups) == 0 {
- return ""
- }
-
- buf := new(bytes.Buffer)
- writeFormat := func(format string, args ...interface{}) {
- buf.WriteString(fmt.Sprintf(format, args...))
- }
- writeLine := func(prefix string, s string) {
- buf.WriteString(prefix + s)
- }
- if hasWhitespaceDiffLines(groups, a, b) {
- writeLine = visibleWhitespaceLine(writeLine)
- }
- formatHeader(writeFormat, conf)
- for _, group := range groups {
- formatRangeLine(writeFormat, group)
- for _, opCode := range group {
- in, out := a[opCode.I1:opCode.I2], b[opCode.J1:opCode.J2]
- switch opCode.Tag {
- case 'e':
- formatLines(writeLine, " ", in)
- case 'r':
- formatLines(writeLine, "-", in)
- formatLines(writeLine, "+", out)
- case 'd':
- formatLines(writeLine, "-", in)
- case 'i':
- formatLines(writeLine, "+", out)
- }
- }
- }
- return buf.String()
-}
-
-// hasWhitespaceDiffLines returns true if any diff groups is only different
-// because of whitespace characters.
-func hasWhitespaceDiffLines(groups [][]difflib.OpCode, a, b []string) bool {
- for _, group := range groups {
- in, out := new(bytes.Buffer), new(bytes.Buffer)
- for _, opCode := range group {
- if opCode.Tag == 'e' {
- continue
- }
- for _, line := range a[opCode.I1:opCode.I2] {
- in.WriteString(line)
- }
- for _, line := range b[opCode.J1:opCode.J2] {
- out.WriteString(line)
- }
- }
- if removeWhitespace(in.String()) == removeWhitespace(out.String()) {
- return true
- }
- }
- return false
-}
-
-func removeWhitespace(s string) string {
- var result []rune
- for _, r := range s {
- if !unicode.IsSpace(r) {
- result = append(result, r)
- }
- }
- return string(result)
-}
-
-func visibleWhitespaceLine(ws func(string, string)) func(string, string) {
- mapToVisibleSpace := func(r rune) rune {
- switch r {
- case '\n':
- case ' ':
- return '·'
- case '\t':
- return '▷'
- case '\v':
- return '▽'
- case '\r':
- return '↵'
- case '\f':
- return '↓'
- default:
- if unicode.IsSpace(r) {
- return '�'
- }
- }
- return r
- }
- return func(prefix, s string) {
- ws(prefix, strings.Map(mapToVisibleSpace, s))
- }
-}
-
-func formatHeader(wf func(string, ...interface{}), conf DiffConfig) {
- if conf.From != "" || conf.To != "" {
- wf("--- %s\n", conf.From)
- wf("+++ %s\n", conf.To)
- }
-}
-
-func formatRangeLine(wf func(string, ...interface{}), group []difflib.OpCode) {
- first, last := group[0], group[len(group)-1]
- range1 := formatRangeUnified(first.I1, last.I2)
- range2 := formatRangeUnified(first.J1, last.J2)
- wf("@@ -%s +%s @@\n", range1, range2)
-}
-
-// Convert range to the "ed" format
-func formatRangeUnified(start, stop int) string {
- // Per the diff spec at http://www.unix.org/single_unix_specification/
- beginning := start + 1 // lines start numbering with one
- length := stop - start
- if length == 1 {
- return fmt.Sprintf("%d", beginning)
- }
- if length == 0 {
- beginning-- // empty ranges begin at line just before the range
- }
- return fmt.Sprintf("%d,%d", beginning, length)
-}
-
-func formatLines(writeLine func(string, string), prefix string, lines []string) {
- for _, line := range lines {
- writeLine(prefix, line)
- }
- // Add a newline if the last line is missing one so that the diff displays
- // properly.
- if !strings.HasSuffix(lines[len(lines)-1], "\n") {
- writeLine("", "\n")
- }
-}
diff --git a/vendor/gotest.tools/v3/internal/format/format.go b/vendor/gotest.tools/v3/internal/format/format.go
deleted file mode 100644
index 5097e4b..0000000
--- a/vendor/gotest.tools/v3/internal/format/format.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package format // import "gotest.tools/v3/internal/format"
-
-import "fmt"
-
-// Message accepts a msgAndArgs varargs and formats it using fmt.Sprintf
-func Message(msgAndArgs ...interface{}) string {
- switch len(msgAndArgs) {
- case 0:
- return ""
- case 1:
- return fmt.Sprintf("%v", msgAndArgs[0])
- default:
- return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
- }
-}
-
-// WithCustomMessage accepts one or two messages and formats them appropriately
-func WithCustomMessage(source string, msgAndArgs ...interface{}) string {
- custom := Message(msgAndArgs...)
- switch {
- case custom == "":
- return source
- case source == "":
- return custom
- }
- return fmt.Sprintf("%s: %s", source, custom)
-}
diff --git a/vendor/gotest.tools/v3/internal/source/defers.go b/vendor/gotest.tools/v3/internal/source/defers.go
deleted file mode 100644
index 392d9fe..0000000
--- a/vendor/gotest.tools/v3/internal/source/defers.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package source
-
-import (
- "fmt"
- "go/ast"
- "go/token"
-)
-
-func scanToDeferLine(fileset *token.FileSet, node ast.Node, lineNum int) ast.Node {
- var matchedNode ast.Node
- ast.Inspect(node, func(node ast.Node) bool {
- switch {
- case node == nil || matchedNode != nil:
- return false
- case fileset.Position(node.End()).Line == lineNum:
- if funcLit, ok := node.(*ast.FuncLit); ok {
- matchedNode = funcLit
- return false
- }
- }
- return true
- })
- debug("defer line node: %s", debugFormatNode{matchedNode})
- return matchedNode
-}
-
-func guessDefer(node ast.Node) (ast.Node, error) {
- defers := collectDefers(node)
- switch len(defers) {
- case 0:
- return nil, fmt.Errorf("failed to find expression in defer")
- case 1:
- return defers[0].Call, nil
- default:
- return nil, fmt.Errorf(
- "ambiguous call expression: multiple (%d) defers in call block",
- len(defers))
- }
-}
-
-func collectDefers(node ast.Node) []*ast.DeferStmt {
- var defers []*ast.DeferStmt
- ast.Inspect(node, func(node ast.Node) bool {
- if d, ok := node.(*ast.DeferStmt); ok {
- defers = append(defers, d)
- debug("defer: %s", debugFormatNode{d})
- return false
- }
- return true
- })
- return defers
-}
diff --git a/vendor/gotest.tools/v3/internal/source/source.go b/vendor/gotest.tools/v3/internal/source/source.go
deleted file mode 100644
index a4fc24e..0000000
--- a/vendor/gotest.tools/v3/internal/source/source.go
+++ /dev/null
@@ -1,148 +0,0 @@
-// Package source provides utilities for handling source-code.
-package source // import "gotest.tools/v3/internal/source"
-
-import (
- "bytes"
- "errors"
- "fmt"
- "go/ast"
- "go/format"
- "go/parser"
- "go/token"
- "os"
- "runtime"
-)
-
-// FormattedCallExprArg returns the argument from an ast.CallExpr at the
-// index in the call stack. The argument is formatted using FormatNode.
-func FormattedCallExprArg(stackIndex int, argPos int) (string, error) {
- args, err := CallExprArgs(stackIndex + 1)
- if err != nil {
- return "", err
- }
- if argPos >= len(args) {
- return "", errors.New("failed to find expression")
- }
- return FormatNode(args[argPos])
-}
-
-// CallExprArgs returns the ast.Expr slice for the args of an ast.CallExpr at
-// the index in the call stack.
-func CallExprArgs(stackIndex int) ([]ast.Expr, error) {
- _, filename, line, ok := runtime.Caller(stackIndex + 1)
- if !ok {
- return nil, errors.New("failed to get call stack")
- }
- debug("call stack position: %s:%d", filename, line)
-
- fileset := token.NewFileSet()
- astFile, err := parser.ParseFile(fileset, filename, nil, parser.AllErrors)
- if err != nil {
- return nil, fmt.Errorf("failed to parse source file %s: %w", filename, err)
- }
-
- expr, err := getCallExprArgs(fileset, astFile, line)
- if err != nil {
- return nil, fmt.Errorf("call from %s:%d: %w", filename, line, err)
- }
- return expr, nil
-}
-
-func getNodeAtLine(fileset *token.FileSet, astFile ast.Node, lineNum int) (ast.Node, error) {
- if node := scanToLine(fileset, astFile, lineNum); node != nil {
- return node, nil
- }
- if node := scanToDeferLine(fileset, astFile, lineNum); node != nil {
- node, err := guessDefer(node)
- if err != nil || node != nil {
- return node, err
- }
- }
- return nil, nil
-}
-
-func scanToLine(fileset *token.FileSet, node ast.Node, lineNum int) ast.Node {
- var matchedNode ast.Node
- ast.Inspect(node, func(node ast.Node) bool {
- switch {
- case node == nil || matchedNode != nil:
- return false
- case fileset.Position(node.Pos()).Line == lineNum:
- matchedNode = node
- return false
- }
- return true
- })
- return matchedNode
-}
-
-func getCallExprArgs(fileset *token.FileSet, astFile ast.Node, line int) ([]ast.Expr, error) {
- node, err := getNodeAtLine(fileset, astFile, line)
- switch {
- case err != nil:
- return nil, err
- case node == nil:
- return nil, fmt.Errorf("failed to find an expression")
- }
-
- debug("found node: %s", debugFormatNode{node})
-
- visitor := &callExprVisitor{}
- ast.Walk(visitor, node)
- if visitor.expr == nil {
- return nil, errors.New("failed to find call expression")
- }
- debug("callExpr: %s", debugFormatNode{visitor.expr})
- return visitor.expr.Args, nil
-}
-
-type callExprVisitor struct {
- expr *ast.CallExpr
-}
-
-func (v *callExprVisitor) Visit(node ast.Node) ast.Visitor {
- if v.expr != nil || node == nil {
- return nil
- }
- debug("visit: %s", debugFormatNode{node})
-
- switch typed := node.(type) {
- case *ast.CallExpr:
- v.expr = typed
- return nil
- case *ast.DeferStmt:
- ast.Walk(v, typed.Call.Fun)
- return nil
- }
- return v
-}
-
-// FormatNode using go/format.Node and return the result as a string
-func FormatNode(node ast.Node) (string, error) {
- buf := new(bytes.Buffer)
- err := format.Node(buf, token.NewFileSet(), node)
- return buf.String(), err
-}
-
-var debugEnabled = os.Getenv("GOTESTTOOLS_DEBUG") != ""
-
-func debug(format string, args ...interface{}) {
- if debugEnabled {
- fmt.Fprintf(os.Stderr, "DEBUG: "+format+"\n", args...)
- }
-}
-
-type debugFormatNode struct {
- ast.Node
-}
-
-func (n debugFormatNode) String() string {
- if n.Node == nil {
- return "none"
- }
- out, err := FormatNode(n.Node)
- if err != nil {
- return fmt.Sprintf("failed to format %s: %s", n.Node, err)
- }
- return fmt.Sprintf("(%T) %s", n.Node, out)
-}
diff --git a/vendor/gotest.tools/v3/internal/source/update.go b/vendor/gotest.tools/v3/internal/source/update.go
deleted file mode 100644
index 5591bff..0000000
--- a/vendor/gotest.tools/v3/internal/source/update.go
+++ /dev/null
@@ -1,171 +0,0 @@
-package source
-
-import (
- "bytes"
- "errors"
- "flag"
- "fmt"
- "go/ast"
- "go/format"
- "go/parser"
- "go/token"
- "os"
- "runtime"
- "strings"
-)
-
-// IsUpdate is returns true if the -update flag is set. It indicates the user
-// running the tests would like to update any golden values.
-func IsUpdate() bool {
- if Update {
- return true
- }
- return flag.Lookup("update").Value.(flag.Getter).Get().(bool)
-}
-
-// Update is a shim for testing, and for compatibility with the old -update-golden
-// flag.
-var Update bool
-
-func init() {
- if f := flag.Lookup("update"); f != nil {
- getter, ok := f.Value.(flag.Getter)
- msg := "some other package defined an incompatible -update flag, expected a flag.Bool"
- if !ok {
- panic(msg)
- }
- if _, ok := getter.Get().(bool); !ok {
- panic(msg)
- }
- return
- }
- flag.Bool("update", false, "update golden values")
-}
-
-// ErrNotFound indicates that UpdateExpectedValue failed to find the
-// variable to update, likely because it is not a package level variable.
-var ErrNotFound = fmt.Errorf("failed to find variable for update of golden value")
-
-// UpdateExpectedValue looks for a package-level variable with a name that
-// starts with expected in the arguments to the caller. If the variable is
-// found, the value of the variable will be updated to value of the other
-// argument to the caller.
-func UpdateExpectedValue(stackIndex int, x, y interface{}) error {
- _, filename, line, ok := runtime.Caller(stackIndex + 1)
- if !ok {
- return errors.New("failed to get call stack")
- }
- debug("call stack position: %s:%d", filename, line)
-
- fileset := token.NewFileSet()
- astFile, err := parser.ParseFile(fileset, filename, nil, parser.AllErrors|parser.ParseComments)
- if err != nil {
- return fmt.Errorf("failed to parse source file %s: %w", filename, err)
- }
-
- expr, err := getCallExprArgs(fileset, astFile, line)
- if err != nil {
- return fmt.Errorf("call from %s:%d: %w", filename, line, err)
- }
-
- if len(expr) < 3 {
- debug("not enough arguments %d: %v",
- len(expr), debugFormatNode{Node: &ast.CallExpr{Args: expr}})
- return ErrNotFound
- }
-
- argIndex, ident := getIdentForExpectedValueArg(expr)
- if argIndex < 0 || ident == nil {
- debug("no arguments started with the word 'expected': %v",
- debugFormatNode{Node: &ast.CallExpr{Args: expr}})
- return ErrNotFound
- }
-
- value := x
- if argIndex == 1 {
- value = y
- }
-
- strValue, ok := value.(string)
- if !ok {
- debug("value must be type string, got %T", value)
- return ErrNotFound
- }
- return UpdateVariable(filename, fileset, astFile, ident, strValue)
-}
-
-// UpdateVariable writes to filename the contents of astFile with the value of
-// the variable updated to value.
-func UpdateVariable(
- filename string,
- fileset *token.FileSet,
- astFile *ast.File,
- ident *ast.Ident,
- value string,
-) error {
- obj := ident.Obj
- if obj == nil {
- return ErrNotFound
- }
- if obj.Kind != ast.Con && obj.Kind != ast.Var {
- debug("can only update var and const, found %v", obj.Kind)
- return ErrNotFound
- }
-
- switch decl := obj.Decl.(type) {
- case *ast.ValueSpec:
- if len(decl.Names) != 1 {
- debug("more than one name in ast.ValueSpec")
- return ErrNotFound
- }
-
- decl.Values[0] = &ast.BasicLit{
- Kind: token.STRING,
- Value: "`" + value + "`",
- }
-
- case *ast.AssignStmt:
- if len(decl.Lhs) != 1 {
- debug("more than one name in ast.AssignStmt")
- return ErrNotFound
- }
-
- decl.Rhs[0] = &ast.BasicLit{
- Kind: token.STRING,
- Value: "`" + value + "`",
- }
-
- default:
- debug("can only update *ast.ValueSpec, found %T", obj.Decl)
- return ErrNotFound
- }
-
- var buf bytes.Buffer
- if err := format.Node(&buf, fileset, astFile); err != nil {
- return fmt.Errorf("failed to format file after update: %w", err)
- }
-
- fh, err := os.Create(filename)
- if err != nil {
- return fmt.Errorf("failed to open file %v: %w", filename, err)
- }
- if _, err = fh.Write(buf.Bytes()); err != nil {
- return fmt.Errorf("failed to write file %v: %w", filename, err)
- }
- if err := fh.Sync(); err != nil {
- return fmt.Errorf("failed to sync file %v: %w", filename, err)
- }
- return nil
-}
-
-func getIdentForExpectedValueArg(expr []ast.Expr) (int, *ast.Ident) {
- for i := 1; i < 3; i++ {
- switch e := expr[i].(type) {
- case *ast.Ident:
- if strings.HasPrefix(strings.ToLower(e.Name), "expected") {
- return i, e
- }
- }
- }
- return -1, nil
-}
diff --git a/vendor/gotest.tools/v3/internal/source/version.go b/vendor/gotest.tools/v3/internal/source/version.go
deleted file mode 100644
index 5fa8a90..0000000
--- a/vendor/gotest.tools/v3/internal/source/version.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package source
-
-import (
- "runtime"
- "strconv"
- "strings"
-)
-
-// GoVersionLessThan returns true if runtime.Version() is semantically less than
-// version major.minor. Returns false if a release version can not be parsed from
-// runtime.Version().
-func GoVersionLessThan(major, minor int64) bool {
- version := runtime.Version()
- // not a release version
- if !strings.HasPrefix(version, "go") {
- return false
- }
- version = strings.TrimPrefix(version, "go")
- parts := strings.Split(version, ".")
- if len(parts) < 2 {
- return false
- }
- rMajor, err := strconv.ParseInt(parts[0], 10, 32)
- if err != nil {
- return false
- }
- if rMajor != major {
- return rMajor < major
- }
- rMinor, err := strconv.ParseInt(parts[1], 10, 32)
- if err != nil {
- return false
- }
- return rMinor < minor
-}
diff --git a/vendor/modules.txt b/vendor/modules.txt
deleted file mode 100644
index dc538c6..0000000
--- a/vendor/modules.txt
+++ /dev/null
@@ -1,30 +0,0 @@
-# github.com/BurntSushi/toml v1.3.2
-## explicit; go 1.16
-github.com/BurntSushi/toml
-github.com/BurntSushi/toml/internal
-# github.com/google/go-cmp v0.5.9
-## explicit; go 1.13
-github.com/google/go-cmp/cmp
-github.com/google/go-cmp/cmp/internal/diff
-github.com/google/go-cmp/cmp/internal/flags
-github.com/google/go-cmp/cmp/internal/function
-github.com/google/go-cmp/cmp/internal/value
-# github.com/google/subcommands v1.2.0
-## explicit
-github.com/google/subcommands
-# github.com/kelseyhightower/envconfig v1.4.0
-## explicit
-github.com/kelseyhightower/envconfig
-# github.com/lib/pq v1.10.9
-## explicit; go 1.13
-github.com/lib/pq
-github.com/lib/pq/oid
-github.com/lib/pq/scram
-# gotest.tools/v3 v3.5.1
-## explicit; go 1.17
-gotest.tools/v3/assert
-gotest.tools/v3/assert/cmp
-gotest.tools/v3/internal/assert
-gotest.tools/v3/internal/difflib
-gotest.tools/v3/internal/format
-gotest.tools/v3/internal/source