. Either ShortName or LongName needs
- // to be non-empty.
- LongName string
-
- // The default value of the option.
- Default []string
-
- // The optional environment default value key name.
- EnvDefaultKey string
-
- // The optional delimiter string for EnvDefaultKey values.
- EnvDefaultDelim string
-
- // If true, specifies that the argument to an option flag is optional.
- // When no argument to the flag is specified on the command line, the
- // value of OptionalValue will be set in the field this option represents.
- // This is only valid for non-boolean options.
- OptionalArgument bool
-
- // The optional value of the option. The optional value is used when
- // the option flag is marked as having an OptionalArgument. This means
- // that when the flag is specified, but no option argument is given,
- // the value of the field this option represents will be set to
- // OptionalValue. This is only valid for non-boolean options.
- OptionalValue []string
-
- // If true, the option _must_ be specified on the command line. If the
- // option is not specified, the parser will generate an ErrRequired type
- // error.
- Required bool
-
- // A name for the value of an option shown in the Help as --flag [ValueName]
- ValueName string
-
- // A mask value to show in the help instead of the default value. This
- // is useful for hiding sensitive information in the help, such as
- // passwords.
- DefaultMask string
-
- // If non empty, only a certain set of values is allowed for an option.
- Choices []string
-
- // If true, the option is not displayed in the help or man page
- Hidden bool
-
- // The group which the option belongs to
- group *Group
-
- // The struct field which the option represents.
- field reflect.StructField
-
- // The struct field value which the option represents.
- value reflect.Value
-
- // Determines if the option will be always quoted in the INI output
- iniQuote bool
-
- tag multiTag
- isSet bool
- isSetDefault bool
- preventDefault bool
-
- defaultLiteral string
-}
-
-// LongNameWithNamespace returns the option's long name with the group namespaces
-// prepended by walking up the option's group tree. Namespaces and the long name
-// itself are separated by the parser's namespace delimiter. If the long name is
-// empty an empty string is returned.
-func (option *Option) LongNameWithNamespace() string {
- if len(option.LongName) == 0 {
- return ""
- }
-
- // fetch the namespace delimiter from the parser which is always at the
- // end of the group hierarchy
- namespaceDelimiter := ""
- g := option.group
-
- for {
- if p, ok := g.parent.(*Parser); ok {
- namespaceDelimiter = p.NamespaceDelimiter
-
- break
- }
-
- switch i := g.parent.(type) {
- case *Command:
- g = i.Group
- case *Group:
- g = i
- }
- }
-
- // concatenate long name with namespace
- longName := option.LongName
- g = option.group
-
- for g != nil {
- if g.Namespace != "" {
- longName = g.Namespace + namespaceDelimiter + longName
- }
-
- switch i := g.parent.(type) {
- case *Command:
- g = i.Group
- case *Group:
- g = i
- case *Parser:
- g = nil
- }
- }
-
- return longName
-}
-
-// String converts an option to a human friendly readable string describing the
-// option.
-func (option *Option) String() string {
- var s string
- var short string
-
- if option.ShortName != 0 {
- data := make([]byte, utf8.RuneLen(option.ShortName))
- utf8.EncodeRune(data, option.ShortName)
- short = string(data)
-
- if len(option.LongName) != 0 {
- s = fmt.Sprintf("%s%s, %s%s",
- string(defaultShortOptDelimiter), short,
- defaultLongOptDelimiter, option.LongNameWithNamespace())
- } else {
- s = fmt.Sprintf("%s%s", string(defaultShortOptDelimiter), short)
- }
- } else if len(option.LongName) != 0 {
- s = fmt.Sprintf("%s%s", defaultLongOptDelimiter, option.LongNameWithNamespace())
- }
-
- return s
-}
-
-// Value returns the option value as an interface{}.
-func (option *Option) Value() interface{} {
- return option.value.Interface()
-}
-
-// Field returns the reflect struct field of the option.
-func (option *Option) Field() reflect.StructField {
- return option.field
-}
-
-// IsSet returns true if option has been set
-func (option *Option) IsSet() bool {
- return option.isSet
-}
-
-// IsSetDefault returns true if option has been set via the default option tag
-func (option *Option) IsSetDefault() bool {
- return option.isSetDefault
-}
-
-// Set the value of an option to the specified value. An error will be returned
-// if the specified value could not be converted to the corresponding option
-// value type.
-func (option *Option) set(value *string) error {
- kind := option.value.Type().Kind()
-
- if (kind == reflect.Map || kind == reflect.Slice) && !option.isSet {
- option.empty()
- }
-
- option.isSet = true
- option.preventDefault = true
-
- if len(option.Choices) != 0 {
- found := false
-
- for _, choice := range option.Choices {
- if choice == *value {
- found = true
- break
- }
- }
-
- if !found {
- allowed := strings.Join(option.Choices[0:len(option.Choices)-1], ", ")
-
- if len(option.Choices) > 1 {
- allowed += " or " + option.Choices[len(option.Choices)-1]
- }
-
- return newErrorf(ErrInvalidChoice,
- "Invalid value `%s' for option `%s'. Allowed values are: %s",
- *value, option, allowed)
- }
- }
-
- if option.isFunc() {
- return option.call(value)
- } else if value != nil {
- return convert(*value, option.value, option.tag)
- }
-
- return convert("", option.value, option.tag)
-}
-
-func (option *Option) canCli() bool {
- return option.ShortName != 0 || len(option.LongName) != 0
-}
-
-func (option *Option) canArgument() bool {
- if u := option.isUnmarshaler(); u != nil {
- return true
- }
-
- return !option.isBool()
-}
-
-func (option *Option) emptyValue() reflect.Value {
- tp := option.value.Type()
-
- if tp.Kind() == reflect.Map {
- return reflect.MakeMap(tp)
- }
-
- return reflect.Zero(tp)
-}
-
-func (option *Option) empty() {
- if !option.isFunc() {
- option.value.Set(option.emptyValue())
- }
-}
-
-func (option *Option) clearDefault() {
- usedDefault := option.Default
-
- if envKey := option.EnvDefaultKey; envKey != "" {
- if value, ok := os.LookupEnv(envKey); ok {
- if option.EnvDefaultDelim != "" {
- usedDefault = strings.Split(value,
- option.EnvDefaultDelim)
- } else {
- usedDefault = []string{value}
- }
- }
- }
-
- option.isSetDefault = true
-
- if len(usedDefault) > 0 {
- option.empty()
-
- for _, d := range usedDefault {
- option.set(&d)
- option.isSetDefault = true
- }
- } else {
- tp := option.value.Type()
-
- switch tp.Kind() {
- case reflect.Map:
- if option.value.IsNil() {
- option.empty()
- }
- case reflect.Slice:
- if option.value.IsNil() {
- option.empty()
- }
- }
- }
-}
-
-func (option *Option) valueIsDefault() bool {
- // Check if the value of the option corresponds to its
- // default value
- emptyval := option.emptyValue()
-
- checkvalptr := reflect.New(emptyval.Type())
- checkval := reflect.Indirect(checkvalptr)
-
- checkval.Set(emptyval)
-
- if len(option.Default) != 0 {
- for _, v := range option.Default {
- convert(v, checkval, option.tag)
- }
- }
-
- return reflect.DeepEqual(option.value.Interface(), checkval.Interface())
-}
-
-func (option *Option) isUnmarshaler() Unmarshaler {
- v := option.value
-
- for {
- if !v.CanInterface() {
- break
- }
-
- i := v.Interface()
-
- if u, ok := i.(Unmarshaler); ok {
- return u
- }
-
- if !v.CanAddr() {
- break
- }
-
- v = v.Addr()
- }
-
- return nil
-}
-
-func (option *Option) isBool() bool {
- tp := option.value.Type()
-
- for {
- switch tp.Kind() {
- case reflect.Slice, reflect.Ptr:
- tp = tp.Elem()
- case reflect.Bool:
- return true
- case reflect.Func:
- return tp.NumIn() == 0
- default:
- return false
- }
- }
-}
-
-func (option *Option) isSignedNumber() bool {
- tp := option.value.Type()
-
- for {
- switch tp.Kind() {
- case reflect.Slice, reflect.Ptr:
- tp = tp.Elem()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float32, reflect.Float64:
- return true
- default:
- return false
- }
- }
-}
-
-func (option *Option) isFunc() bool {
- return option.value.Type().Kind() == reflect.Func
-}
-
-func (option *Option) call(value *string) error {
- var retval []reflect.Value
-
- if value == nil {
- retval = option.value.Call(nil)
- } else {
- tp := option.value.Type().In(0)
-
- val := reflect.New(tp)
- val = reflect.Indirect(val)
-
- if err := convert(*value, val, option.tag); err != nil {
- return err
- }
-
- retval = option.value.Call([]reflect.Value{val})
- }
-
- if len(retval) == 1 && retval[0].Type() == reflect.TypeOf((*error)(nil)).Elem() {
- if retval[0].Interface() == nil {
- return nil
- }
-
- return retval[0].Interface().(error)
- }
-
- return nil
-}
-
-func (option *Option) updateDefaultLiteral() {
- defs := option.Default
- def := ""
-
- if len(defs) == 0 && option.canArgument() {
- var showdef bool
-
- switch option.field.Type.Kind() {
- case reflect.Func, reflect.Ptr:
- showdef = !option.value.IsNil()
- case reflect.Slice, reflect.String, reflect.Array:
- showdef = option.value.Len() > 0
- case reflect.Map:
- showdef = !option.value.IsNil() && option.value.Len() > 0
- default:
- zeroval := reflect.Zero(option.field.Type)
- showdef = !reflect.DeepEqual(zeroval.Interface(), option.value.Interface())
- }
-
- if showdef {
- def, _ = convertToString(option.value, option.tag)
- }
- } else if len(defs) != 0 {
- l := len(defs) - 1
-
- for i := 0; i < l; i++ {
- def += quoteIfNeeded(defs[i]) + ", "
- }
-
- def += quoteIfNeeded(defs[l])
- }
-
- option.defaultLiteral = def
-}
-
-func (option *Option) shortAndLongName() string {
- ret := &bytes.Buffer{}
-
- if option.ShortName != 0 {
- ret.WriteRune(defaultShortOptDelimiter)
- ret.WriteRune(option.ShortName)
- }
-
- if len(option.LongName) != 0 {
- if option.ShortName != 0 {
- ret.WriteRune('/')
- }
-
- ret.WriteString(option.LongName)
- }
-
- return ret.String()
-}
diff --git a/vendor/github.com/jessevdk/go-flags/optstyle_other.go b/vendor/github.com/jessevdk/go-flags/optstyle_other.go
deleted file mode 100644
index 56dfdae1..00000000
--- a/vendor/github.com/jessevdk/go-flags/optstyle_other.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// +build !windows forceposix
-
-package flags
-
-import (
- "strings"
-)
-
-const (
- defaultShortOptDelimiter = '-'
- defaultLongOptDelimiter = "--"
- defaultNameArgDelimiter = '='
-)
-
-func argumentStartsOption(arg string) bool {
- return len(arg) > 0 && arg[0] == '-'
-}
-
-func argumentIsOption(arg string) bool {
- if len(arg) > 1 && arg[0] == '-' && arg[1] != '-' {
- return true
- }
-
- if len(arg) > 2 && arg[0] == '-' && arg[1] == '-' && arg[2] != '-' {
- return true
- }
-
- return false
-}
-
-// stripOptionPrefix returns the option without the prefix and whether or
-// not the option is a long option or not.
-func stripOptionPrefix(optname string) (prefix string, name string, islong bool) {
- if strings.HasPrefix(optname, "--") {
- return "--", optname[2:], true
- } else if strings.HasPrefix(optname, "-") {
- return "-", optname[1:], false
- }
-
- return "", optname, false
-}
-
-// splitOption attempts to split the passed option into a name and an argument.
-// When there is no argument specified, nil will be returned for it.
-func splitOption(prefix string, option string, islong bool) (string, string, *string) {
- pos := strings.Index(option, "=")
-
- if (islong && pos >= 0) || (!islong && pos == 1) {
- rest := option[pos+1:]
- return option[:pos], "=", &rest
- }
-
- return option, "", nil
-}
-
-// addHelpGroup adds a new group that contains default help parameters.
-func (c *Command) addHelpGroup(showHelp func() error) *Group {
- var help struct {
- ShowHelp func() error `short:"h" long:"help" description:"Show this help message"`
- }
-
- help.ShowHelp = showHelp
- ret, _ := c.AddGroup("Help Options", "", &help)
- ret.isBuiltinHelp = true
-
- return ret
-}
diff --git a/vendor/github.com/jessevdk/go-flags/optstyle_windows.go b/vendor/github.com/jessevdk/go-flags/optstyle_windows.go
deleted file mode 100644
index f3f28aee..00000000
--- a/vendor/github.com/jessevdk/go-flags/optstyle_windows.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// +build !forceposix
-
-package flags
-
-import (
- "strings"
-)
-
-// Windows uses a front slash for both short and long options. Also it uses
-// a colon for name/argument delimter.
-const (
- defaultShortOptDelimiter = '/'
- defaultLongOptDelimiter = "/"
- defaultNameArgDelimiter = ':'
-)
-
-func argumentStartsOption(arg string) bool {
- return len(arg) > 0 && (arg[0] == '-' || arg[0] == '/')
-}
-
-func argumentIsOption(arg string) bool {
- // Windows-style options allow front slash for the option
- // delimiter.
- if len(arg) > 1 && arg[0] == '/' {
- return true
- }
-
- if len(arg) > 1 && arg[0] == '-' && arg[1] != '-' {
- return true
- }
-
- if len(arg) > 2 && arg[0] == '-' && arg[1] == '-' && arg[2] != '-' {
- return true
- }
-
- return false
-}
-
-// stripOptionPrefix returns the option without the prefix and whether or
-// not the option is a long option or not.
-func stripOptionPrefix(optname string) (prefix string, name string, islong bool) {
- // Determine if the argument is a long option or not. Windows
- // typically supports both long and short options with a single
- // front slash as the option delimiter, so handle this situation
- // nicely.
- possplit := 0
-
- if strings.HasPrefix(optname, "--") {
- possplit = 2
- islong = true
- } else if strings.HasPrefix(optname, "-") {
- possplit = 1
- islong = false
- } else if strings.HasPrefix(optname, "/") {
- possplit = 1
- islong = len(optname) > 2
- }
-
- return optname[:possplit], optname[possplit:], islong
-}
-
-// splitOption attempts to split the passed option into a name and an argument.
-// When there is no argument specified, nil will be returned for it.
-func splitOption(prefix string, option string, islong bool) (string, string, *string) {
- if len(option) == 0 {
- return option, "", nil
- }
-
- // Windows typically uses a colon for the option name and argument
- // delimiter while POSIX typically uses an equals. Support both styles,
- // but don't allow the two to be mixed. That is to say /foo:bar and
- // --foo=bar are acceptable, but /foo=bar and --foo:bar are not.
- var pos int
- var sp string
-
- if prefix == "/" {
- sp = ":"
- pos = strings.Index(option, sp)
- } else if len(prefix) > 0 {
- sp = "="
- pos = strings.Index(option, sp)
- }
-
- if (islong && pos >= 0) || (!islong && pos == 1) {
- rest := option[pos+1:]
- return option[:pos], sp, &rest
- }
-
- return option, "", nil
-}
-
-// addHelpGroup adds a new group that contains default help parameters.
-func (c *Command) addHelpGroup(showHelp func() error) *Group {
- // Windows CLI applications typically use /? for help, so make both
- // that available as well as the POSIX style h and help.
- var help struct {
- ShowHelpWindows func() error `short:"?" description:"Show this help message"`
- ShowHelpPosix func() error `short:"h" long:"help" description:"Show this help message"`
- }
-
- help.ShowHelpWindows = showHelp
- help.ShowHelpPosix = showHelp
-
- ret, _ := c.AddGroup("Help Options", "", &help)
- ret.isBuiltinHelp = true
-
- return ret
-}
diff --git a/vendor/github.com/jessevdk/go-flags/parser.go b/vendor/github.com/jessevdk/go-flags/parser.go
deleted file mode 100644
index 0a7922a0..00000000
--- a/vendor/github.com/jessevdk/go-flags/parser.go
+++ /dev/null
@@ -1,700 +0,0 @@
-// Copyright 2012 Jesse van den Kieboom. 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
-
-import (
- "bytes"
- "fmt"
- "os"
- "path"
- "sort"
- "strings"
- "unicode/utf8"
-)
-
-// A Parser provides command line option parsing. It can contain several
-// option groups each with their own set of options.
-type Parser struct {
- // Embedded, see Command for more information
- *Command
-
- // A usage string to be displayed in the help message.
- Usage string
-
- // Option flags changing the behavior of the parser.
- Options Options
-
- // NamespaceDelimiter separates group namespaces and option long names
- NamespaceDelimiter string
-
- // UnknownOptionsHandler is a function which gets called when the parser
- // encounters an unknown option. The function receives the unknown option
- // name, a SplitArgument which specifies its value if set with an argument
- // separator, and the remaining command line arguments.
- // It should return a new list of remaining arguments to continue parsing,
- // or an error to indicate a parse failure.
- UnknownOptionHandler func(option string, arg SplitArgument, args []string) ([]string, error)
-
- // CompletionHandler is a function gets called to handle the completion of
- // items. By default, the items are printed and the application is exited.
- // You can override this default behavior by specifying a custom CompletionHandler.
- CompletionHandler func(items []Completion)
-
- // CommandHandler is a function that gets called to handle execution of a
- // command. By default, the command will simply be executed. This can be
- // overridden to perform certain actions (such as applying global flags)
- // just before the command is executed. Note that if you override the
- // handler it is your responsibility to call the command.Execute function.
- //
- // The command passed into CommandHandler may be nil in case there is no
- // command to be executed when parsing has finished.
- CommandHandler func(command Commander, args []string) error
-
- internalError error
-}
-
-// SplitArgument represents the argument value of an option that was passed using
-// an argument separator.
-type SplitArgument interface {
- // String returns the option's value as a string, and a boolean indicating
- // if the option was present.
- Value() (string, bool)
-}
-
-type strArgument struct {
- value *string
-}
-
-func (s strArgument) Value() (string, bool) {
- if s.value == nil {
- return "", false
- }
-
- return *s.value, true
-}
-
-// Options provides parser options that change the behavior of the option
-// parser.
-type Options uint
-
-const (
- // None indicates no options.
- None Options = 0
-
- // HelpFlag adds a default Help Options group to the parser containing
- // -h and --help options. When either -h or --help is specified on the
- // command line, the parser will return the special error of type
- // ErrHelp. When PrintErrors is also specified, then the help message
- // will also be automatically printed to os.Stdout.
- HelpFlag = 1 << iota
-
- // PassDoubleDash passes all arguments after a double dash, --, as
- // remaining command line arguments (i.e. they will not be parsed for
- // flags).
- PassDoubleDash
-
- // IgnoreUnknown ignores any unknown options and passes them as
- // remaining command line arguments instead of generating an error.
- IgnoreUnknown
-
- // PrintErrors prints any errors which occurred during parsing to
- // os.Stderr. In the special case of ErrHelp, the message will be printed
- // to os.Stdout.
- PrintErrors
-
- // PassAfterNonOption passes all arguments after the first non option
- // as remaining command line arguments. This is equivalent to strict
- // POSIX processing.
- PassAfterNonOption
-
- // Default is a convenient default set of options which should cover
- // most of the uses of the flags package.
- Default = HelpFlag | PrintErrors | PassDoubleDash
-)
-
-type parseState struct {
- arg string
- args []string
- retargs []string
- positional []*Arg
- err error
-
- command *Command
- lookup lookup
-}
-
-// Parse is a convenience function to parse command line options with default
-// settings. The provided data is a pointer to a struct representing the
-// default option group (named "Application Options"). For more control, use
-// flags.NewParser.
-func Parse(data interface{}) ([]string, error) {
- return NewParser(data, Default).Parse()
-}
-
-// ParseArgs is a convenience function to parse command line options with default
-// settings. The provided data is a pointer to a struct representing the
-// default option group (named "Application Options"). The args argument is
-// the list of command line arguments to parse. If you just want to parse the
-// default program command line arguments (i.e. os.Args), then use flags.Parse
-// instead. For more control, use flags.NewParser.
-func ParseArgs(data interface{}, args []string) ([]string, error) {
- return NewParser(data, Default).ParseArgs(args)
-}
-
-// NewParser creates a new parser. It uses os.Args[0] as the application
-// name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for
-// more details). The provided data is a pointer to a struct representing the
-// default option group (named "Application Options"), or nil if the default
-// group should not be added. The options parameter specifies a set of options
-// for the parser.
-func NewParser(data interface{}, options Options) *Parser {
- p := NewNamedParser(path.Base(os.Args[0]), options)
-
- if data != nil {
- g, err := p.AddGroup("Application Options", "", data)
-
- if err == nil {
- g.parent = p
- }
-
- p.internalError = err
- }
-
- return p
-}
-
-// NewNamedParser creates a new parser. The appname is used to display the
-// executable name in the built-in help message. Option groups and commands can
-// be added to this parser by using AddGroup and AddCommand.
-func NewNamedParser(appname string, options Options) *Parser {
- p := &Parser{
- Command: newCommand(appname, "", "", nil),
- Options: options,
- NamespaceDelimiter: ".",
- }
-
- p.Command.parent = p
-
- return p
-}
-
-// Parse parses the command line arguments from os.Args using Parser.ParseArgs.
-// For more detailed information see ParseArgs.
-func (p *Parser) Parse() ([]string, error) {
- return p.ParseArgs(os.Args[1:])
-}
-
-// ParseArgs parses the command line arguments according to the option groups that
-// were added to the parser. On successful parsing of the arguments, the
-// remaining, non-option, arguments (if any) are returned. The returned error
-// indicates a parsing error and can be used with PrintError to display
-// contextual information on where the error occurred exactly.
-//
-// When the common help group has been added (AddHelp) and either -h or --help
-// was specified in the command line arguments, a help message will be
-// automatically printed if the PrintErrors option is enabled.
-// Furthermore, the special error type ErrHelp is returned.
-// It is up to the caller to exit the program if so desired.
-func (p *Parser) ParseArgs(args []string) ([]string, error) {
- if p.internalError != nil {
- return nil, p.internalError
- }
-
- p.eachOption(func(c *Command, g *Group, option *Option) {
- option.isSet = false
- option.isSetDefault = false
- option.updateDefaultLiteral()
- })
-
- // Add built-in help group to all commands if necessary
- if (p.Options & HelpFlag) != None {
- p.addHelpGroups(p.showBuiltinHelp)
- }
-
- compval := os.Getenv("GO_FLAGS_COMPLETION")
-
- if len(compval) != 0 {
- comp := &completion{parser: p}
- items := comp.complete(args)
-
- if p.CompletionHandler != nil {
- p.CompletionHandler(items)
- } else {
- comp.print(items, compval == "verbose")
- os.Exit(0)
- }
-
- return nil, nil
- }
-
- s := &parseState{
- args: args,
- retargs: make([]string, 0, len(args)),
- }
-
- p.fillParseState(s)
-
- for !s.eof() {
- arg := s.pop()
-
- // When PassDoubleDash is set and we encounter a --, then
- // simply append all the rest as arguments and break out
- if (p.Options&PassDoubleDash) != None && arg == "--" {
- s.addArgs(s.args...)
- break
- }
-
- if !argumentIsOption(arg) {
- // Note: this also sets s.err, so we can just check for
- // nil here and use s.err later
- if p.parseNonOption(s) != nil {
- break
- }
-
- continue
- }
-
- var err error
-
- prefix, optname, islong := stripOptionPrefix(arg)
- optname, _, argument := splitOption(prefix, optname, islong)
-
- if islong {
- err = p.parseLong(s, optname, argument)
- } else {
- err = p.parseShort(s, optname, argument)
- }
-
- if err != nil {
- ignoreUnknown := (p.Options & IgnoreUnknown) != None
- parseErr := wrapError(err)
-
- if parseErr.Type != ErrUnknownFlag || (!ignoreUnknown && p.UnknownOptionHandler == nil) {
- s.err = parseErr
- break
- }
-
- if ignoreUnknown {
- s.addArgs(arg)
- } else if p.UnknownOptionHandler != nil {
- modifiedArgs, err := p.UnknownOptionHandler(optname, strArgument{argument}, s.args)
-
- if err != nil {
- s.err = err
- break
- }
-
- s.args = modifiedArgs
- }
- }
- }
-
- if s.err == nil {
- p.eachOption(func(c *Command, g *Group, option *Option) {
- if option.preventDefault {
- return
- }
-
- option.clearDefault()
- })
-
- s.checkRequired(p)
- }
-
- var reterr error
-
- if s.err != nil {
- reterr = s.err
- } else if len(s.command.commands) != 0 && !s.command.SubcommandsOptional {
- reterr = s.estimateCommand()
- } else if cmd, ok := s.command.data.(Commander); ok {
- if p.CommandHandler != nil {
- reterr = p.CommandHandler(cmd, s.retargs)
- } else {
- reterr = cmd.Execute(s.retargs)
- }
- } else if p.CommandHandler != nil {
- reterr = p.CommandHandler(nil, s.retargs)
- }
-
- if reterr != nil {
- var retargs []string
-
- if ourErr, ok := reterr.(*Error); !ok || ourErr.Type != ErrHelp {
- retargs = append([]string{s.arg}, s.args...)
- } else {
- retargs = s.args
- }
-
- return retargs, p.printError(reterr)
- }
-
- return s.retargs, nil
-}
-
-func (p *parseState) eof() bool {
- return len(p.args) == 0
-}
-
-func (p *parseState) pop() string {
- if p.eof() {
- return ""
- }
-
- p.arg = p.args[0]
- p.args = p.args[1:]
-
- return p.arg
-}
-
-func (p *parseState) peek() string {
- if p.eof() {
- return ""
- }
-
- return p.args[0]
-}
-
-func (p *parseState) checkRequired(parser *Parser) error {
- c := parser.Command
-
- var required []*Option
-
- for c != nil {
- c.eachGroup(func(g *Group) {
- for _, option := range g.options {
- if !option.isSet && option.Required {
- required = append(required, option)
- }
- }
- })
-
- c = c.Active
- }
-
- if len(required) == 0 {
- if len(p.positional) > 0 {
- var reqnames []string
-
- for _, arg := range p.positional {
- argRequired := (!arg.isRemaining() && p.command.ArgsRequired) || arg.Required != -1 || arg.RequiredMaximum != -1
-
- if !argRequired {
- continue
- }
-
- if arg.isRemaining() {
- if arg.value.Len() < arg.Required {
- var arguments string
-
- if arg.Required > 1 {
- arguments = "arguments, but got only " + fmt.Sprintf("%d", arg.value.Len())
- } else {
- arguments = "argument"
- }
-
- reqnames = append(reqnames, "`"+arg.Name+" (at least "+fmt.Sprintf("%d", arg.Required)+" "+arguments+")`")
- } else if arg.RequiredMaximum != -1 && arg.value.Len() > arg.RequiredMaximum {
- if arg.RequiredMaximum == 0 {
- reqnames = append(reqnames, "`"+arg.Name+" (zero arguments)`")
- } else {
- var arguments string
-
- if arg.RequiredMaximum > 1 {
- arguments = "arguments, but got " + fmt.Sprintf("%d", arg.value.Len())
- } else {
- arguments = "argument"
- }
-
- reqnames = append(reqnames, "`"+arg.Name+" (at most "+fmt.Sprintf("%d", arg.RequiredMaximum)+" "+arguments+")`")
- }
- }
- } else {
- reqnames = append(reqnames, "`"+arg.Name+"`")
- }
- }
-
- if len(reqnames) == 0 {
- return nil
- }
-
- var msg string
-
- if len(reqnames) == 1 {
- msg = fmt.Sprintf("the required argument %s was not provided", reqnames[0])
- } else {
- msg = fmt.Sprintf("the required arguments %s and %s were not provided",
- strings.Join(reqnames[:len(reqnames)-1], ", "), reqnames[len(reqnames)-1])
- }
-
- p.err = newError(ErrRequired, msg)
- return p.err
- }
-
- return nil
- }
-
- names := make([]string, 0, len(required))
-
- for _, k := range required {
- names = append(names, "`"+k.String()+"'")
- }
-
- sort.Strings(names)
-
- var msg string
-
- if len(names) == 1 {
- msg = fmt.Sprintf("the required flag %s was not specified", names[0])
- } else {
- msg = fmt.Sprintf("the required flags %s and %s were not specified",
- strings.Join(names[:len(names)-1], ", "), names[len(names)-1])
- }
-
- p.err = newError(ErrRequired, msg)
- return p.err
-}
-
-func (p *parseState) estimateCommand() error {
- commands := p.command.sortedVisibleCommands()
- cmdnames := make([]string, len(commands))
-
- for i, v := range commands {
- cmdnames[i] = v.Name
- }
-
- var msg string
- var errtype ErrorType
-
- if len(p.retargs) != 0 {
- c, l := closestChoice(p.retargs[0], cmdnames)
- msg = fmt.Sprintf("Unknown command `%s'", p.retargs[0])
- errtype = ErrUnknownCommand
-
- if float32(l)/float32(len(c)) < 0.5 {
- msg = fmt.Sprintf("%s, did you mean `%s'?", msg, c)
- } else if len(cmdnames) == 1 {
- msg = fmt.Sprintf("%s. You should use the %s command",
- msg,
- cmdnames[0])
- } else if len(cmdnames) > 1 {
- msg = fmt.Sprintf("%s. Please specify one command of: %s or %s",
- msg,
- strings.Join(cmdnames[:len(cmdnames)-1], ", "),
- cmdnames[len(cmdnames)-1])
- }
- } else {
- errtype = ErrCommandRequired
-
- if len(cmdnames) == 1 {
- msg = fmt.Sprintf("Please specify the %s command", cmdnames[0])
- } else if len(cmdnames) > 1 {
- msg = fmt.Sprintf("Please specify one command of: %s or %s",
- strings.Join(cmdnames[:len(cmdnames)-1], ", "),
- cmdnames[len(cmdnames)-1])
- }
- }
-
- return newError(errtype, msg)
-}
-
-func (p *Parser) parseOption(s *parseState, name string, option *Option, canarg bool, argument *string) (err error) {
- if !option.canArgument() {
- if argument != nil {
- return newErrorf(ErrNoArgumentForBool, "bool flag `%s' cannot have an argument", option)
- }
-
- err = option.set(nil)
- } else if argument != nil || (canarg && !s.eof()) {
- var arg string
-
- if argument != nil {
- arg = *argument
- } else {
- arg = s.pop()
-
- if argumentIsOption(arg) && !(option.isSignedNumber() && len(arg) > 1 && arg[0] == '-' && arg[1] >= '0' && arg[1] <= '9') {
- return newErrorf(ErrExpectedArgument, "expected argument for flag `%s', but got option `%s'", option, arg)
- } else if p.Options&PassDoubleDash != 0 && arg == "--" {
- return newErrorf(ErrExpectedArgument, "expected argument for flag `%s', but got double dash `--'", option)
- }
- }
-
- if option.tag.Get("unquote") != "false" {
- arg, err = unquoteIfPossible(arg)
- }
-
- if err == nil {
- err = option.set(&arg)
- }
- } else if option.OptionalArgument {
- option.empty()
-
- for _, v := range option.OptionalValue {
- err = option.set(&v)
-
- if err != nil {
- break
- }
- }
- } else {
- err = newErrorf(ErrExpectedArgument, "expected argument for flag `%s'", option)
- }
-
- if err != nil {
- if _, ok := err.(*Error); !ok {
- err = newErrorf(ErrMarshal, "invalid argument for flag `%s' (expected %s): %s",
- option,
- option.value.Type(),
- err.Error())
- }
- }
-
- return err
-}
-
-func (p *Parser) parseLong(s *parseState, name string, argument *string) error {
- if option := s.lookup.longNames[name]; option != nil {
- // Only long options that are required can consume an argument
- // from the argument list
- canarg := !option.OptionalArgument
-
- return p.parseOption(s, name, option, canarg, argument)
- }
-
- return newErrorf(ErrUnknownFlag, "unknown flag `%s'", name)
-}
-
-func (p *Parser) splitShortConcatArg(s *parseState, optname string) (string, *string) {
- c, n := utf8.DecodeRuneInString(optname)
-
- if n == len(optname) {
- return optname, nil
- }
-
- first := string(c)
-
- if option := s.lookup.shortNames[first]; option != nil && option.canArgument() {
- arg := optname[n:]
- return first, &arg
- }
-
- return optname, nil
-}
-
-func (p *Parser) parseShort(s *parseState, optname string, argument *string) error {
- if argument == nil {
- optname, argument = p.splitShortConcatArg(s, optname)
- }
-
- for i, c := range optname {
- shortname := string(c)
-
- if option := s.lookup.shortNames[shortname]; option != nil {
- // Only the last short argument can consume an argument from
- // the arguments list, and only if it's non optional
- canarg := (i+utf8.RuneLen(c) == len(optname)) && !option.OptionalArgument
-
- if err := p.parseOption(s, shortname, option, canarg, argument); err != nil {
- return err
- }
- } else {
- return newErrorf(ErrUnknownFlag, "unknown flag `%s'", shortname)
- }
-
- // Only the first option can have a concatted argument, so just
- // clear argument here
- argument = nil
- }
-
- return nil
-}
-
-func (p *parseState) addArgs(args ...string) error {
- for len(p.positional) > 0 && len(args) > 0 {
- arg := p.positional[0]
-
- if err := convert(args[0], arg.value, arg.tag); err != nil {
- p.err = err
- return err
- }
-
- if !arg.isRemaining() {
- p.positional = p.positional[1:]
- }
-
- args = args[1:]
- }
-
- p.retargs = append(p.retargs, args...)
- return nil
-}
-
-func (p *Parser) parseNonOption(s *parseState) error {
- if len(s.positional) > 0 {
- return s.addArgs(s.arg)
- }
-
- if len(s.command.commands) > 0 && len(s.retargs) == 0 {
- if cmd := s.lookup.commands[s.arg]; cmd != nil {
- s.command.Active = cmd
- cmd.fillParseState(s)
-
- return nil
- } else if !s.command.SubcommandsOptional {
- s.addArgs(s.arg)
- return newErrorf(ErrUnknownCommand, "Unknown command `%s'", s.arg)
- }
- }
-
- if (p.Options & PassAfterNonOption) != None {
- // If PassAfterNonOption is set then all remaining arguments
- // are considered positional
- if err := s.addArgs(s.arg); err != nil {
- return err
- }
-
- if err := s.addArgs(s.args...); err != nil {
- return err
- }
-
- s.args = []string{}
- } else {
- return s.addArgs(s.arg)
- }
-
- return nil
-}
-
-func (p *Parser) showBuiltinHelp() error {
- var b bytes.Buffer
-
- p.WriteHelp(&b)
- return newError(ErrHelp, b.String())
-}
-
-func (p *Parser) printError(err error) error {
- if err != nil && (p.Options&PrintErrors) != None {
- flagsErr, ok := err.(*Error)
-
- if ok && flagsErr.Type == ErrHelp {
- fmt.Fprintln(os.Stdout, err)
- } else {
- fmt.Fprintln(os.Stderr, err)
- }
- }
-
- return err
-}
-
-func (p *Parser) clearIsSet() {
- p.eachCommand(func(c *Command) {
- c.eachGroup(func(g *Group) {
- for _, option := range g.options {
- option.isSet = false
- }
- })
- }, true)
-}
diff --git a/vendor/github.com/jessevdk/go-flags/termsize.go b/vendor/github.com/jessevdk/go-flags/termsize.go
deleted file mode 100644
index 1ca6a850..00000000
--- a/vendor/github.com/jessevdk/go-flags/termsize.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// +build !windows,!plan9,!solaris,!appengine
-
-package flags
-
-import (
- "syscall"
- "unsafe"
-)
-
-type winsize struct {
- row, col uint16
- xpixel, ypixel uint16
-}
-
-func getTerminalColumns() int {
- ws := winsize{}
-
- if tIOCGWINSZ != 0 {
- syscall.Syscall(syscall.SYS_IOCTL,
- uintptr(0),
- uintptr(tIOCGWINSZ),
- uintptr(unsafe.Pointer(&ws)))
-
- return int(ws.col)
- }
-
- return 80
-}
diff --git a/vendor/github.com/jessevdk/go-flags/termsize_nosysioctl.go b/vendor/github.com/jessevdk/go-flags/termsize_nosysioctl.go
deleted file mode 100644
index 3d5385b0..00000000
--- a/vendor/github.com/jessevdk/go-flags/termsize_nosysioctl.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build windows plan9 solaris appengine
-
-package flags
-
-func getTerminalColumns() int {
- return 80
-}
diff --git a/vendor/github.com/jessevdk/go-flags/tiocgwinsz_bsdish.go b/vendor/github.com/jessevdk/go-flags/tiocgwinsz_bsdish.go
deleted file mode 100644
index fcc11860..00000000
--- a/vendor/github.com/jessevdk/go-flags/tiocgwinsz_bsdish.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build darwin freebsd netbsd openbsd
-
-package flags
-
-const (
- tIOCGWINSZ = 0x40087468
-)
diff --git a/vendor/github.com/jessevdk/go-flags/tiocgwinsz_linux.go b/vendor/github.com/jessevdk/go-flags/tiocgwinsz_linux.go
deleted file mode 100644
index e3975e28..00000000
--- a/vendor/github.com/jessevdk/go-flags/tiocgwinsz_linux.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build linux
-
-package flags
-
-const (
- tIOCGWINSZ = 0x5413
-)
diff --git a/vendor/github.com/jessevdk/go-flags/tiocgwinsz_other.go b/vendor/github.com/jessevdk/go-flags/tiocgwinsz_other.go
deleted file mode 100644
index 30821515..00000000
--- a/vendor/github.com/jessevdk/go-flags/tiocgwinsz_other.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build !darwin,!freebsd,!netbsd,!openbsd,!linux
-
-package flags
-
-const (
- tIOCGWINSZ = 0
-)
diff --git a/vendor/github.com/mailru/easyjson/LICENSE b/vendor/github.com/mailru/easyjson/LICENSE
deleted file mode 100644
index fbff658f..00000000
--- a/vendor/github.com/mailru/easyjson/LICENSE
+++ /dev/null
@@ -1,7 +0,0 @@
-Copyright (c) 2016 Mail.Ru Group
-
-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/mailru/easyjson/buffer/pool.go b/vendor/github.com/mailru/easyjson/buffer/pool.go
deleted file mode 100644
index 07fb4bc1..00000000
--- a/vendor/github.com/mailru/easyjson/buffer/pool.go
+++ /dev/null
@@ -1,270 +0,0 @@
-// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to
-// reduce copying and to allow reuse of individual chunks.
-package buffer
-
-import (
- "io"
- "sync"
-)
-
-// PoolConfig contains configuration for the allocation and reuse strategy.
-type PoolConfig struct {
- StartSize int // Minimum chunk size that is allocated.
- PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead.
- MaxSize int // Maximum chunk size that will be allocated.
-}
-
-var config = PoolConfig{
- StartSize: 128,
- PooledSize: 512,
- MaxSize: 32768,
-}
-
-// Reuse pool: chunk size -> pool.
-var buffers = map[int]*sync.Pool{}
-
-func initBuffers() {
- for l := config.PooledSize; l <= config.MaxSize; l *= 2 {
- buffers[l] = new(sync.Pool)
- }
-}
-
-func init() {
- initBuffers()
-}
-
-// Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done.
-func Init(cfg PoolConfig) {
- config = cfg
- initBuffers()
-}
-
-// putBuf puts a chunk to reuse pool if it can be reused.
-func putBuf(buf []byte) {
- size := cap(buf)
- if size < config.PooledSize {
- return
- }
- if c := buffers[size]; c != nil {
- c.Put(buf[:0])
- }
-}
-
-// getBuf gets a chunk from reuse pool or creates a new one if reuse failed.
-func getBuf(size int) []byte {
- if size < config.PooledSize {
- return make([]byte, 0, size)
- }
-
- if c := buffers[size]; c != nil {
- v := c.Get()
- if v != nil {
- return v.([]byte)
- }
- }
- return make([]byte, 0, size)
-}
-
-// Buffer is a buffer optimized for serialization without extra copying.
-type Buffer struct {
-
- // Buf is the current chunk that can be used for serialization.
- Buf []byte
-
- toPool []byte
- bufs [][]byte
-}
-
-// EnsureSpace makes sure that the current chunk contains at least s free bytes,
-// possibly creating a new chunk.
-func (b *Buffer) EnsureSpace(s int) {
- if cap(b.Buf)-len(b.Buf) >= s {
- return
- }
- l := len(b.Buf)
- if l > 0 {
- if cap(b.toPool) != cap(b.Buf) {
- // Chunk was reallocated, toPool can be pooled.
- putBuf(b.toPool)
- }
- if cap(b.bufs) == 0 {
- b.bufs = make([][]byte, 0, 8)
- }
- b.bufs = append(b.bufs, b.Buf)
- l = cap(b.toPool) * 2
- } else {
- l = config.StartSize
- }
-
- if l > config.MaxSize {
- l = config.MaxSize
- }
- b.Buf = getBuf(l)
- b.toPool = b.Buf
-}
-
-// AppendByte appends a single byte to buffer.
-func (b *Buffer) AppendByte(data byte) {
- if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined.
- b.EnsureSpace(1)
- }
- b.Buf = append(b.Buf, data)
-}
-
-// AppendBytes appends a byte slice to buffer.
-func (b *Buffer) AppendBytes(data []byte) {
- for len(data) > 0 {
- if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined.
- b.EnsureSpace(1)
- }
-
- sz := cap(b.Buf) - len(b.Buf)
- if sz > len(data) {
- sz = len(data)
- }
-
- b.Buf = append(b.Buf, data[:sz]...)
- data = data[sz:]
- }
-}
-
-// AppendBytes appends a string to buffer.
-func (b *Buffer) AppendString(data string) {
- for len(data) > 0 {
- if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined.
- b.EnsureSpace(1)
- }
-
- sz := cap(b.Buf) - len(b.Buf)
- if sz > len(data) {
- sz = len(data)
- }
-
- b.Buf = append(b.Buf, data[:sz]...)
- data = data[sz:]
- }
-}
-
-// Size computes the size of a buffer by adding sizes of every chunk.
-func (b *Buffer) Size() int {
- size := len(b.Buf)
- for _, buf := range b.bufs {
- size += len(buf)
- }
- return size
-}
-
-// DumpTo outputs the contents of a buffer to a writer and resets the buffer.
-func (b *Buffer) DumpTo(w io.Writer) (written int, err error) {
- var n int
- for _, buf := range b.bufs {
- if err == nil {
- n, err = w.Write(buf)
- written += n
- }
- putBuf(buf)
- }
-
- if err == nil {
- n, err = w.Write(b.Buf)
- written += n
- }
- putBuf(b.toPool)
-
- b.bufs = nil
- b.Buf = nil
- b.toPool = nil
-
- return
-}
-
-// BuildBytes creates a single byte slice with all the contents of the buffer. Data is
-// copied if it does not fit in a single chunk. You can optionally provide one byte
-// slice as argument that it will try to reuse.
-func (b *Buffer) BuildBytes(reuse ...[]byte) []byte {
- if len(b.bufs) == 0 {
- ret := b.Buf
- b.toPool = nil
- b.Buf = nil
- return ret
- }
-
- var ret []byte
- size := b.Size()
-
- // If we got a buffer as argument and it is big enought, reuse it.
- if len(reuse) == 1 && cap(reuse[0]) >= size {
- ret = reuse[0][:0]
- } else {
- ret = make([]byte, 0, size)
- }
- for _, buf := range b.bufs {
- ret = append(ret, buf...)
- putBuf(buf)
- }
-
- ret = append(ret, b.Buf...)
- putBuf(b.toPool)
-
- b.bufs = nil
- b.toPool = nil
- b.Buf = nil
-
- return ret
-}
-
-type readCloser struct {
- offset int
- bufs [][]byte
-}
-
-func (r *readCloser) Read(p []byte) (n int, err error) {
- for _, buf := range r.bufs {
- // Copy as much as we can.
- x := copy(p[n:], buf[r.offset:])
- n += x // Increment how much we filled.
-
- // Did we empty the whole buffer?
- if r.offset+x == len(buf) {
- // On to the next buffer.
- r.offset = 0
- r.bufs = r.bufs[1:]
-
- // We can release this buffer.
- putBuf(buf)
- } else {
- r.offset += x
- }
-
- if n == len(p) {
- break
- }
- }
- // No buffers left or nothing read?
- if len(r.bufs) == 0 {
- err = io.EOF
- }
- return
-}
-
-func (r *readCloser) Close() error {
- // Release all remaining buffers.
- for _, buf := range r.bufs {
- putBuf(buf)
- }
- // In case Close gets called multiple times.
- r.bufs = nil
-
- return nil
-}
-
-// ReadCloser creates an io.ReadCloser with all the contents of the buffer.
-func (b *Buffer) ReadCloser() io.ReadCloser {
- ret := &readCloser{0, append(b.bufs, b.Buf)}
-
- b.bufs = nil
- b.toPool = nil
- b.Buf = nil
-
- return ret
-}
diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go
deleted file mode 100644
index ff7b27c5..00000000
--- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// This file will only be included to the build if neither
-// easyjson_nounsafe nor appengine build tag is set. See README notes
-// for more details.
-
-//+build !easyjson_nounsafe
-//+build !appengine
-
-package jlexer
-
-import (
- "reflect"
- "unsafe"
-)
-
-// bytesToStr creates a string pointing at the slice to avoid copying.
-//
-// Warning: the string returned by the function should be used with care, as the whole input data
-// chunk may be either blocked from being freed by GC because of a single string or the buffer.Data
-// may be garbage-collected even when the string exists.
-func bytesToStr(data []byte) string {
- h := (*reflect.SliceHeader)(unsafe.Pointer(&data))
- shdr := reflect.StringHeader{Data: h.Data, Len: h.Len}
- return *(*string)(unsafe.Pointer(&shdr))
-}
diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go
deleted file mode 100644
index 864d1be6..00000000
--- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// This file is included to the build if any of the buildtags below
-// are defined. Refer to README notes for more details.
-
-//+build easyjson_nounsafe appengine
-
-package jlexer
-
-// bytesToStr creates a string normally from []byte
-//
-// Note that this method is roughly 1.5x slower than using the 'unsafe' method.
-func bytesToStr(data []byte) string {
- return string(data)
-}
diff --git a/vendor/github.com/mailru/easyjson/jlexer/error.go b/vendor/github.com/mailru/easyjson/jlexer/error.go
deleted file mode 100644
index e90ec40d..00000000
--- a/vendor/github.com/mailru/easyjson/jlexer/error.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package jlexer
-
-import "fmt"
-
-// LexerError implements the error interface and represents all possible errors that can be
-// generated during parsing the JSON data.
-type LexerError struct {
- Reason string
- Offset int
- Data string
-}
-
-func (l *LexerError) Error() string {
- return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data)
-}
diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go
deleted file mode 100644
index ddd376b8..00000000
--- a/vendor/github.com/mailru/easyjson/jlexer/lexer.go
+++ /dev/null
@@ -1,1182 +0,0 @@
-// Package jlexer contains a JSON lexer implementation.
-//
-// It is expected that it is mostly used with generated parser code, so the interface is tuned
-// for a parser that knows what kind of data is expected.
-package jlexer
-
-import (
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "strconv"
- "unicode"
- "unicode/utf16"
- "unicode/utf8"
-)
-
-// tokenKind determines type of a token.
-type tokenKind byte
-
-const (
- tokenUndef tokenKind = iota // No token.
- tokenDelim // Delimiter: one of '{', '}', '[' or ']'.
- tokenString // A string literal, e.g. "abc\u1234"
- tokenNumber // Number literal, e.g. 1.5e5
- tokenBool // Boolean literal: true or false.
- tokenNull // null keyword.
-)
-
-// token describes a single token: type, position in the input and value.
-type token struct {
- kind tokenKind // Type of a token.
-
- boolValue bool // Value if a boolean literal token.
- byteValue []byte // Raw value of a token.
- delimValue byte
-}
-
-// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice.
-type Lexer struct {
- Data []byte // Input data given to the lexer.
-
- start int // Start of the current token.
- pos int // Current unscanned position in the input stream.
- token token // Last scanned token, if token.kind != tokenUndef.
-
- firstElement bool // Whether current element is the first in array or an object.
- wantSep byte // A comma or a colon character, which need to occur before a token.
-
- UseMultipleErrors bool // If we want to use multiple errors.
- fatalError error // Fatal error occurred during lexing. It is usually a syntax error.
- multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors.
-}
-
-// FetchToken scans the input for the next token.
-func (r *Lexer) FetchToken() {
- r.token.kind = tokenUndef
- r.start = r.pos
-
- // Check if r.Data has r.pos element
- // If it doesn't, it mean corrupted input data
- if len(r.Data) < r.pos {
- r.errParse("Unexpected end of data")
- return
- }
- // Determine the type of a token by skipping whitespace and reading the
- // first character.
- for _, c := range r.Data[r.pos:] {
- switch c {
- case ':', ',':
- if r.wantSep == c {
- r.pos++
- r.start++
- r.wantSep = 0
- } else {
- r.errSyntax()
- }
-
- case ' ', '\t', '\r', '\n':
- r.pos++
- r.start++
-
- case '"':
- if r.wantSep != 0 {
- r.errSyntax()
- }
-
- r.token.kind = tokenString
- r.fetchString()
- return
-
- case '{', '[':
- if r.wantSep != 0 {
- r.errSyntax()
- }
- r.firstElement = true
- r.token.kind = tokenDelim
- r.token.delimValue = r.Data[r.pos]
- r.pos++
- return
-
- case '}', ']':
- if !r.firstElement && (r.wantSep != ',') {
- r.errSyntax()
- }
- r.wantSep = 0
- r.token.kind = tokenDelim
- r.token.delimValue = r.Data[r.pos]
- r.pos++
- return
-
- case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-':
- if r.wantSep != 0 {
- r.errSyntax()
- }
- r.token.kind = tokenNumber
- r.fetchNumber()
- return
-
- case 'n':
- if r.wantSep != 0 {
- r.errSyntax()
- }
-
- r.token.kind = tokenNull
- r.fetchNull()
- return
-
- case 't':
- if r.wantSep != 0 {
- r.errSyntax()
- }
-
- r.token.kind = tokenBool
- r.token.boolValue = true
- r.fetchTrue()
- return
-
- case 'f':
- if r.wantSep != 0 {
- r.errSyntax()
- }
-
- r.token.kind = tokenBool
- r.token.boolValue = false
- r.fetchFalse()
- return
-
- default:
- r.errSyntax()
- return
- }
- }
- r.fatalError = io.EOF
- return
-}
-
-// isTokenEnd returns true if the char can follow a non-delimiter token
-func isTokenEnd(c byte) bool {
- return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':'
-}
-
-// fetchNull fetches and checks remaining bytes of null keyword.
-func (r *Lexer) fetchNull() {
- r.pos += 4
- if r.pos > len(r.Data) ||
- r.Data[r.pos-3] != 'u' ||
- r.Data[r.pos-2] != 'l' ||
- r.Data[r.pos-1] != 'l' ||
- (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) {
-
- r.pos -= 4
- r.errSyntax()
- }
-}
-
-// fetchTrue fetches and checks remaining bytes of true keyword.
-func (r *Lexer) fetchTrue() {
- r.pos += 4
- if r.pos > len(r.Data) ||
- r.Data[r.pos-3] != 'r' ||
- r.Data[r.pos-2] != 'u' ||
- r.Data[r.pos-1] != 'e' ||
- (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) {
-
- r.pos -= 4
- r.errSyntax()
- }
-}
-
-// fetchFalse fetches and checks remaining bytes of false keyword.
-func (r *Lexer) fetchFalse() {
- r.pos += 5
- if r.pos > len(r.Data) ||
- r.Data[r.pos-4] != 'a' ||
- r.Data[r.pos-3] != 'l' ||
- r.Data[r.pos-2] != 's' ||
- r.Data[r.pos-1] != 'e' ||
- (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) {
-
- r.pos -= 5
- r.errSyntax()
- }
-}
-
-// fetchNumber scans a number literal token.
-func (r *Lexer) fetchNumber() {
- hasE := false
- afterE := false
- hasDot := false
-
- r.pos++
- for i, c := range r.Data[r.pos:] {
- switch {
- case c >= '0' && c <= '9':
- afterE = false
- case c == '.' && !hasDot:
- hasDot = true
- case (c == 'e' || c == 'E') && !hasE:
- hasE = true
- hasDot = true
- afterE = true
- case (c == '+' || c == '-') && afterE:
- afterE = false
- default:
- r.pos += i
- if !isTokenEnd(c) {
- r.errSyntax()
- } else {
- r.token.byteValue = r.Data[r.start:r.pos]
- }
- return
- }
- }
-
- r.pos = len(r.Data)
- r.token.byteValue = r.Data[r.start:]
-}
-
-// findStringLen tries to scan into the string literal for ending quote char to determine required size.
-// The size will be exact if no escapes are present and may be inexact if there are escaped chars.
-func findStringLen(data []byte) (isValid, hasEscapes bool, length int) {
- delta := 0
-
- for i := 0; i < len(data); i++ {
- switch data[i] {
- case '\\':
- i++
- delta++
- if i < len(data) && data[i] == 'u' {
- delta++
- }
- case '"':
- return true, (delta > 0), (i - delta)
- }
- }
-
- return false, false, len(data)
-}
-
-// getu4 decodes \uXXXX from the beginning of s, returning the hex value,
-// or it returns -1.
-func getu4(s []byte) rune {
- if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
- return -1
- }
- var val rune
- for i := 2; i < len(s) && i < 6; i++ {
- var v byte
- c := s[i]
- switch c {
- case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
- v = c - '0'
- case 'a', 'b', 'c', 'd', 'e', 'f':
- v = c - 'a' + 10
- case 'A', 'B', 'C', 'D', 'E', 'F':
- v = c - 'A' + 10
- default:
- return -1
- }
-
- val <<= 4
- val |= rune(v)
- }
- return val
-}
-
-// processEscape processes a single escape sequence and returns number of bytes processed.
-func (r *Lexer) processEscape(data []byte) (int, error) {
- if len(data) < 2 {
- return 0, fmt.Errorf("syntax error at %v", string(data))
- }
-
- c := data[1]
- switch c {
- case '"', '/', '\\':
- r.token.byteValue = append(r.token.byteValue, c)
- return 2, nil
- case 'b':
- r.token.byteValue = append(r.token.byteValue, '\b')
- return 2, nil
- case 'f':
- r.token.byteValue = append(r.token.byteValue, '\f')
- return 2, nil
- case 'n':
- r.token.byteValue = append(r.token.byteValue, '\n')
- return 2, nil
- case 'r':
- r.token.byteValue = append(r.token.byteValue, '\r')
- return 2, nil
- case 't':
- r.token.byteValue = append(r.token.byteValue, '\t')
- return 2, nil
- case 'u':
- rr := getu4(data)
- if rr < 0 {
- return 0, errors.New("syntax error")
- }
-
- read := 6
- if utf16.IsSurrogate(rr) {
- rr1 := getu4(data[read:])
- if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
- read += 6
- rr = dec
- } else {
- rr = unicode.ReplacementChar
- }
- }
- var d [4]byte
- s := utf8.EncodeRune(d[:], rr)
- r.token.byteValue = append(r.token.byteValue, d[:s]...)
- return read, nil
- }
-
- return 0, errors.New("syntax error")
-}
-
-// fetchString scans a string literal token.
-func (r *Lexer) fetchString() {
- r.pos++
- data := r.Data[r.pos:]
-
- isValid, hasEscapes, length := findStringLen(data)
- if !isValid {
- r.pos += length
- r.errParse("unterminated string literal")
- return
- }
- if !hasEscapes {
- r.token.byteValue = data[:length]
- r.pos += length + 1
- return
- }
-
- r.token.byteValue = make([]byte, 0, length)
- p := 0
- for i := 0; i < len(data); {
- switch data[i] {
- case '"':
- r.pos += i + 1
- r.token.byteValue = append(r.token.byteValue, data[p:i]...)
- i++
- return
-
- case '\\':
- r.token.byteValue = append(r.token.byteValue, data[p:i]...)
- off, err := r.processEscape(data[i:])
- if err != nil {
- r.errParse(err.Error())
- return
- }
- i += off
- p = i
-
- default:
- i++
- }
- }
- r.errParse("unterminated string literal")
-}
-
-// scanToken scans the next token if no token is currently available in the lexer.
-func (r *Lexer) scanToken() {
- if r.token.kind != tokenUndef || r.fatalError != nil {
- return
- }
-
- r.FetchToken()
-}
-
-// consume resets the current token to allow scanning the next one.
-func (r *Lexer) consume() {
- r.token.kind = tokenUndef
- r.token.delimValue = 0
-}
-
-// Ok returns true if no error (including io.EOF) was encountered during scanning.
-func (r *Lexer) Ok() bool {
- return r.fatalError == nil
-}
-
-const maxErrorContextLen = 13
-
-func (r *Lexer) errParse(what string) {
- if r.fatalError == nil {
- var str string
- if len(r.Data)-r.pos <= maxErrorContextLen {
- str = string(r.Data)
- } else {
- str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..."
- }
- r.fatalError = &LexerError{
- Reason: what,
- Offset: r.pos,
- Data: str,
- }
- }
-}
-
-func (r *Lexer) errSyntax() {
- r.errParse("syntax error")
-}
-
-func (r *Lexer) errInvalidToken(expected string) {
- if r.fatalError != nil {
- return
- }
- if r.UseMultipleErrors {
- r.pos = r.start
- r.consume()
- r.SkipRecursive()
- switch expected {
- case "[":
- r.token.delimValue = ']'
- r.token.kind = tokenDelim
- case "{":
- r.token.delimValue = '}'
- r.token.kind = tokenDelim
- }
- r.addNonfatalError(&LexerError{
- Reason: fmt.Sprintf("expected %s", expected),
- Offset: r.start,
- Data: string(r.Data[r.start:r.pos]),
- })
- return
- }
-
- var str string
- if len(r.token.byteValue) <= maxErrorContextLen {
- str = string(r.token.byteValue)
- } else {
- str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..."
- }
- r.fatalError = &LexerError{
- Reason: fmt.Sprintf("expected %s", expected),
- Offset: r.pos,
- Data: str,
- }
-}
-
-func (r *Lexer) GetPos() int {
- return r.pos
-}
-
-// Delim consumes a token and verifies that it is the given delimiter.
-func (r *Lexer) Delim(c byte) {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
-
- if !r.Ok() || r.token.delimValue != c {
- r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled.
- r.errInvalidToken(string([]byte{c}))
- } else {
- r.consume()
- }
-}
-
-// IsDelim returns true if there was no scanning error and next token is the given delimiter.
-func (r *Lexer) IsDelim(c byte) bool {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- return !r.Ok() || r.token.delimValue == c
-}
-
-// Null verifies that the next token is null and consumes it.
-func (r *Lexer) Null() {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- if !r.Ok() || r.token.kind != tokenNull {
- r.errInvalidToken("null")
- }
- r.consume()
-}
-
-// IsNull returns true if the next token is a null keyword.
-func (r *Lexer) IsNull() bool {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- return r.Ok() && r.token.kind == tokenNull
-}
-
-// Skip skips a single token.
-func (r *Lexer) Skip() {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- r.consume()
-}
-
-// SkipRecursive skips next array or object completely, or just skips a single token if not
-// an array/object.
-//
-// Note: no syntax validation is performed on the skipped data.
-func (r *Lexer) SkipRecursive() {
- r.scanToken()
- var start, end byte
-
- switch r.token.delimValue {
- case '{':
- start, end = '{', '}'
- case '[':
- start, end = '[', ']'
- default:
- r.consume()
- return
- }
-
- r.consume()
-
- level := 1
- inQuotes := false
- wasEscape := false
-
- for i, c := range r.Data[r.pos:] {
- switch {
- case c == start && !inQuotes:
- level++
- case c == end && !inQuotes:
- level--
- if level == 0 {
- r.pos += i + 1
- return
- }
- case c == '\\' && inQuotes:
- wasEscape = !wasEscape
- continue
- case c == '"' && inQuotes:
- inQuotes = wasEscape
- case c == '"':
- inQuotes = true
- }
- wasEscape = false
- }
- r.pos = len(r.Data)
- r.fatalError = &LexerError{
- Reason: "EOF reached while skipping array/object or token",
- Offset: r.pos,
- Data: string(r.Data[r.pos:]),
- }
-}
-
-// Raw fetches the next item recursively as a data slice
-func (r *Lexer) Raw() []byte {
- r.SkipRecursive()
- if !r.Ok() {
- return nil
- }
- return r.Data[r.start:r.pos]
-}
-
-// IsStart returns whether the lexer is positioned at the start
-// of an input string.
-func (r *Lexer) IsStart() bool {
- return r.pos == 0
-}
-
-// Consumed reads all remaining bytes from the input, publishing an error if
-// there is anything but whitespace remaining.
-func (r *Lexer) Consumed() {
- if r.pos > len(r.Data) || !r.Ok() {
- return
- }
-
- for _, c := range r.Data[r.pos:] {
- if c != ' ' && c != '\t' && c != '\r' && c != '\n' {
- r.AddError(&LexerError{
- Reason: "invalid character '" + string(c) + "' after top-level value",
- Offset: r.pos,
- Data: string(r.Data[r.pos:]),
- })
- return
- }
-
- r.pos++
- r.start++
- }
-}
-
-func (r *Lexer) unsafeString() (string, []byte) {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- if !r.Ok() || r.token.kind != tokenString {
- r.errInvalidToken("string")
- return "", nil
- }
- bytes := r.token.byteValue
- ret := bytesToStr(r.token.byteValue)
- r.consume()
- return ret, bytes
-}
-
-// UnsafeString returns the string value if the token is a string literal.
-//
-// Warning: returned string may point to the input buffer, so the string should not outlive
-// the input buffer. Intended pattern of usage is as an argument to a switch statement.
-func (r *Lexer) UnsafeString() string {
- ret, _ := r.unsafeString()
- return ret
-}
-
-// UnsafeBytes returns the byte slice if the token is a string literal.
-func (r *Lexer) UnsafeBytes() []byte {
- _, ret := r.unsafeString()
- return ret
-}
-
-// String reads a string literal.
-func (r *Lexer) String() string {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- if !r.Ok() || r.token.kind != tokenString {
- r.errInvalidToken("string")
- return ""
- }
- ret := string(r.token.byteValue)
- r.consume()
- return ret
-}
-
-// Bytes reads a string literal and base64 decodes it into a byte slice.
-func (r *Lexer) Bytes() []byte {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- if !r.Ok() || r.token.kind != tokenString {
- r.errInvalidToken("string")
- return nil
- }
- ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue)))
- n, err := base64.StdEncoding.Decode(ret, r.token.byteValue)
- if err != nil {
- r.fatalError = &LexerError{
- Reason: err.Error(),
- }
- return nil
- }
-
- r.consume()
- return ret[:n]
-}
-
-// Bool reads a true or false boolean keyword.
-func (r *Lexer) Bool() bool {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- if !r.Ok() || r.token.kind != tokenBool {
- r.errInvalidToken("bool")
- return false
- }
- ret := r.token.boolValue
- r.consume()
- return ret
-}
-
-func (r *Lexer) number() string {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- if !r.Ok() || r.token.kind != tokenNumber {
- r.errInvalidToken("number")
- return ""
- }
- ret := bytesToStr(r.token.byteValue)
- r.consume()
- return ret
-}
-
-func (r *Lexer) Uint8() uint8 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 8)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return uint8(n)
-}
-
-func (r *Lexer) Uint16() uint16 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 16)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return uint16(n)
-}
-
-func (r *Lexer) Uint32() uint32 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 32)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return uint32(n)
-}
-
-func (r *Lexer) Uint64() uint64 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 64)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return n
-}
-
-func (r *Lexer) Uint() uint {
- return uint(r.Uint64())
-}
-
-func (r *Lexer) Int8() int8 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 8)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return int8(n)
-}
-
-func (r *Lexer) Int16() int16 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 16)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return int16(n)
-}
-
-func (r *Lexer) Int32() int32 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 32)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return int32(n)
-}
-
-func (r *Lexer) Int64() int64 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 64)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return n
-}
-
-func (r *Lexer) Int() int {
- return int(r.Int64())
-}
-
-func (r *Lexer) Uint8Str() uint8 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 8)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return uint8(n)
-}
-
-func (r *Lexer) Uint16Str() uint16 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 16)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return uint16(n)
-}
-
-func (r *Lexer) Uint32Str() uint32 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 32)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return uint32(n)
-}
-
-func (r *Lexer) Uint64Str() uint64 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseUint(s, 10, 64)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return n
-}
-
-func (r *Lexer) UintStr() uint {
- return uint(r.Uint64Str())
-}
-
-func (r *Lexer) UintptrStr() uintptr {
- return uintptr(r.Uint64Str())
-}
-
-func (r *Lexer) Int8Str() int8 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 8)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return int8(n)
-}
-
-func (r *Lexer) Int16Str() int16 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 16)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return int16(n)
-}
-
-func (r *Lexer) Int32Str() int32 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 32)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return int32(n)
-}
-
-func (r *Lexer) Int64Str() int64 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseInt(s, 10, 64)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return n
-}
-
-func (r *Lexer) IntStr() int {
- return int(r.Int64Str())
-}
-
-func (r *Lexer) Float32() float32 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseFloat(s, 32)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return float32(n)
-}
-
-func (r *Lexer) Float32Str() float32 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
- n, err := strconv.ParseFloat(s, 32)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return float32(n)
-}
-
-func (r *Lexer) Float64() float64 {
- s := r.number()
- if !r.Ok() {
- return 0
- }
-
- n, err := strconv.ParseFloat(s, 64)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: s,
- })
- }
- return n
-}
-
-func (r *Lexer) Float64Str() float64 {
- s, b := r.unsafeString()
- if !r.Ok() {
- return 0
- }
- n, err := strconv.ParseFloat(s, 64)
- if err != nil {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Reason: err.Error(),
- Data: string(b),
- })
- }
- return n
-}
-
-func (r *Lexer) Error() error {
- return r.fatalError
-}
-
-func (r *Lexer) AddError(e error) {
- if r.fatalError == nil {
- r.fatalError = e
- }
-}
-
-func (r *Lexer) AddNonFatalError(e error) {
- r.addNonfatalError(&LexerError{
- Offset: r.start,
- Data: string(r.Data[r.start:r.pos]),
- Reason: e.Error(),
- })
-}
-
-func (r *Lexer) addNonfatalError(err *LexerError) {
- if r.UseMultipleErrors {
- // We don't want to add errors with the same offset.
- if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset {
- return
- }
- r.multipleErrors = append(r.multipleErrors, err)
- return
- }
- r.fatalError = err
-}
-
-func (r *Lexer) GetNonFatalErrors() []*LexerError {
- return r.multipleErrors
-}
-
-// JsonNumber fetches and json.Number from 'encoding/json' package.
-// Both int, float or string, contains them are valid values
-func (r *Lexer) JsonNumber() json.Number {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
- if !r.Ok() {
- r.errInvalidToken("json.Number")
- return json.Number("")
- }
-
- switch r.token.kind {
- case tokenString:
- return json.Number(r.String())
- case tokenNumber:
- return json.Number(r.Raw())
- case tokenNull:
- r.Null()
- return json.Number("")
- default:
- r.errSyntax()
- return json.Number("")
- }
-}
-
-// Interface fetches an interface{} analogous to the 'encoding/json' package.
-func (r *Lexer) Interface() interface{} {
- if r.token.kind == tokenUndef && r.Ok() {
- r.FetchToken()
- }
-
- if !r.Ok() {
- return nil
- }
- switch r.token.kind {
- case tokenString:
- return r.String()
- case tokenNumber:
- return r.Float64()
- case tokenBool:
- return r.Bool()
- case tokenNull:
- r.Null()
- return nil
- }
-
- if r.token.delimValue == '{' {
- r.consume()
-
- ret := map[string]interface{}{}
- for !r.IsDelim('}') {
- key := r.String()
- r.WantColon()
- ret[key] = r.Interface()
- r.WantComma()
- }
- r.Delim('}')
-
- if r.Ok() {
- return ret
- } else {
- return nil
- }
- } else if r.token.delimValue == '[' {
- r.consume()
-
- ret := []interface{}{}
- for !r.IsDelim(']') {
- ret = append(ret, r.Interface())
- r.WantComma()
- }
- r.Delim(']')
-
- if r.Ok() {
- return ret
- } else {
- return nil
- }
- }
- r.errSyntax()
- return nil
-}
-
-// WantComma requires a comma to be present before fetching next token.
-func (r *Lexer) WantComma() {
- r.wantSep = ','
- r.firstElement = false
-}
-
-// WantColon requires a colon to be present before fetching next token.
-func (r *Lexer) WantColon() {
- r.wantSep = ':'
- r.firstElement = false
-}
diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go
deleted file mode 100644
index eb8547cc..00000000
--- a/vendor/github.com/mailru/easyjson/jwriter/writer.go
+++ /dev/null
@@ -1,407 +0,0 @@
-// Package jwriter contains a JSON writer.
-package jwriter
-
-import (
- "io"
- "strconv"
- "unicode/utf8"
-
- "github.com/mailru/easyjson/buffer"
-)
-
-// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but
-// Flags field in Writer is used to set and pass them around.
-type Flags int
-
-const (
- NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'.
- NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'.
-)
-
-// Writer is a JSON writer.
-type Writer struct {
- Flags Flags
-
- Error error
- Buffer buffer.Buffer
- NoEscapeHTML bool
-}
-
-// Size returns the size of the data that was written out.
-func (w *Writer) Size() int {
- return w.Buffer.Size()
-}
-
-// DumpTo outputs the data to given io.Writer, resetting the buffer.
-func (w *Writer) DumpTo(out io.Writer) (written int, err error) {
- return w.Buffer.DumpTo(out)
-}
-
-// BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice
-// as argument that it will try to reuse.
-func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) {
- if w.Error != nil {
- return nil, w.Error
- }
-
- return w.Buffer.BuildBytes(reuse...), nil
-}
-
-// ReadCloser returns an io.ReadCloser that can be used to read the data.
-// ReadCloser also resets the buffer.
-func (w *Writer) ReadCloser() (io.ReadCloser, error) {
- if w.Error != nil {
- return nil, w.Error
- }
-
- return w.Buffer.ReadCloser(), nil
-}
-
-// RawByte appends raw binary data to the buffer.
-func (w *Writer) RawByte(c byte) {
- w.Buffer.AppendByte(c)
-}
-
-// RawByte appends raw binary data to the buffer.
-func (w *Writer) RawString(s string) {
- w.Buffer.AppendString(s)
-}
-
-// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for
-// calling with results of MarshalJSON-like functions.
-func (w *Writer) Raw(data []byte, err error) {
- switch {
- case w.Error != nil:
- return
- case err != nil:
- w.Error = err
- case len(data) > 0:
- w.Buffer.AppendBytes(data)
- default:
- w.RawString("null")
- }
-}
-
-// RawText encloses raw binary data in quotes and appends in to the buffer.
-// Useful for calling with results of MarshalText-like functions.
-func (w *Writer) RawText(data []byte, err error) {
- switch {
- case w.Error != nil:
- return
- case err != nil:
- w.Error = err
- case len(data) > 0:
- w.String(string(data))
- default:
- w.RawString("null")
- }
-}
-
-// Base64Bytes appends data to the buffer after base64 encoding it
-func (w *Writer) Base64Bytes(data []byte) {
- if data == nil {
- w.Buffer.AppendString("null")
- return
- }
- w.Buffer.AppendByte('"')
- w.base64(data)
- w.Buffer.AppendByte('"')
-}
-
-func (w *Writer) Uint8(n uint8) {
- w.Buffer.EnsureSpace(3)
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
-}
-
-func (w *Writer) Uint16(n uint16) {
- w.Buffer.EnsureSpace(5)
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
-}
-
-func (w *Writer) Uint32(n uint32) {
- w.Buffer.EnsureSpace(10)
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
-}
-
-func (w *Writer) Uint(n uint) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
-}
-
-func (w *Writer) Uint64(n uint64) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10)
-}
-
-func (w *Writer) Int8(n int8) {
- w.Buffer.EnsureSpace(4)
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
-}
-
-func (w *Writer) Int16(n int16) {
- w.Buffer.EnsureSpace(6)
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
-}
-
-func (w *Writer) Int32(n int32) {
- w.Buffer.EnsureSpace(11)
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
-}
-
-func (w *Writer) Int(n int) {
- w.Buffer.EnsureSpace(21)
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
-}
-
-func (w *Writer) Int64(n int64) {
- w.Buffer.EnsureSpace(21)
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10)
-}
-
-func (w *Writer) Uint8Str(n uint8) {
- w.Buffer.EnsureSpace(3)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Uint16Str(n uint16) {
- w.Buffer.EnsureSpace(5)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Uint32Str(n uint32) {
- w.Buffer.EnsureSpace(10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) UintStr(n uint) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Uint64Str(n uint64) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) UintptrStr(n uintptr) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Int8Str(n int8) {
- w.Buffer.EnsureSpace(4)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Int16Str(n int16) {
- w.Buffer.EnsureSpace(6)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Int32Str(n int32) {
- w.Buffer.EnsureSpace(11)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) IntStr(n int) {
- w.Buffer.EnsureSpace(21)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Int64Str(n int64) {
- w.Buffer.EnsureSpace(21)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Float32(n float32) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32)
-}
-
-func (w *Writer) Float32Str(n float32) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Float64(n float64) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64)
-}
-
-func (w *Writer) Float64Str(n float64) {
- w.Buffer.EnsureSpace(20)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
- w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 64)
- w.Buffer.Buf = append(w.Buffer.Buf, '"')
-}
-
-func (w *Writer) Bool(v bool) {
- w.Buffer.EnsureSpace(5)
- if v {
- w.Buffer.Buf = append(w.Buffer.Buf, "true"...)
- } else {
- w.Buffer.Buf = append(w.Buffer.Buf, "false"...)
- }
-}
-
-const chars = "0123456789abcdef"
-
-func getTable(falseValues ...int) [128]bool {
- table := [128]bool{}
-
- for i := 0; i < 128; i++ {
- table[i] = true
- }
-
- for _, v := range falseValues {
- table[v] = false
- }
-
- return table
-}
-
-var (
- htmlEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '&', '<', '>', '\\')
- htmlNoEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '\\')
-)
-
-func (w *Writer) String(s string) {
- w.Buffer.AppendByte('"')
-
- // Portions of the string that contain no escapes are appended as
- // byte slices.
-
- p := 0 // last non-escape symbol
-
- var escapeTable [128]bool
- if w.NoEscapeHTML {
- escapeTable = htmlNoEscapeTable
- } else {
- escapeTable = htmlEscapeTable
- }
-
- for i := 0; i < len(s); {
- c := s[i]
-
- if c < utf8.RuneSelf {
- if escapeTable[c] {
- // single-width character, no escaping is required
- i++
- continue
- }
-
- w.Buffer.AppendString(s[p:i])
- switch c {
- case '\t':
- w.Buffer.AppendString(`\t`)
- case '\r':
- w.Buffer.AppendString(`\r`)
- case '\n':
- w.Buffer.AppendString(`\n`)
- case '\\':
- w.Buffer.AppendString(`\\`)
- case '"':
- w.Buffer.AppendString(`\"`)
- default:
- w.Buffer.AppendString(`\u00`)
- w.Buffer.AppendByte(chars[c>>4])
- w.Buffer.AppendByte(chars[c&0xf])
- }
-
- i++
- p = i
- continue
- }
-
- // broken utf
- runeValue, runeWidth := utf8.DecodeRuneInString(s[i:])
- if runeValue == utf8.RuneError && runeWidth == 1 {
- w.Buffer.AppendString(s[p:i])
- w.Buffer.AppendString(`\ufffd`)
- i++
- p = i
- continue
- }
-
- // jsonp stuff - tab separator and line separator
- if runeValue == '\u2028' || runeValue == '\u2029' {
- w.Buffer.AppendString(s[p:i])
- w.Buffer.AppendString(`\u202`)
- w.Buffer.AppendByte(chars[runeValue&0xf])
- i += runeWidth
- p = i
- continue
- }
- i += runeWidth
- }
- w.Buffer.AppendString(s[p:])
- w.Buffer.AppendByte('"')
-}
-
-const encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
-const padChar = '='
-
-func (w *Writer) base64(in []byte) {
-
- if len(in) == 0 {
- return
- }
-
- w.Buffer.EnsureSpace(((len(in)-1)/3 + 1) * 4)
-
- si := 0
- n := (len(in) / 3) * 3
-
- for si < n {
- // Convert 3x 8bit source bytes into 4 bytes
- val := uint(in[si+0])<<16 | uint(in[si+1])<<8 | uint(in[si+2])
-
- w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F], encode[val>>6&0x3F], encode[val&0x3F])
-
- si += 3
- }
-
- remain := len(in) - si
- if remain == 0 {
- return
- }
-
- // Add the remaining small block
- val := uint(in[si+0]) << 16
- if remain == 2 {
- val |= uint(in[si+1]) << 8
- }
-
- w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F])
-
- switch remain {
- case 2:
- w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>6&0x3F], byte(padChar))
- case 1:
- w.Buffer.Buf = append(w.Buffer.Buf, byte(padChar), byte(padChar))
- }
-}
diff --git a/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE
new file mode 100644
index 00000000..c67dad61
--- /dev/null
+++ b/vendor/github.com/pmezard/go-difflib/LICENSE
@@ -0,0 +1,27 @@
+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/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go
new file mode 100644
index 00000000..003e99fa
--- /dev/null
+++ b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go
@@ -0,0 +1,772 @@
+// Package difflib is a partial port of Python difflib module.
+//
+// It provides tools to compare sequences of strings and generate textual diffs.
+//
+// The following class and functions have been ported:
+//
+// - SequenceMatcher
+//
+// - unified_diff
+//
+// - context_diff
+//
+// Getting unified diffs was the main goal of the port. Keep in mind this code
+// is mostly suitable to output text differences in a human friendly way, there
+// are no guarantees generated diffs are consumable by patch(1).
+package difflib
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "strings"
+)
+
+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
+}
+
+func calculateRatio(matches, length int) float64 {
+ if length > 0 {
+ return 2.0 * float64(matches) / float64(length)
+ }
+ return 1.0
+}
+
+type Match struct {
+ A int
+ B int
+ Size int
+}
+
+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 "" lines in HTML files). That may be
+// because this is the only method of the 3 that has a *concept* of
+// "junk" .
+//
+// 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
+}
+
+func NewMatcher(a, b []string) *SequenceMatcher {
+ m := SequenceMatcher{autoJunk: true}
+ m.SetSeqs(a, b)
+ return &m
+}
+
+func NewMatcherWithJunk(a, b []string, autoJunk bool,
+ isJunk func(string) bool) *SequenceMatcher {
+
+ m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
+ m.SetSeqs(a, b)
+ return &m
+}
+
+// Set two sequences to be compared.
+func (m *SequenceMatcher) SetSeqs(a, b []string) {
+ m.SetSeq1(a)
+ m.SetSeq2(b)
+}
+
+// Set 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
+}
+
+// Set 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}
+}
+
+// Return 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
+}
+
+// Return 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
+}
+
+// Isolate 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{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
+}
+
+// Return a measure of the sequences' similarity (float in [0,1]).
+//
+// Where T is the total number of elements in both sequences, and
+// M is the number of matches, this is 2.0*M / T.
+// Note that this is 1 if the sequences are identical, and 0 if
+// they have nothing in common.
+//
+// .Ratio() is expensive to compute if you haven't already computed
+// .GetMatchingBlocks() or .GetOpCodes(), in which case you may
+// want to try .QuickRatio() or .RealQuickRation() first to get an
+// upper bound.
+func (m *SequenceMatcher) Ratio() float64 {
+ matches := 0
+ for _, m := range m.GetMatchingBlocks() {
+ matches += m.Size
+ }
+ return calculateRatio(matches, len(m.a)+len(m.b))
+}
+
+// Return an upper bound on ratio() relatively quickly.
+//
+// This isn't defined beyond that it is an upper bound on .Ratio(), and
+// is faster to compute.
+func (m *SequenceMatcher) QuickRatio() float64 {
+ // viewing a and b as multisets, set matches to the cardinality
+ // of their intersection; this counts the number of matches
+ // without regard to order, so is clearly an upper bound
+ if m.fullBCount == nil {
+ m.fullBCount = map[string]int{}
+ for _, s := range m.b {
+ m.fullBCount[s] = m.fullBCount[s] + 1
+ }
+ }
+
+ // avail[x] is the number of times x appears in 'b' less the
+ // number of times we've seen it in 'a' so far ... kinda
+ avail := map[string]int{}
+ matches := 0
+ for _, s := range m.a {
+ n, ok := avail[s]
+ if !ok {
+ n = m.fullBCount[s]
+ }
+ avail[s] = n - 1
+ if n > 0 {
+ matches += 1
+ }
+ }
+ return calculateRatio(matches, len(m.a)+len(m.b))
+}
+
+// Return an upper bound on ratio() very quickly.
+//
+// This isn't defined beyond that it is an upper bound on .Ratio(), and
+// is faster to compute than either .Ratio() or .QuickRatio().
+func (m *SequenceMatcher) RealQuickRatio() float64 {
+ la, lb := len(m.a), len(m.b)
+ return calculateRatio(min(la, lb), la+lb)
+}
+
+// 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 -= 1 // empty ranges begin at line just before the range
+ }
+ return fmt.Sprintf("%d,%d", beginning, length)
+}
+
+// Unified diff parameters
+type UnifiedDiff struct {
+ A []string // First sequence lines
+ FromFile string // First file name
+ FromDate string // First file time
+ B []string // Second sequence lines
+ ToFile string // Second file name
+ ToDate string // Second file time
+ Eol string // Headers end of line, defaults to LF
+ Context int // Number of context lines
+}
+
+// Compare two sequences of lines; generate the delta as a unified diff.
+//
+// Unified diffs are a compact way of showing line changes and a few
+// lines of context. The number of context lines is set by 'n' which
+// defaults to three.
+//
+// By default, the diff control lines (those with ---, +++, or @@) are
+// created with a trailing newline. This is helpful so that inputs
+// created from file.readlines() result in diffs that are suitable for
+// file.writelines() since both the inputs and outputs have trailing
+// newlines.
+//
+// For inputs that do not have trailing newlines, set the lineterm
+// argument to "" so that the output will be uniformly newline free.
+//
+// The unidiff format normally has a header for filenames and modification
+// times. Any or all of these may be specified using strings for
+// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
+// The modification times are normally expressed in the ISO 8601 format.
+func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
+ buf := bufio.NewWriter(writer)
+ defer buf.Flush()
+ wf := func(format string, args ...interface{}) error {
+ _, err := buf.WriteString(fmt.Sprintf(format, args...))
+ return err
+ }
+ ws := func(s string) error {
+ _, err := buf.WriteString(s)
+ return err
+ }
+
+ if len(diff.Eol) == 0 {
+ diff.Eol = "\n"
+ }
+
+ started := false
+ m := NewMatcher(diff.A, diff.B)
+ for _, g := range m.GetGroupedOpCodes(diff.Context) {
+ if !started {
+ started = true
+ fromDate := ""
+ if len(diff.FromDate) > 0 {
+ fromDate = "\t" + diff.FromDate
+ }
+ toDate := ""
+ if len(diff.ToDate) > 0 {
+ toDate = "\t" + diff.ToDate
+ }
+ if diff.FromFile != "" || diff.ToFile != "" {
+ err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
+ if err != nil {
+ return err
+ }
+ err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
+ if err != nil {
+ return err
+ }
+ }
+ }
+ first, last := g[0], g[len(g)-1]
+ range1 := formatRangeUnified(first.I1, last.I2)
+ range2 := formatRangeUnified(first.J1, last.J2)
+ if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
+ return err
+ }
+ for _, c := range g {
+ i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
+ if c.Tag == 'e' {
+ for _, line := range diff.A[i1:i2] {
+ if err := ws(" " + line); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if c.Tag == 'r' || c.Tag == 'd' {
+ for _, line := range diff.A[i1:i2] {
+ if err := ws("-" + line); err != nil {
+ return err
+ }
+ }
+ }
+ if c.Tag == 'r' || c.Tag == 'i' {
+ for _, line := range diff.B[j1:j2] {
+ if err := ws("+" + line); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// Like WriteUnifiedDiff but returns the diff a string.
+func GetUnifiedDiffString(diff UnifiedDiff) (string, error) {
+ w := &bytes.Buffer{}
+ err := WriteUnifiedDiff(w, diff)
+ return string(w.Bytes()), err
+}
+
+// Convert range to the "ed" format.
+func formatRangeContext(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 == 0 {
+ beginning -= 1 // empty ranges begin at line just before the range
+ }
+ if length <= 1 {
+ return fmt.Sprintf("%d", beginning)
+ }
+ return fmt.Sprintf("%d,%d", beginning, beginning+length-1)
+}
+
+type ContextDiff UnifiedDiff
+
+// Compare two sequences of lines; generate the delta as a context diff.
+//
+// Context diffs are a compact way of showing line changes and a few
+// lines of context. The number of context lines is set by diff.Context
+// which defaults to three.
+//
+// By default, the diff control lines (those with *** or ---) are
+// created with a trailing newline.
+//
+// For inputs that do not have trailing newlines, set the diff.Eol
+// argument to "" so that the output will be uniformly newline free.
+//
+// The context diff format normally has a header for filenames and
+// modification times. Any or all of these may be specified using
+// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
+// The modification times are normally expressed in the ISO 8601 format.
+// If not specified, the strings default to blanks.
+func WriteContextDiff(writer io.Writer, diff ContextDiff) error {
+ buf := bufio.NewWriter(writer)
+ defer buf.Flush()
+ var diffErr error
+ wf := func(format string, args ...interface{}) {
+ _, err := buf.WriteString(fmt.Sprintf(format, args...))
+ if diffErr == nil && err != nil {
+ diffErr = err
+ }
+ }
+ ws := func(s string) {
+ _, err := buf.WriteString(s)
+ if diffErr == nil && err != nil {
+ diffErr = err
+ }
+ }
+
+ if len(diff.Eol) == 0 {
+ diff.Eol = "\n"
+ }
+
+ prefix := map[byte]string{
+ 'i': "+ ",
+ 'd': "- ",
+ 'r': "! ",
+ 'e': " ",
+ }
+
+ started := false
+ m := NewMatcher(diff.A, diff.B)
+ for _, g := range m.GetGroupedOpCodes(diff.Context) {
+ if !started {
+ started = true
+ fromDate := ""
+ if len(diff.FromDate) > 0 {
+ fromDate = "\t" + diff.FromDate
+ }
+ toDate := ""
+ if len(diff.ToDate) > 0 {
+ toDate = "\t" + diff.ToDate
+ }
+ if diff.FromFile != "" || diff.ToFile != "" {
+ wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
+ wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
+ }
+ }
+
+ first, last := g[0], g[len(g)-1]
+ ws("***************" + diff.Eol)
+
+ range1 := formatRangeContext(first.I1, last.I2)
+ wf("*** %s ****%s", range1, diff.Eol)
+ for _, c := range g {
+ if c.Tag == 'r' || c.Tag == 'd' {
+ for _, cc := range g {
+ if cc.Tag == 'i' {
+ continue
+ }
+ for _, line := range diff.A[cc.I1:cc.I2] {
+ ws(prefix[cc.Tag] + line)
+ }
+ }
+ break
+ }
+ }
+
+ range2 := formatRangeContext(first.J1, last.J2)
+ wf("--- %s ----%s", range2, diff.Eol)
+ for _, c := range g {
+ if c.Tag == 'r' || c.Tag == 'i' {
+ for _, cc := range g {
+ if cc.Tag == 'd' {
+ continue
+ }
+ for _, line := range diff.B[cc.J1:cc.J2] {
+ ws(prefix[cc.Tag] + line)
+ }
+ }
+ break
+ }
+ }
+ }
+ return diffErr
+}
+
+// Like WriteContextDiff but returns the diff a string.
+func GetContextDiffString(diff ContextDiff) (string, error) {
+ w := &bytes.Buffer{}
+ err := WriteContextDiff(w, diff)
+ return string(w.Bytes()), err
+}
+
+// Split a string on "\n" while preserving them. The output can be used
+// as input for UnifiedDiff and ContextDiff structures.
+func SplitLines(s string) []string {
+ lines := strings.SplitAfter(s, "\n")
+ lines[len(lines)-1] += "\n"
+ return lines
+}
diff --git a/vendor/github.com/go-stack/stack/LICENSE.md b/vendor/github.com/stretchr/testify/LICENSE
similarity index 92%
rename from vendor/github.com/go-stack/stack/LICENSE.md
rename to vendor/github.com/stretchr/testify/LICENSE
index 2abf98ea..4b0421cf 100644
--- a/vendor/github.com/go-stack/stack/LICENSE.md
+++ b/vendor/github.com/stretchr/testify/LICENSE
@@ -1,6 +1,6 @@
-The MIT License (MIT)
+MIT License
-Copyright (c) 2014 Chris Hines
+Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare.go b/vendor/github.com/stretchr/testify/assert/assertion_compare.go
new file mode 100644
index 00000000..dc200395
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertion_compare.go
@@ -0,0 +1,274 @@
+package assert
+
+import (
+ "fmt"
+ "reflect"
+)
+
+type CompareType int
+
+const (
+ compareLess CompareType = iota - 1
+ compareEqual
+ compareGreater
+)
+
+func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
+ switch kind {
+ case reflect.Int:
+ {
+ intobj1 := obj1.(int)
+ intobj2 := obj2.(int)
+ if intobj1 > intobj2 {
+ return compareGreater, true
+ }
+ if intobj1 == intobj2 {
+ return compareEqual, true
+ }
+ if intobj1 < intobj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Int8:
+ {
+ int8obj1 := obj1.(int8)
+ int8obj2 := obj2.(int8)
+ if int8obj1 > int8obj2 {
+ return compareGreater, true
+ }
+ if int8obj1 == int8obj2 {
+ return compareEqual, true
+ }
+ if int8obj1 < int8obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Int16:
+ {
+ int16obj1 := obj1.(int16)
+ int16obj2 := obj2.(int16)
+ if int16obj1 > int16obj2 {
+ return compareGreater, true
+ }
+ if int16obj1 == int16obj2 {
+ return compareEqual, true
+ }
+ if int16obj1 < int16obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Int32:
+ {
+ int32obj1 := obj1.(int32)
+ int32obj2 := obj2.(int32)
+ if int32obj1 > int32obj2 {
+ return compareGreater, true
+ }
+ if int32obj1 == int32obj2 {
+ return compareEqual, true
+ }
+ if int32obj1 < int32obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Int64:
+ {
+ int64obj1 := obj1.(int64)
+ int64obj2 := obj2.(int64)
+ if int64obj1 > int64obj2 {
+ return compareGreater, true
+ }
+ if int64obj1 == int64obj2 {
+ return compareEqual, true
+ }
+ if int64obj1 < int64obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Uint:
+ {
+ uintobj1 := obj1.(uint)
+ uintobj2 := obj2.(uint)
+ if uintobj1 > uintobj2 {
+ return compareGreater, true
+ }
+ if uintobj1 == uintobj2 {
+ return compareEqual, true
+ }
+ if uintobj1 < uintobj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Uint8:
+ {
+ uint8obj1 := obj1.(uint8)
+ uint8obj2 := obj2.(uint8)
+ if uint8obj1 > uint8obj2 {
+ return compareGreater, true
+ }
+ if uint8obj1 == uint8obj2 {
+ return compareEqual, true
+ }
+ if uint8obj1 < uint8obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Uint16:
+ {
+ uint16obj1 := obj1.(uint16)
+ uint16obj2 := obj2.(uint16)
+ if uint16obj1 > uint16obj2 {
+ return compareGreater, true
+ }
+ if uint16obj1 == uint16obj2 {
+ return compareEqual, true
+ }
+ if uint16obj1 < uint16obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Uint32:
+ {
+ uint32obj1 := obj1.(uint32)
+ uint32obj2 := obj2.(uint32)
+ if uint32obj1 > uint32obj2 {
+ return compareGreater, true
+ }
+ if uint32obj1 == uint32obj2 {
+ return compareEqual, true
+ }
+ if uint32obj1 < uint32obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Uint64:
+ {
+ uint64obj1 := obj1.(uint64)
+ uint64obj2 := obj2.(uint64)
+ if uint64obj1 > uint64obj2 {
+ return compareGreater, true
+ }
+ if uint64obj1 == uint64obj2 {
+ return compareEqual, true
+ }
+ if uint64obj1 < uint64obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Float32:
+ {
+ float32obj1 := obj1.(float32)
+ float32obj2 := obj2.(float32)
+ if float32obj1 > float32obj2 {
+ return compareGreater, true
+ }
+ if float32obj1 == float32obj2 {
+ return compareEqual, true
+ }
+ if float32obj1 < float32obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.Float64:
+ {
+ float64obj1 := obj1.(float64)
+ float64obj2 := obj2.(float64)
+ if float64obj1 > float64obj2 {
+ return compareGreater, true
+ }
+ if float64obj1 == float64obj2 {
+ return compareEqual, true
+ }
+ if float64obj1 < float64obj2 {
+ return compareLess, true
+ }
+ }
+ case reflect.String:
+ {
+ stringobj1 := obj1.(string)
+ stringobj2 := obj2.(string)
+ if stringobj1 > stringobj2 {
+ return compareGreater, true
+ }
+ if stringobj1 == stringobj2 {
+ return compareEqual, true
+ }
+ if stringobj1 < stringobj2 {
+ return compareLess, true
+ }
+ }
+ }
+
+ return compareEqual, false
+}
+
+// Greater asserts that the first element is greater than the second
+//
+// assert.Greater(t, 2, 1)
+// assert.Greater(t, float64(2), float64(1))
+// assert.Greater(t, "b", "a")
+func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ return compareTwoValues(t, e1, e2, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs)
+}
+
+// GreaterOrEqual asserts that the first element is greater than or equal to the second
+//
+// assert.GreaterOrEqual(t, 2, 1)
+// assert.GreaterOrEqual(t, 2, 2)
+// assert.GreaterOrEqual(t, "b", "a")
+// assert.GreaterOrEqual(t, "b", "b")
+func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ return compareTwoValues(t, e1, e2, []CompareType{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs)
+}
+
+// Less asserts that the first element is less than the second
+//
+// assert.Less(t, 1, 2)
+// assert.Less(t, float64(1), float64(2))
+// assert.Less(t, "a", "b")
+func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ return compareTwoValues(t, e1, e2, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs)
+}
+
+// LessOrEqual asserts that the first element is less than or equal to the second
+//
+// assert.LessOrEqual(t, 1, 2)
+// assert.LessOrEqual(t, 2, 2)
+// assert.LessOrEqual(t, "a", "b")
+// assert.LessOrEqual(t, "b", "b")
+func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ return compareTwoValues(t, e1, e2, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs)
+}
+
+func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ e1Kind := reflect.ValueOf(e1).Kind()
+ e2Kind := reflect.ValueOf(e2).Kind()
+ if e1Kind != e2Kind {
+ return Fail(t, "Elements should be the same type", msgAndArgs...)
+ }
+
+ compareResult, isComparable := compare(e1, e2, e1Kind)
+ if !isComparable {
+ return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...)
+ }
+
+ if !containsValue(allowedComparesResults, compareResult) {
+ return Fail(t, fmt.Sprintf(failMessage, e1, e2), msgAndArgs...)
+ }
+
+ return true
+}
+
+func containsValue(values []CompareType, value CompareType) bool {
+ for _, v := range values {
+ if v == value {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go
new file mode 100644
index 00000000..49370eb1
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go
@@ -0,0 +1,644 @@
+/*
+* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
+* THIS FILE MUST NOT BE EDITED BY HAND
+ */
+
+package assert
+
+import (
+ http "net/http"
+ url "net/url"
+ time "time"
+)
+
+// Conditionf uses a Comparison to assert a complex condition.
+func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Condition(t, comp, append([]interface{}{msg}, args...)...)
+}
+
+// Containsf asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted")
+// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted")
+// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted")
+func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Contains(t, s, contains, append([]interface{}{msg}, args...)...)
+}
+
+// DirExistsf checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return DirExists(t, path, append([]interface{}{msg}, args...)...)
+}
+
+// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
+func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...)
+}
+
+// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// assert.Emptyf(t, obj, "error message %s", "formatted")
+func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Empty(t, object, append([]interface{}{msg}, args...)...)
+}
+
+// Equalf asserts that two objects are equal.
+//
+// assert.Equalf(t, 123, 123, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Equal(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted")
+func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...)
+}
+
+// EqualValuesf asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")
+func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// Errorf asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.Errorf(t, err, "error message %s", "formatted") {
+// assert.Equal(t, expectedErrorf, err)
+// }
+func Errorf(t TestingT, err error, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Error(t, err, append([]interface{}{msg}, args...)...)
+}
+
+// Eventuallyf asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Eventually(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...)
+}
+
+// Exactlyf asserts that two objects are equal in value and type.
+//
+// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted")
+func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// Failf reports a failure through
+func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(t, failureMessage, append([]interface{}{msg}, args...)...)
+}
+
+// FailNowf fails test
+func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...)
+}
+
+// Falsef asserts that the specified value is false.
+//
+// assert.Falsef(t, myBool, "error message %s", "formatted")
+func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return False(t, value, append([]interface{}{msg}, args...)...)
+}
+
+// FileExistsf checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return FileExists(t, path, append([]interface{}{msg}, args...)...)
+}
+
+// Greaterf asserts that the first element is greater than the second
+//
+// assert.Greaterf(t, 2, 1, "error message %s", "formatted")
+// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted")
+// assert.Greaterf(t, "b", "a", "error message %s", "formatted")
+func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Greater(t, e1, e2, append([]interface{}{msg}, args...)...)
+}
+
+// GreaterOrEqualf asserts that the first element is greater than or equal to the second
+//
+// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted")
+// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted")
+// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted")
+// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted")
+func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return GreaterOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...)
+}
+
+// HTTPBodyContainsf asserts that a specified handler returns a
+// body that contains a string.
+//
+// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...)
+}
+
+// HTTPBodyNotContainsf asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...)
+}
+
+// HTTPErrorf asserts that a specified handler returns an error status code.
+//
+// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...)
+}
+
+// HTTPRedirectf asserts that a specified handler returns a redirect status code.
+//
+// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...)
+}
+
+// HTTPStatusCodef asserts that a specified handler returns a specified status code.
+//
+// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPStatusCode(t, handler, method, url, values, statuscode, append([]interface{}{msg}, args...)...)
+}
+
+// HTTPSuccessf asserts that a specified handler returns a success status code.
+//
+// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...)
+}
+
+// Implementsf asserts that an object is implemented by the specified interface.
+//
+// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
+func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...)
+}
+
+// InDeltaf asserts that the two numerals are within delta of each other.
+//
+// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
+func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
+}
+
+// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
+}
+
+// InDeltaSlicef is the same as InDelta, except it compares two slices.
+func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
+}
+
+// InEpsilonf asserts that expected and actual have a relative error less than epsilon
+func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...)
+}
+
+// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices.
+func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...)
+}
+
+// IsTypef asserts that the specified objects are of the same type.
+func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...)
+}
+
+// JSONEqf asserts that two JSON strings are equivalent.
+//
+// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
+func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// Lenf asserts that the specified object has specific length.
+// Lenf also fails if the object has a type that len() not accept.
+//
+// assert.Lenf(t, mySlice, 3, "error message %s", "formatted")
+func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Len(t, object, length, append([]interface{}{msg}, args...)...)
+}
+
+// Lessf asserts that the first element is less than the second
+//
+// assert.Lessf(t, 1, 2, "error message %s", "formatted")
+// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted")
+// assert.Lessf(t, "a", "b", "error message %s", "formatted")
+func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Less(t, e1, e2, append([]interface{}{msg}, args...)...)
+}
+
+// LessOrEqualf asserts that the first element is less than or equal to the second
+//
+// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted")
+// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted")
+// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted")
+// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted")
+func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return LessOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...)
+}
+
+// Neverf asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Never(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...)
+}
+
+// Nilf asserts that the specified object is nil.
+//
+// assert.Nilf(t, err, "error message %s", "formatted")
+func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Nil(t, object, append([]interface{}{msg}, args...)...)
+}
+
+// NoDirExistsf checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoDirExists(t, path, append([]interface{}{msg}, args...)...)
+}
+
+// NoErrorf asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.NoErrorf(t, err, "error message %s", "formatted") {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoError(t, err, append([]interface{}{msg}, args...)...)
+}
+
+// NoFileExistsf checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoFileExists(t, path, append([]interface{}{msg}, args...)...)
+}
+
+// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted")
+// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted")
+// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted")
+func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotContains(t, s, contains, append([]interface{}{msg}, args...)...)
+}
+
+// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if assert.NotEmptyf(t, obj, "error message %s", "formatted") {
+// assert.Equal(t, "two", obj[1])
+// }
+func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEmpty(t, object, append([]interface{}{msg}, args...)...)
+}
+
+// NotEqualf asserts that the specified values are NOT equal.
+//
+// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// NotEqualValuesf asserts that two objects are not equal even when converted to the same type
+//
+// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted")
+func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// NotNilf asserts that the specified object is not nil.
+//
+// assert.NotNilf(t, err, "error message %s", "formatted")
+func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotNil(t, object, append([]interface{}{msg}, args...)...)
+}
+
+// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted")
+func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotPanics(t, f, append([]interface{}{msg}, args...)...)
+}
+
+// NotRegexpf asserts that a specified regexp does not match a string.
+//
+// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
+// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted")
+func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...)
+}
+
+// NotSamef asserts that two pointers do not reference the same object.
+//
+// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotSame(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// NotSubsetf asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted")
+func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...)
+}
+
+// NotZerof asserts that i is not the zero value for its type.
+func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotZero(t, i, append([]interface{}{msg}, args...)...)
+}
+
+// Panicsf asserts that the code inside the specified PanicTestFunc panics.
+//
+// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted")
+func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Panics(t, f, append([]interface{}{msg}, args...)...)
+}
+
+// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return PanicsWithError(t, errString, f, append([]interface{}{msg}, args...)...)
+}
+
+// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...)
+}
+
+// Regexpf asserts that a specified regexp matches a string.
+//
+// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
+// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted")
+func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Regexp(t, rx, str, append([]interface{}{msg}, args...)...)
+}
+
+// Samef asserts that two pointers reference the same object.
+//
+// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Same(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// Subsetf asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted")
+func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Subset(t, list, subset, append([]interface{}{msg}, args...)...)
+}
+
+// Truef asserts that the specified value is true.
+//
+// assert.Truef(t, myBool, "error message %s", "formatted")
+func Truef(t TestingT, value bool, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return True(t, value, append([]interface{}{msg}, args...)...)
+}
+
+// WithinDurationf asserts that the two times are within duration delta of each other.
+//
+// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
+func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
+}
+
+// YAMLEqf asserts that two YAML strings are equivalent.
+func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return YAMLEq(t, expected, actual, append([]interface{}{msg}, args...)...)
+}
+
+// Zerof asserts that i is the zero value for its type.
+func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Zero(t, i, append([]interface{}{msg}, args...)...)
+}
diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl
new file mode 100644
index 00000000..d2bb0b81
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl
@@ -0,0 +1,5 @@
+{{.CommentFormat}}
+func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool {
+ if h, ok := t.(tHelper); ok { h.Helper() }
+ return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}})
+}
diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go
new file mode 100644
index 00000000..9db88942
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go
@@ -0,0 +1,1276 @@
+/*
+* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
+* THIS FILE MUST NOT BE EDITED BY HAND
+ */
+
+package assert
+
+import (
+ http "net/http"
+ url "net/url"
+ time "time"
+)
+
+// Condition uses a Comparison to assert a complex condition.
+func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Condition(a.t, comp, msgAndArgs...)
+}
+
+// Conditionf uses a Comparison to assert a complex condition.
+func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Conditionf(a.t, comp, msg, args...)
+}
+
+// Contains asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// a.Contains("Hello World", "World")
+// a.Contains(["Hello", "World"], "World")
+// a.Contains({"Hello": "World"}, "Hello")
+func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Contains(a.t, s, contains, msgAndArgs...)
+}
+
+// Containsf asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// a.Containsf("Hello World", "World", "error message %s", "formatted")
+// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted")
+// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted")
+func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Containsf(a.t, s, contains, msg, args...)
+}
+
+// DirExists checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return DirExists(a.t, path, msgAndArgs...)
+}
+
+// DirExistsf checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return DirExistsf(a.t, path, msg, args...)
+}
+
+// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2])
+func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return ElementsMatch(a.t, listA, listB, msgAndArgs...)
+}
+
+// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
+func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return ElementsMatchf(a.t, listA, listB, msg, args...)
+}
+
+// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// a.Empty(obj)
+func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Empty(a.t, object, msgAndArgs...)
+}
+
+// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// a.Emptyf(obj, "error message %s", "formatted")
+func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Emptyf(a.t, object, msg, args...)
+}
+
+// Equal asserts that two objects are equal.
+//
+// a.Equal(123, 123)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Equal(a.t, expected, actual, msgAndArgs...)
+}
+
+// EqualError asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// a.EqualError(err, expectedErrorString)
+func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return EqualError(a.t, theError, errString, msgAndArgs...)
+}
+
+// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted")
+func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return EqualErrorf(a.t, theError, errString, msg, args...)
+}
+
+// EqualValues asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// a.EqualValues(uint32(123), int32(123))
+func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return EqualValues(a.t, expected, actual, msgAndArgs...)
+}
+
+// EqualValuesf asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted")
+func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return EqualValuesf(a.t, expected, actual, msg, args...)
+}
+
+// Equalf asserts that two objects are equal.
+//
+// a.Equalf(123, 123, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Equalf(a.t, expected, actual, msg, args...)
+}
+
+// Error asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.Error(err) {
+// assert.Equal(t, expectedError, err)
+// }
+func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Error(a.t, err, msgAndArgs...)
+}
+
+// Errorf asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.Errorf(err, "error message %s", "formatted") {
+// assert.Equal(t, expectedErrorf, err)
+// }
+func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Errorf(a.t, err, msg, args...)
+}
+
+// Eventually asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond)
+func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Eventually(a.t, condition, waitFor, tick, msgAndArgs...)
+}
+
+// Eventuallyf asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Eventuallyf(a.t, condition, waitFor, tick, msg, args...)
+}
+
+// Exactly asserts that two objects are equal in value and type.
+//
+// a.Exactly(int32(123), int64(123))
+func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Exactly(a.t, expected, actual, msgAndArgs...)
+}
+
+// Exactlyf asserts that two objects are equal in value and type.
+//
+// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted")
+func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Exactlyf(a.t, expected, actual, msg, args...)
+}
+
+// Fail reports a failure through
+func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(a.t, failureMessage, msgAndArgs...)
+}
+
+// FailNow fails test
+func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return FailNow(a.t, failureMessage, msgAndArgs...)
+}
+
+// FailNowf fails test
+func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return FailNowf(a.t, failureMessage, msg, args...)
+}
+
+// Failf reports a failure through
+func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Failf(a.t, failureMessage, msg, args...)
+}
+
+// False asserts that the specified value is false.
+//
+// a.False(myBool)
+func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return False(a.t, value, msgAndArgs...)
+}
+
+// Falsef asserts that the specified value is false.
+//
+// a.Falsef(myBool, "error message %s", "formatted")
+func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Falsef(a.t, value, msg, args...)
+}
+
+// FileExists checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return FileExists(a.t, path, msgAndArgs...)
+}
+
+// FileExistsf checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return FileExistsf(a.t, path, msg, args...)
+}
+
+// Greater asserts that the first element is greater than the second
+//
+// a.Greater(2, 1)
+// a.Greater(float64(2), float64(1))
+// a.Greater("b", "a")
+func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Greater(a.t, e1, e2, msgAndArgs...)
+}
+
+// GreaterOrEqual asserts that the first element is greater than or equal to the second
+//
+// a.GreaterOrEqual(2, 1)
+// a.GreaterOrEqual(2, 2)
+// a.GreaterOrEqual("b", "a")
+// a.GreaterOrEqual("b", "b")
+func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return GreaterOrEqual(a.t, e1, e2, msgAndArgs...)
+}
+
+// GreaterOrEqualf asserts that the first element is greater than or equal to the second
+//
+// a.GreaterOrEqualf(2, 1, "error message %s", "formatted")
+// a.GreaterOrEqualf(2, 2, "error message %s", "formatted")
+// a.GreaterOrEqualf("b", "a", "error message %s", "formatted")
+// a.GreaterOrEqualf("b", "b", "error message %s", "formatted")
+func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return GreaterOrEqualf(a.t, e1, e2, msg, args...)
+}
+
+// Greaterf asserts that the first element is greater than the second
+//
+// a.Greaterf(2, 1, "error message %s", "formatted")
+// a.Greaterf(float64(2), float64(1), "error message %s", "formatted")
+// a.Greaterf("b", "a", "error message %s", "formatted")
+func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Greaterf(a.t, e1, e2, msg, args...)
+}
+
+// HTTPBodyContains asserts that a specified handler returns a
+// body that contains a string.
+//
+// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...)
+}
+
+// HTTPBodyContainsf asserts that a specified handler returns a
+// body that contains a string.
+//
+// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...)
+}
+
+// HTTPBodyNotContains asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...)
+}
+
+// HTTPBodyNotContainsf asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...)
+}
+
+// HTTPError asserts that a specified handler returns an error status code.
+//
+// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPError(a.t, handler, method, url, values, msgAndArgs...)
+}
+
+// HTTPErrorf asserts that a specified handler returns an error status code.
+//
+// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPErrorf(a.t, handler, method, url, values, msg, args...)
+}
+
+// HTTPRedirect asserts that a specified handler returns a redirect status code.
+//
+// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...)
+}
+
+// HTTPRedirectf asserts that a specified handler returns a redirect status code.
+//
+// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPRedirectf(a.t, handler, method, url, values, msg, args...)
+}
+
+// HTTPStatusCode asserts that a specified handler returns a specified status code.
+//
+// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...)
+}
+
+// HTTPStatusCodef asserts that a specified handler returns a specified status code.
+//
+// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...)
+}
+
+// HTTPSuccess asserts that a specified handler returns a success status code.
+//
+// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...)
+}
+
+// HTTPSuccessf asserts that a specified handler returns a success status code.
+//
+// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return HTTPSuccessf(a.t, handler, method, url, values, msg, args...)
+}
+
+// Implements asserts that an object is implemented by the specified interface.
+//
+// a.Implements((*MyInterface)(nil), new(MyObject))
+func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Implements(a.t, interfaceObject, object, msgAndArgs...)
+}
+
+// Implementsf asserts that an object is implemented by the specified interface.
+//
+// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
+func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Implementsf(a.t, interfaceObject, object, msg, args...)
+}
+
+// InDelta asserts that the two numerals are within delta of each other.
+//
+// a.InDelta(math.Pi, 22/7.0, 0.01)
+func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDelta(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...)
+}
+
+// InDeltaSlice is the same as InDelta, except it compares two slices.
+func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// InDeltaSlicef is the same as InDelta, except it compares two slices.
+func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDeltaSlicef(a.t, expected, actual, delta, msg, args...)
+}
+
+// InDeltaf asserts that the two numerals are within delta of each other.
+//
+// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
+func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InDeltaf(a.t, expected, actual, delta, msg, args...)
+}
+
+// InEpsilon asserts that expected and actual have a relative error less than epsilon
+func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...)
+}
+
+// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
+func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...)
+}
+
+// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices.
+func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...)
+}
+
+// InEpsilonf asserts that expected and actual have a relative error less than epsilon
+func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return InEpsilonf(a.t, expected, actual, epsilon, msg, args...)
+}
+
+// IsType asserts that the specified objects are of the same type.
+func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return IsType(a.t, expectedType, object, msgAndArgs...)
+}
+
+// IsTypef asserts that the specified objects are of the same type.
+func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return IsTypef(a.t, expectedType, object, msg, args...)
+}
+
+// JSONEq asserts that two JSON strings are equivalent.
+//
+// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
+func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return JSONEq(a.t, expected, actual, msgAndArgs...)
+}
+
+// JSONEqf asserts that two JSON strings are equivalent.
+//
+// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
+func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return JSONEqf(a.t, expected, actual, msg, args...)
+}
+
+// Len asserts that the specified object has specific length.
+// Len also fails if the object has a type that len() not accept.
+//
+// a.Len(mySlice, 3)
+func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Len(a.t, object, length, msgAndArgs...)
+}
+
+// Lenf asserts that the specified object has specific length.
+// Lenf also fails if the object has a type that len() not accept.
+//
+// a.Lenf(mySlice, 3, "error message %s", "formatted")
+func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Lenf(a.t, object, length, msg, args...)
+}
+
+// Less asserts that the first element is less than the second
+//
+// a.Less(1, 2)
+// a.Less(float64(1), float64(2))
+// a.Less("a", "b")
+func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Less(a.t, e1, e2, msgAndArgs...)
+}
+
+// LessOrEqual asserts that the first element is less than or equal to the second
+//
+// a.LessOrEqual(1, 2)
+// a.LessOrEqual(2, 2)
+// a.LessOrEqual("a", "b")
+// a.LessOrEqual("b", "b")
+func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return LessOrEqual(a.t, e1, e2, msgAndArgs...)
+}
+
+// LessOrEqualf asserts that the first element is less than or equal to the second
+//
+// a.LessOrEqualf(1, 2, "error message %s", "formatted")
+// a.LessOrEqualf(2, 2, "error message %s", "formatted")
+// a.LessOrEqualf("a", "b", "error message %s", "formatted")
+// a.LessOrEqualf("b", "b", "error message %s", "formatted")
+func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return LessOrEqualf(a.t, e1, e2, msg, args...)
+}
+
+// Lessf asserts that the first element is less than the second
+//
+// a.Lessf(1, 2, "error message %s", "formatted")
+// a.Lessf(float64(1), float64(2), "error message %s", "formatted")
+// a.Lessf("a", "b", "error message %s", "formatted")
+func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Lessf(a.t, e1, e2, msg, args...)
+}
+
+// Never asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond)
+func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Never(a.t, condition, waitFor, tick, msgAndArgs...)
+}
+
+// Neverf asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Neverf(a.t, condition, waitFor, tick, msg, args...)
+}
+
+// Nil asserts that the specified object is nil.
+//
+// a.Nil(err)
+func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Nil(a.t, object, msgAndArgs...)
+}
+
+// Nilf asserts that the specified object is nil.
+//
+// a.Nilf(err, "error message %s", "formatted")
+func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Nilf(a.t, object, msg, args...)
+}
+
+// NoDirExists checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func (a *Assertions) NoDirExists(path string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoDirExists(a.t, path, msgAndArgs...)
+}
+
+// NoDirExistsf checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoDirExistsf(a.t, path, msg, args...)
+}
+
+// NoError asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.NoError(err) {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoError(a.t, err, msgAndArgs...)
+}
+
+// NoErrorf asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.NoErrorf(err, "error message %s", "formatted") {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoErrorf(a.t, err, msg, args...)
+}
+
+// NoFileExists checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func (a *Assertions) NoFileExists(path string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoFileExists(a.t, path, msgAndArgs...)
+}
+
+// NoFileExistsf checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NoFileExistsf(a.t, path, msg, args...)
+}
+
+// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// a.NotContains("Hello World", "Earth")
+// a.NotContains(["Hello", "World"], "Earth")
+// a.NotContains({"Hello": "World"}, "Earth")
+func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotContains(a.t, s, contains, msgAndArgs...)
+}
+
+// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted")
+// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted")
+// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted")
+func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotContainsf(a.t, s, contains, msg, args...)
+}
+
+// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if a.NotEmpty(obj) {
+// assert.Equal(t, "two", obj[1])
+// }
+func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEmpty(a.t, object, msgAndArgs...)
+}
+
+// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if a.NotEmptyf(obj, "error message %s", "formatted") {
+// assert.Equal(t, "two", obj[1])
+// }
+func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEmptyf(a.t, object, msg, args...)
+}
+
+// NotEqual asserts that the specified values are NOT equal.
+//
+// a.NotEqual(obj1, obj2)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEqual(a.t, expected, actual, msgAndArgs...)
+}
+
+// NotEqualValues asserts that two objects are not equal even when converted to the same type
+//
+// a.NotEqualValues(obj1, obj2)
+func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEqualValues(a.t, expected, actual, msgAndArgs...)
+}
+
+// NotEqualValuesf asserts that two objects are not equal even when converted to the same type
+//
+// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted")
+func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEqualValuesf(a.t, expected, actual, msg, args...)
+}
+
+// NotEqualf asserts that the specified values are NOT equal.
+//
+// a.NotEqualf(obj1, obj2, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotEqualf(a.t, expected, actual, msg, args...)
+}
+
+// NotNil asserts that the specified object is not nil.
+//
+// a.NotNil(err)
+func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotNil(a.t, object, msgAndArgs...)
+}
+
+// NotNilf asserts that the specified object is not nil.
+//
+// a.NotNilf(err, "error message %s", "formatted")
+func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotNilf(a.t, object, msg, args...)
+}
+
+// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// a.NotPanics(func(){ RemainCalm() })
+func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotPanics(a.t, f, msgAndArgs...)
+}
+
+// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted")
+func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotPanicsf(a.t, f, msg, args...)
+}
+
+// NotRegexp asserts that a specified regexp does not match a string.
+//
+// a.NotRegexp(regexp.MustCompile("starts"), "it's starting")
+// a.NotRegexp("^start", "it's not starting")
+func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotRegexp(a.t, rx, str, msgAndArgs...)
+}
+
+// NotRegexpf asserts that a specified regexp does not match a string.
+//
+// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
+// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted")
+func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotRegexpf(a.t, rx, str, msg, args...)
+}
+
+// NotSame asserts that two pointers do not reference the same object.
+//
+// a.NotSame(ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotSame(a.t, expected, actual, msgAndArgs...)
+}
+
+// NotSamef asserts that two pointers do not reference the same object.
+//
+// a.NotSamef(ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotSamef(a.t, expected, actual, msg, args...)
+}
+
+// NotSubset asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
+func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotSubset(a.t, list, subset, msgAndArgs...)
+}
+
+// NotSubsetf asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted")
+func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotSubsetf(a.t, list, subset, msg, args...)
+}
+
+// NotZero asserts that i is not the zero value for its type.
+func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotZero(a.t, i, msgAndArgs...)
+}
+
+// NotZerof asserts that i is not the zero value for its type.
+func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotZerof(a.t, i, msg, args...)
+}
+
+// Panics asserts that the code inside the specified PanicTestFunc panics.
+//
+// a.Panics(func(){ GoCrazy() })
+func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Panics(a.t, f, msgAndArgs...)
+}
+
+// PanicsWithError asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// a.PanicsWithError("crazy error", func(){ GoCrazy() })
+func (a *Assertions) PanicsWithError(errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return PanicsWithError(a.t, errString, f, msgAndArgs...)
+}
+
+// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func (a *Assertions) PanicsWithErrorf(errString string, f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return PanicsWithErrorf(a.t, errString, f, msg, args...)
+}
+
+// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// a.PanicsWithValue("crazy error", func(){ GoCrazy() })
+func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return PanicsWithValue(a.t, expected, f, msgAndArgs...)
+}
+
+// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return PanicsWithValuef(a.t, expected, f, msg, args...)
+}
+
+// Panicsf asserts that the code inside the specified PanicTestFunc panics.
+//
+// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted")
+func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Panicsf(a.t, f, msg, args...)
+}
+
+// Regexp asserts that a specified regexp matches a string.
+//
+// a.Regexp(regexp.MustCompile("start"), "it's starting")
+// a.Regexp("start...$", "it's not starting")
+func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Regexp(a.t, rx, str, msgAndArgs...)
+}
+
+// Regexpf asserts that a specified regexp matches a string.
+//
+// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
+// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted")
+func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Regexpf(a.t, rx, str, msg, args...)
+}
+
+// Same asserts that two pointers reference the same object.
+//
+// a.Same(ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Same(a.t, expected, actual, msgAndArgs...)
+}
+
+// Samef asserts that two pointers reference the same object.
+//
+// a.Samef(ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Samef(a.t, expected, actual, msg, args...)
+}
+
+// Subset asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
+func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Subset(a.t, list, subset, msgAndArgs...)
+}
+
+// Subsetf asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted")
+func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Subsetf(a.t, list, subset, msg, args...)
+}
+
+// True asserts that the specified value is true.
+//
+// a.True(myBool)
+func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return True(a.t, value, msgAndArgs...)
+}
+
+// Truef asserts that the specified value is true.
+//
+// a.Truef(myBool, "error message %s", "formatted")
+func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Truef(a.t, value, msg, args...)
+}
+
+// WithinDuration asserts that the two times are within duration delta of each other.
+//
+// a.WithinDuration(time.Now(), time.Now(), 10*time.Second)
+func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return WithinDuration(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// WithinDurationf asserts that the two times are within duration delta of each other.
+//
+// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
+func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return WithinDurationf(a.t, expected, actual, delta, msg, args...)
+}
+
+// YAMLEq asserts that two YAML strings are equivalent.
+func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return YAMLEq(a.t, expected, actual, msgAndArgs...)
+}
+
+// YAMLEqf asserts that two YAML strings are equivalent.
+func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return YAMLEqf(a.t, expected, actual, msg, args...)
+}
+
+// Zero asserts that i is the zero value for its type.
+func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Zero(a.t, i, msgAndArgs...)
+}
+
+// Zerof asserts that i is the zero value for its type.
+func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return Zerof(a.t, i, msg, args...)
+}
diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl
new file mode 100644
index 00000000..188bb9e1
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl
@@ -0,0 +1,5 @@
+{{.CommentWithoutT "a"}}
+func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool {
+ if h, ok := a.t.(tHelper); ok { h.Helper() }
+ return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}})
+}
diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go
new file mode 100644
index 00000000..914a10d8
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertions.go
@@ -0,0 +1,1695 @@
+package assert
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "os"
+ "reflect"
+ "regexp"
+ "runtime"
+ "runtime/debug"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/davecgh/go-spew/spew"
+ "github.com/pmezard/go-difflib/difflib"
+ yaml "gopkg.in/yaml.v3"
+)
+
+//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
+
+// TestingT is an interface wrapper around *testing.T
+type TestingT interface {
+ Errorf(format string, args ...interface{})
+}
+
+// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
+// for table driven tests.
+type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
+
+// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
+// for table driven tests.
+type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
+
+// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
+// for table driven tests.
+type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
+
+// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
+// for table driven tests.
+type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
+
+// Comparison is a custom function that returns true on success and false on failure
+type Comparison func() (success bool)
+
+/*
+ Helper functions
+*/
+
+// ObjectsAreEqual determines if two objects are considered equal.
+//
+// This function does no assertion of any kind.
+func ObjectsAreEqual(expected, actual interface{}) bool {
+ if expected == nil || actual == nil {
+ return expected == actual
+ }
+
+ exp, ok := expected.([]byte)
+ if !ok {
+ return reflect.DeepEqual(expected, actual)
+ }
+
+ act, ok := actual.([]byte)
+ if !ok {
+ return false
+ }
+ if exp == nil || act == nil {
+ return exp == nil && act == nil
+ }
+ return bytes.Equal(exp, act)
+}
+
+// ObjectsAreEqualValues gets whether two objects are equal, or if their
+// values are equal.
+func ObjectsAreEqualValues(expected, actual interface{}) bool {
+ if ObjectsAreEqual(expected, actual) {
+ return true
+ }
+
+ actualType := reflect.TypeOf(actual)
+ if actualType == nil {
+ return false
+ }
+ expectedValue := reflect.ValueOf(expected)
+ if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
+ // Attempt comparison after type conversion
+ return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
+ }
+
+ return false
+}
+
+/* CallerInfo is necessary because the assert functions use the testing object
+internally, causing it to print the file:line of the assert method, rather than where
+the problem actually occurred in calling code.*/
+
+// CallerInfo returns an array of strings containing the file and line number
+// of each stack frame leading from the current test to the assert call that
+// failed.
+func CallerInfo() []string {
+
+ var pc uintptr
+ var ok bool
+ var file string
+ var line int
+ var name string
+
+ callers := []string{}
+ for i := 0; ; i++ {
+ pc, file, line, ok = runtime.Caller(i)
+ if !ok {
+ // The breaks below failed to terminate the loop, and we ran off the
+ // end of the call stack.
+ break
+ }
+
+ // This is a huge edge case, but it will panic if this is the case, see #180
+ if file == "" {
+ break
+ }
+
+ f := runtime.FuncForPC(pc)
+ if f == nil {
+ break
+ }
+ name = f.Name()
+
+ // testing.tRunner is the standard library function that calls
+ // tests. Subtests are called directly by tRunner, without going through
+ // the Test/Benchmark/Example function that contains the t.Run calls, so
+ // with subtests we should break when we hit tRunner, without adding it
+ // to the list of callers.
+ if name == "testing.tRunner" {
+ break
+ }
+
+ parts := strings.Split(file, "/")
+ file = parts[len(parts)-1]
+ if len(parts) > 1 {
+ dir := parts[len(parts)-2]
+ if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
+ callers = append(callers, fmt.Sprintf("%s:%d", file, line))
+ }
+ }
+
+ // Drop the package
+ segments := strings.Split(name, ".")
+ name = segments[len(segments)-1]
+ if isTest(name, "Test") ||
+ isTest(name, "Benchmark") ||
+ isTest(name, "Example") {
+ break
+ }
+ }
+
+ return callers
+}
+
+// Stolen from the `go test` tool.
+// isTest tells whether name looks like a test (or benchmark, according to prefix).
+// It is a Test (say) if there is a character after Test that is not a lower-case letter.
+// We don't want TesticularCancer.
+func isTest(name, prefix string) bool {
+ if !strings.HasPrefix(name, prefix) {
+ return false
+ }
+ if len(name) == len(prefix) { // "Test" is ok
+ return true
+ }
+ rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
+ return !unicode.IsLower(rune)
+}
+
+func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
+ if len(msgAndArgs) == 0 || msgAndArgs == nil {
+ return ""
+ }
+ if len(msgAndArgs) == 1 {
+ msg := msgAndArgs[0]
+ if msgAsStr, ok := msg.(string); ok {
+ return msgAsStr
+ }
+ return fmt.Sprintf("%+v", msg)
+ }
+ if len(msgAndArgs) > 1 {
+ return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
+ }
+ return ""
+}
+
+// Aligns the provided message so that all lines after the first line start at the same location as the first line.
+// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
+// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
+// basis on which the alignment occurs).
+func indentMessageLines(message string, longestLabelLen int) string {
+ outBuf := new(bytes.Buffer)
+
+ for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
+ // no need to align first line because it starts at the correct location (after the label)
+ if i != 0 {
+ // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
+ outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
+ }
+ outBuf.WriteString(scanner.Text())
+ }
+
+ return outBuf.String()
+}
+
+type failNower interface {
+ FailNow()
+}
+
+// FailNow fails test
+func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ Fail(t, failureMessage, msgAndArgs...)
+
+ // We cannot extend TestingT with FailNow() and
+ // maintain backwards compatibility, so we fallback
+ // to panicking when FailNow is not available in
+ // TestingT.
+ // See issue #263
+
+ if t, ok := t.(failNower); ok {
+ t.FailNow()
+ } else {
+ panic("test failed and t is missing `FailNow()`")
+ }
+ return false
+}
+
+// Fail reports a failure through
+func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ content := []labeledContent{
+ {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
+ {"Error", failureMessage},
+ }
+
+ // Add test name if the Go version supports it
+ if n, ok := t.(interface {
+ Name() string
+ }); ok {
+ content = append(content, labeledContent{"Test", n.Name()})
+ }
+
+ message := messageFromMsgAndArgs(msgAndArgs...)
+ if len(message) > 0 {
+ content = append(content, labeledContent{"Messages", message})
+ }
+
+ t.Errorf("\n%s", ""+labeledOutput(content...))
+
+ return false
+}
+
+type labeledContent struct {
+ label string
+ content string
+}
+
+// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
+//
+// \t{{label}}:{{align_spaces}}\t{{content}}\n
+//
+// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
+// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
+// alignment is achieved, "\t{{content}}\n" is added for the output.
+//
+// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
+func labeledOutput(content ...labeledContent) string {
+ longestLabel := 0
+ for _, v := range content {
+ if len(v.label) > longestLabel {
+ longestLabel = len(v.label)
+ }
+ }
+ var output string
+ for _, v := range content {
+ output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
+ }
+ return output
+}
+
+// Implements asserts that an object is implemented by the specified interface.
+//
+// assert.Implements(t, (*MyInterface)(nil), new(MyObject))
+func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ interfaceType := reflect.TypeOf(interfaceObject).Elem()
+
+ if object == nil {
+ return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
+ }
+ if !reflect.TypeOf(object).Implements(interfaceType) {
+ return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
+ }
+
+ return true
+}
+
+// IsType asserts that the specified objects are of the same type.
+func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
+ return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
+ }
+
+ return true
+}
+
+// Equal asserts that two objects are equal.
+//
+// assert.Equal(t, 123, 123)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if err := validateEqualArgs(expected, actual); err != nil {
+ return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
+ expected, actual, err), msgAndArgs...)
+ }
+
+ if !ObjectsAreEqual(expected, actual) {
+ diff := diff(expected, actual)
+ expected, actual = formatUnequalValues(expected, actual)
+ return Fail(t, fmt.Sprintf("Not equal: \n"+
+ "expected: %s\n"+
+ "actual : %s%s", expected, actual, diff), msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// validateEqualArgs checks whether provided arguments can be safely used in the
+// Equal/NotEqual functions.
+func validateEqualArgs(expected, actual interface{}) error {
+ if expected == nil && actual == nil {
+ return nil
+ }
+
+ if isFunction(expected) || isFunction(actual) {
+ return errors.New("cannot take func type as argument")
+ }
+ return nil
+}
+
+// Same asserts that two pointers reference the same object.
+//
+// assert.Same(t, ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ if !samePointers(expected, actual) {
+ return Fail(t, fmt.Sprintf("Not same: \n"+
+ "expected: %p %#v\n"+
+ "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
+ }
+
+ return true
+}
+
+// NotSame asserts that two pointers do not reference the same object.
+//
+// assert.NotSame(t, ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ if samePointers(expected, actual) {
+ return Fail(t, fmt.Sprintf(
+ "Expected and actual point to the same object: %p %#v",
+ expected, expected), msgAndArgs...)
+ }
+ return true
+}
+
+// samePointers compares two generic interface objects and returns whether
+// they point to the same object
+func samePointers(first, second interface{}) bool {
+ firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
+ if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
+ return false
+ }
+
+ firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
+ if firstType != secondType {
+ return false
+ }
+
+ // compare pointer addresses
+ return first == second
+}
+
+// formatUnequalValues takes two values of arbitrary types and returns string
+// representations appropriate to be presented to the user.
+//
+// If the values are not of like type, the returned strings will be prefixed
+// with the type name, and the value will be enclosed in parenthesis similar
+// to a type conversion in the Go grammar.
+func formatUnequalValues(expected, actual interface{}) (e string, a string) {
+ if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
+ return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
+ fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
+ }
+ switch expected.(type) {
+ case time.Duration:
+ return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
+ }
+ return truncatingFormat(expected), truncatingFormat(actual)
+}
+
+// truncatingFormat formats the data and truncates it if it's too long.
+//
+// This helps keep formatted error messages lines from exceeding the
+// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
+func truncatingFormat(data interface{}) string {
+ value := fmt.Sprintf("%#v", data)
+ max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
+ if len(value) > max {
+ value = value[0:max] + "<... truncated>"
+ }
+ return value
+}
+
+// EqualValues asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// assert.EqualValues(t, uint32(123), int32(123))
+func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ if !ObjectsAreEqualValues(expected, actual) {
+ diff := diff(expected, actual)
+ expected, actual = formatUnequalValues(expected, actual)
+ return Fail(t, fmt.Sprintf("Not equal: \n"+
+ "expected: %s\n"+
+ "actual : %s%s", expected, actual, diff), msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// Exactly asserts that two objects are equal in value and type.
+//
+// assert.Exactly(t, int32(123), int64(123))
+func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ aType := reflect.TypeOf(expected)
+ bType := reflect.TypeOf(actual)
+
+ if aType != bType {
+ return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
+ }
+
+ return Equal(t, expected, actual, msgAndArgs...)
+
+}
+
+// NotNil asserts that the specified object is not nil.
+//
+// assert.NotNil(t, err)
+func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
+ if !isNil(object) {
+ return true
+ }
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(t, "Expected value not to be nil.", msgAndArgs...)
+}
+
+// containsKind checks if a specified kind in the slice of kinds.
+func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool {
+ for i := 0; i < len(kinds); i++ {
+ if kind == kinds[i] {
+ return true
+ }
+ }
+
+ return false
+}
+
+// isNil checks if a specified object is nil or not, without Failing.
+func isNil(object interface{}) bool {
+ if object == nil {
+ return true
+ }
+
+ value := reflect.ValueOf(object)
+ kind := value.Kind()
+ isNilableKind := containsKind(
+ []reflect.Kind{
+ reflect.Chan, reflect.Func,
+ reflect.Interface, reflect.Map,
+ reflect.Ptr, reflect.Slice},
+ kind)
+
+ if isNilableKind && value.IsNil() {
+ return true
+ }
+
+ return false
+}
+
+// Nil asserts that the specified object is nil.
+//
+// assert.Nil(t, err)
+func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
+ if isNil(object) {
+ return true
+ }
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
+}
+
+// isEmpty gets whether the specified object is considered empty or not.
+func isEmpty(object interface{}) bool {
+
+ // get nil case out of the way
+ if object == nil {
+ return true
+ }
+
+ objValue := reflect.ValueOf(object)
+
+ switch objValue.Kind() {
+ // collection types are empty when they have no element
+ case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+ return objValue.Len() == 0
+ // pointers are empty if nil or if the value they point to is empty
+ case reflect.Ptr:
+ if objValue.IsNil() {
+ return true
+ }
+ deref := objValue.Elem().Interface()
+ return isEmpty(deref)
+ // for all other types, compare against the zero value
+ default:
+ zero := reflect.Zero(objValue.Type())
+ return reflect.DeepEqual(object, zero.Interface())
+ }
+}
+
+// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// assert.Empty(t, obj)
+func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
+ pass := isEmpty(object)
+ if !pass {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
+ }
+
+ return pass
+
+}
+
+// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if assert.NotEmpty(t, obj) {
+// assert.Equal(t, "two", obj[1])
+// }
+func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
+ pass := !isEmpty(object)
+ if !pass {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
+ }
+
+ return pass
+
+}
+
+// getLen try to get length of object.
+// return (false, 0) if impossible.
+func getLen(x interface{}) (ok bool, length int) {
+ v := reflect.ValueOf(x)
+ defer func() {
+ if e := recover(); e != nil {
+ ok = false
+ }
+ }()
+ return true, v.Len()
+}
+
+// Len asserts that the specified object has specific length.
+// Len also fails if the object has a type that len() not accept.
+//
+// assert.Len(t, mySlice, 3)
+func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ ok, l := getLen(object)
+ if !ok {
+ return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
+ }
+
+ if l != length {
+ return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
+ }
+ return true
+}
+
+// True asserts that the specified value is true.
+//
+// assert.True(t, myBool)
+func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
+ if !value {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(t, "Should be true", msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// False asserts that the specified value is false.
+//
+// assert.False(t, myBool)
+func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
+ if value {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(t, "Should be false", msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// NotEqual asserts that the specified values are NOT equal.
+//
+// assert.NotEqual(t, obj1, obj2)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if err := validateEqualArgs(expected, actual); err != nil {
+ return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
+ expected, actual, err), msgAndArgs...)
+ }
+
+ if ObjectsAreEqual(expected, actual) {
+ return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// NotEqualValues asserts that two objects are not equal even when converted to the same type
+//
+// assert.NotEqualValues(t, obj1, obj2)
+func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ if ObjectsAreEqualValues(expected, actual) {
+ return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
+ }
+
+ return true
+}
+
+// containsElement try loop over the list check if the list includes the element.
+// return (false, false) if impossible.
+// return (true, false) if element was not found.
+// return (true, true) if element was found.
+func includeElement(list interface{}, element interface{}) (ok, found bool) {
+
+ listValue := reflect.ValueOf(list)
+ listKind := reflect.TypeOf(list).Kind()
+ defer func() {
+ if e := recover(); e != nil {
+ ok = false
+ found = false
+ }
+ }()
+
+ if listKind == reflect.String {
+ elementValue := reflect.ValueOf(element)
+ return true, strings.Contains(listValue.String(), elementValue.String())
+ }
+
+ if listKind == reflect.Map {
+ mapKeys := listValue.MapKeys()
+ for i := 0; i < len(mapKeys); i++ {
+ if ObjectsAreEqual(mapKeys[i].Interface(), element) {
+ return true, true
+ }
+ }
+ return true, false
+ }
+
+ for i := 0; i < listValue.Len(); i++ {
+ if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
+ return true, true
+ }
+ }
+ return true, false
+
+}
+
+// Contains asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// assert.Contains(t, "Hello World", "World")
+// assert.Contains(t, ["Hello", "World"], "World")
+// assert.Contains(t, {"Hello": "World"}, "Hello")
+func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ ok, found := includeElement(s, contains)
+ if !ok {
+ return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
+ }
+ if !found {
+ return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// assert.NotContains(t, "Hello World", "Earth")
+// assert.NotContains(t, ["Hello", "World"], "Earth")
+// assert.NotContains(t, {"Hello": "World"}, "Earth")
+func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ ok, found := includeElement(s, contains)
+ if !ok {
+ return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
+ }
+ if found {
+ return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// Subset asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
+func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if subset == nil {
+ return true // we consider nil to be equal to the nil set
+ }
+
+ subsetValue := reflect.ValueOf(subset)
+ defer func() {
+ if e := recover(); e != nil {
+ ok = false
+ }
+ }()
+
+ listKind := reflect.TypeOf(list).Kind()
+ subsetKind := reflect.TypeOf(subset).Kind()
+
+ if listKind != reflect.Array && listKind != reflect.Slice {
+ return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
+ }
+
+ if subsetKind != reflect.Array && subsetKind != reflect.Slice {
+ return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
+ }
+
+ for i := 0; i < subsetValue.Len(); i++ {
+ element := subsetValue.Index(i).Interface()
+ ok, found := includeElement(list, element)
+ if !ok {
+ return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
+ }
+ if !found {
+ return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
+ }
+ }
+
+ return true
+}
+
+// NotSubset asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
+func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if subset == nil {
+ return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...)
+ }
+
+ subsetValue := reflect.ValueOf(subset)
+ defer func() {
+ if e := recover(); e != nil {
+ ok = false
+ }
+ }()
+
+ listKind := reflect.TypeOf(list).Kind()
+ subsetKind := reflect.TypeOf(subset).Kind()
+
+ if listKind != reflect.Array && listKind != reflect.Slice {
+ return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
+ }
+
+ if subsetKind != reflect.Array && subsetKind != reflect.Slice {
+ return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
+ }
+
+ for i := 0; i < subsetValue.Len(); i++ {
+ element := subsetValue.Index(i).Interface()
+ ok, found := includeElement(list, element)
+ if !ok {
+ return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
+ }
+ if !found {
+ return true
+ }
+ }
+
+ return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
+}
+
+// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
+func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if isEmpty(listA) && isEmpty(listB) {
+ return true
+ }
+
+ if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
+ return false
+ }
+
+ extraA, extraB := diffLists(listA, listB)
+
+ if len(extraA) == 0 && len(extraB) == 0 {
+ return true
+ }
+
+ return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
+}
+
+// isList checks that the provided value is array or slice.
+func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
+ kind := reflect.TypeOf(list).Kind()
+ if kind != reflect.Array && kind != reflect.Slice {
+ return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
+ msgAndArgs...)
+ }
+ return true
+}
+
+// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
+// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
+// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
+func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
+ aValue := reflect.ValueOf(listA)
+ bValue := reflect.ValueOf(listB)
+
+ aLen := aValue.Len()
+ bLen := bValue.Len()
+
+ // Mark indexes in bValue that we already used
+ visited := make([]bool, bLen)
+ for i := 0; i < aLen; i++ {
+ element := aValue.Index(i).Interface()
+ found := false
+ for j := 0; j < bLen; j++ {
+ if visited[j] {
+ continue
+ }
+ if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
+ visited[j] = true
+ found = true
+ break
+ }
+ }
+ if !found {
+ extraA = append(extraA, element)
+ }
+ }
+
+ for j := 0; j < bLen; j++ {
+ if visited[j] {
+ continue
+ }
+ extraB = append(extraB, bValue.Index(j).Interface())
+ }
+
+ return
+}
+
+func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
+ var msg bytes.Buffer
+
+ msg.WriteString("elements differ")
+ if len(extraA) > 0 {
+ msg.WriteString("\n\nextra elements in list A:\n")
+ msg.WriteString(spewConfig.Sdump(extraA))
+ }
+ if len(extraB) > 0 {
+ msg.WriteString("\n\nextra elements in list B:\n")
+ msg.WriteString(spewConfig.Sdump(extraB))
+ }
+ msg.WriteString("\n\nlistA:\n")
+ msg.WriteString(spewConfig.Sdump(listA))
+ msg.WriteString("\n\nlistB:\n")
+ msg.WriteString(spewConfig.Sdump(listB))
+
+ return msg.String()
+}
+
+// Condition uses a Comparison to assert a complex condition.
+func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ result := comp()
+ if !result {
+ Fail(t, "Condition failed!", msgAndArgs...)
+ }
+ return result
+}
+
+// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
+// methods, and represents a simple func that takes no arguments, and returns nothing.
+type PanicTestFunc func()
+
+// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
+func didPanic(f PanicTestFunc) (bool, interface{}, string) {
+
+ didPanic := false
+ var message interface{}
+ var stack string
+ func() {
+
+ defer func() {
+ if message = recover(); message != nil {
+ didPanic = true
+ stack = string(debug.Stack())
+ }
+ }()
+
+ // call the target function
+ f()
+
+ }()
+
+ return didPanic, message, stack
+
+}
+
+// Panics asserts that the code inside the specified PanicTestFunc panics.
+//
+// assert.Panics(t, func(){ GoCrazy() })
+func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
+ return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
+ }
+
+ return true
+}
+
+// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
+func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ funcDidPanic, panicValue, panickedStack := didPanic(f)
+ if !funcDidPanic {
+ return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
+ }
+ if panicValue != expected {
+ return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, expected, panicValue, panickedStack), msgAndArgs...)
+ }
+
+ return true
+}
+
+// PanicsWithError asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
+func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ funcDidPanic, panicValue, panickedStack := didPanic(f)
+ if !funcDidPanic {
+ return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
+ }
+ panicErr, ok := panicValue.(error)
+ if !ok || panicErr.Error() != errString {
+ return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
+ }
+
+ return true
+}
+
+// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// assert.NotPanics(t, func(){ RemainCalm() })
+func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
+ return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
+ }
+
+ return true
+}
+
+// WithinDuration asserts that the two times are within duration delta of each other.
+//
+// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
+func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ dt := expected.Sub(actual)
+ if dt < -delta || dt > delta {
+ return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
+ }
+
+ return true
+}
+
+func toFloat(x interface{}) (float64, bool) {
+ var xf float64
+ xok := true
+
+ switch xn := x.(type) {
+ case uint:
+ xf = float64(xn)
+ case uint8:
+ xf = float64(xn)
+ case uint16:
+ xf = float64(xn)
+ case uint32:
+ xf = float64(xn)
+ case uint64:
+ xf = float64(xn)
+ case int:
+ xf = float64(xn)
+ case int8:
+ xf = float64(xn)
+ case int16:
+ xf = float64(xn)
+ case int32:
+ xf = float64(xn)
+ case int64:
+ xf = float64(xn)
+ case float32:
+ xf = float64(xn)
+ case float64:
+ xf = xn
+ case time.Duration:
+ xf = float64(xn)
+ default:
+ xok = false
+ }
+
+ return xf, xok
+}
+
+// InDelta asserts that the two numerals are within delta of each other.
+//
+// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
+func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ af, aok := toFloat(expected)
+ bf, bok := toFloat(actual)
+
+ if !aok || !bok {
+ return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
+ }
+
+ if math.IsNaN(af) {
+ return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
+ }
+
+ if math.IsNaN(bf) {
+ return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
+ }
+
+ dt := af - bf
+ if dt < -delta || dt > delta {
+ return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
+ }
+
+ return true
+}
+
+// InDeltaSlice is the same as InDelta, except it compares two slices.
+func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if expected == nil || actual == nil ||
+ reflect.TypeOf(actual).Kind() != reflect.Slice ||
+ reflect.TypeOf(expected).Kind() != reflect.Slice {
+ return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
+ }
+
+ actualSlice := reflect.ValueOf(actual)
+ expectedSlice := reflect.ValueOf(expected)
+
+ for i := 0; i < actualSlice.Len(); i++ {
+ result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
+ if !result {
+ return result
+ }
+ }
+
+ return true
+}
+
+// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if expected == nil || actual == nil ||
+ reflect.TypeOf(actual).Kind() != reflect.Map ||
+ reflect.TypeOf(expected).Kind() != reflect.Map {
+ return Fail(t, "Arguments must be maps", msgAndArgs...)
+ }
+
+ expectedMap := reflect.ValueOf(expected)
+ actualMap := reflect.ValueOf(actual)
+
+ if expectedMap.Len() != actualMap.Len() {
+ return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
+ }
+
+ for _, k := range expectedMap.MapKeys() {
+ ev := expectedMap.MapIndex(k)
+ av := actualMap.MapIndex(k)
+
+ if !ev.IsValid() {
+ return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
+ }
+
+ if !av.IsValid() {
+ return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
+ }
+
+ if !InDelta(
+ t,
+ ev.Interface(),
+ av.Interface(),
+ delta,
+ msgAndArgs...,
+ ) {
+ return false
+ }
+ }
+
+ return true
+}
+
+func calcRelativeError(expected, actual interface{}) (float64, error) {
+ af, aok := toFloat(expected)
+ if !aok {
+ return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
+ }
+ if math.IsNaN(af) {
+ return 0, errors.New("expected value must not be NaN")
+ }
+ if af == 0 {
+ return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
+ }
+ bf, bok := toFloat(actual)
+ if !bok {
+ return 0, fmt.Errorf("actual value %q cannot be converted to float", actual)
+ }
+ if math.IsNaN(bf) {
+ return 0, errors.New("actual value must not be NaN")
+ }
+
+ return math.Abs(af-bf) / math.Abs(af), nil
+}
+
+// InEpsilon asserts that expected and actual have a relative error less than epsilon
+func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if math.IsNaN(epsilon) {
+ return Fail(t, "epsilon must not be NaN")
+ }
+ actualEpsilon, err := calcRelativeError(expected, actual)
+ if err != nil {
+ return Fail(t, err.Error(), msgAndArgs...)
+ }
+ if actualEpsilon > epsilon {
+ return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
+ " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
+ }
+
+ return true
+}
+
+// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
+func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if expected == nil || actual == nil ||
+ reflect.TypeOf(actual).Kind() != reflect.Slice ||
+ reflect.TypeOf(expected).Kind() != reflect.Slice {
+ return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
+ }
+
+ actualSlice := reflect.ValueOf(actual)
+ expectedSlice := reflect.ValueOf(expected)
+
+ for i := 0; i < actualSlice.Len(); i++ {
+ result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
+ if !result {
+ return result
+ }
+ }
+
+ return true
+}
+
+/*
+ Errors
+*/
+
+// NoError asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.NoError(t, err) {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
+ if err != nil {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
+ }
+
+ return true
+}
+
+// Error asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.Error(t, err) {
+// assert.Equal(t, expectedError, err)
+// }
+func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
+ if err == nil {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return Fail(t, "An error is expected but got nil.", msgAndArgs...)
+ }
+
+ return true
+}
+
+// EqualError asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// assert.EqualError(t, err, expectedErrorString)
+func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if !Error(t, theError, msgAndArgs...) {
+ return false
+ }
+ expected := errString
+ actual := theError.Error()
+ // don't need to use deep equals here, we know they are both strings
+ if expected != actual {
+ return Fail(t, fmt.Sprintf("Error message not equal:\n"+
+ "expected: %q\n"+
+ "actual : %q", expected, actual), msgAndArgs...)
+ }
+ return true
+}
+
+// matchRegexp return true if a specified regexp matches a string.
+func matchRegexp(rx interface{}, str interface{}) bool {
+
+ var r *regexp.Regexp
+ if rr, ok := rx.(*regexp.Regexp); ok {
+ r = rr
+ } else {
+ r = regexp.MustCompile(fmt.Sprint(rx))
+ }
+
+ return (r.FindStringIndex(fmt.Sprint(str)) != nil)
+
+}
+
+// Regexp asserts that a specified regexp matches a string.
+//
+// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
+// assert.Regexp(t, "start...$", "it's not starting")
+func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ match := matchRegexp(rx, str)
+
+ if !match {
+ Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
+ }
+
+ return match
+}
+
+// NotRegexp asserts that a specified regexp does not match a string.
+//
+// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
+// assert.NotRegexp(t, "^start", "it's not starting")
+func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ match := matchRegexp(rx, str)
+
+ if match {
+ Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
+ }
+
+ return !match
+
+}
+
+// Zero asserts that i is the zero value for its type.
+func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
+ return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
+ }
+ return true
+}
+
+// NotZero asserts that i is not the zero value for its type.
+func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
+ return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
+ }
+ return true
+}
+
+// FileExists checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ info, err := os.Lstat(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
+ }
+ return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
+ }
+ if info.IsDir() {
+ return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
+ }
+ return true
+}
+
+// NoFileExists checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ info, err := os.Lstat(path)
+ if err != nil {
+ return true
+ }
+ if info.IsDir() {
+ return true
+ }
+ return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
+}
+
+// DirExists checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ info, err := os.Lstat(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
+ }
+ return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
+ }
+ if !info.IsDir() {
+ return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
+ }
+ return true
+}
+
+// NoDirExists checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ info, err := os.Lstat(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return true
+ }
+ return true
+ }
+ if !info.IsDir() {
+ return true
+ }
+ return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
+}
+
+// JSONEq asserts that two JSON strings are equivalent.
+//
+// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
+func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ var expectedJSONAsInterface, actualJSONAsInterface interface{}
+
+ if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
+ return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
+ }
+
+ if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
+ return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
+ }
+
+ return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
+}
+
+// YAMLEq asserts that two YAML strings are equivalent.
+func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
+
+ if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
+ return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
+ }
+
+ if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
+ return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
+ }
+
+ return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
+}
+
+func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
+ t := reflect.TypeOf(v)
+ k := t.Kind()
+
+ if k == reflect.Ptr {
+ t = t.Elem()
+ k = t.Kind()
+ }
+ return t, k
+}
+
+// diff returns a diff of both values as long as both are of the same type and
+// are a struct, map, slice, array or string. Otherwise it returns an empty string.
+func diff(expected interface{}, actual interface{}) string {
+ if expected == nil || actual == nil {
+ return ""
+ }
+
+ et, ek := typeAndKind(expected)
+ at, _ := typeAndKind(actual)
+
+ if et != at {
+ return ""
+ }
+
+ if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
+ return ""
+ }
+
+ var e, a string
+ if et != reflect.TypeOf("") {
+ e = spewConfig.Sdump(expected)
+ a = spewConfig.Sdump(actual)
+ } else {
+ e = reflect.ValueOf(expected).String()
+ a = reflect.ValueOf(actual).String()
+ }
+
+ diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
+ A: difflib.SplitLines(e),
+ B: difflib.SplitLines(a),
+ FromFile: "Expected",
+ FromDate: "",
+ ToFile: "Actual",
+ ToDate: "",
+ Context: 1,
+ })
+
+ return "\n\nDiff:\n" + diff
+}
+
+func isFunction(arg interface{}) bool {
+ if arg == nil {
+ return false
+ }
+ return reflect.TypeOf(arg).Kind() == reflect.Func
+}
+
+var spewConfig = spew.ConfigState{
+ Indent: " ",
+ DisablePointerAddresses: true,
+ DisableCapacities: true,
+ SortKeys: true,
+ DisableMethods: true,
+}
+
+type tHelper interface {
+ Helper()
+}
+
+// Eventually asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
+func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ ch := make(chan bool, 1)
+
+ timer := time.NewTimer(waitFor)
+ defer timer.Stop()
+
+ ticker := time.NewTicker(tick)
+ defer ticker.Stop()
+
+ for tick := ticker.C; ; {
+ select {
+ case <-timer.C:
+ return Fail(t, "Condition never satisfied", msgAndArgs...)
+ case <-tick:
+ tick = nil
+ go func() { ch <- condition() }()
+ case v := <-ch:
+ if v {
+ return true
+ }
+ tick = ticker.C
+ }
+ }
+}
+
+// Never asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
+func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+
+ ch := make(chan bool, 1)
+
+ timer := time.NewTimer(waitFor)
+ defer timer.Stop()
+
+ ticker := time.NewTicker(tick)
+ defer ticker.Stop()
+
+ for tick := ticker.C; ; {
+ select {
+ case <-timer.C:
+ return true
+ case <-tick:
+ tick = nil
+ go func() { ch <- condition() }()
+ case v := <-ch:
+ if v {
+ return Fail(t, "Condition satisfied", msgAndArgs...)
+ }
+ tick = ticker.C
+ }
+ }
+}
diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go
new file mode 100644
index 00000000..c9dccc4d
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/doc.go
@@ -0,0 +1,45 @@
+// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.
+//
+// Example Usage
+//
+// The following is a complete example using assert in a standard test function:
+// import (
+// "testing"
+// "github.com/stretchr/testify/assert"
+// )
+//
+// func TestSomething(t *testing.T) {
+//
+// var a string = "Hello"
+// var b string = "Hello"
+//
+// assert.Equal(t, a, b, "The two words should be the same.")
+//
+// }
+//
+// if you assert many times, use the format below:
+//
+// import (
+// "testing"
+// "github.com/stretchr/testify/assert"
+// )
+//
+// func TestSomething(t *testing.T) {
+// assert := assert.New(t)
+//
+// var a string = "Hello"
+// var b string = "Hello"
+//
+// assert.Equal(a, b, "The two words should be the same.")
+// }
+//
+// Assertions
+//
+// Assertions allow you to easily write test code, and are global funcs in the `assert` package.
+// All assertion functions take, as the first argument, the `*testing.T` object provided by the
+// testing framework. This allows the assertion funcs to write the failings and other details to
+// the correct place.
+//
+// Every assertion function also takes an optional string message as the final argument,
+// allowing custom error messages to be appended to the message the assertion method outputs.
+package assert
diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go
new file mode 100644
index 00000000..ac9dc9d1
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/errors.go
@@ -0,0 +1,10 @@
+package assert
+
+import (
+ "errors"
+)
+
+// AnError is an error instance useful for testing. If the code does not care
+// about error specifics, and only needs to return the error for example, this
+// error should be used to make the test code more readable.
+var AnError = errors.New("assert.AnError general error for testing")
diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go
new file mode 100644
index 00000000..df189d23
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/forward_assertions.go
@@ -0,0 +1,16 @@
+package assert
+
+// Assertions provides assertion methods around the
+// TestingT interface.
+type Assertions struct {
+ t TestingT
+}
+
+// New makes a new Assertions object for the specified TestingT.
+func New(t TestingT) *Assertions {
+ return &Assertions{
+ t: t,
+ }
+}
+
+//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs"
diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go
new file mode 100644
index 00000000..4ed341dd
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go
@@ -0,0 +1,162 @@
+package assert
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+)
+
+// httpCode is a helper that returns HTTP code of the response. It returns -1 and
+// an error if building a new request fails.
+func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) {
+ w := httptest.NewRecorder()
+ req, err := http.NewRequest(method, url, nil)
+ if err != nil {
+ return -1, err
+ }
+ req.URL.RawQuery = values.Encode()
+ handler(w, req)
+ return w.Code, nil
+}
+
+// HTTPSuccess asserts that a specified handler returns a success status code.
+//
+// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ code, err := httpCode(handler, method, url, values)
+ if err != nil {
+ Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
+ }
+
+ isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent
+ if !isSuccessCode {
+ Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code))
+ }
+
+ return isSuccessCode
+}
+
+// HTTPRedirect asserts that a specified handler returns a redirect status code.
+//
+// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ code, err := httpCode(handler, method, url, values)
+ if err != nil {
+ Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
+ }
+
+ isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect
+ if !isRedirectCode {
+ Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code))
+ }
+
+ return isRedirectCode
+}
+
+// HTTPError asserts that a specified handler returns an error status code.
+//
+// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ code, err := httpCode(handler, method, url, values)
+ if err != nil {
+ Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
+ }
+
+ isErrorCode := code >= http.StatusBadRequest
+ if !isErrorCode {
+ Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code))
+ }
+
+ return isErrorCode
+}
+
+// HTTPStatusCode asserts that a specified handler returns a specified status code.
+//
+// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ code, err := httpCode(handler, method, url, values)
+ if err != nil {
+ Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
+ }
+
+ successful := code == statuscode
+ if !successful {
+ Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code))
+ }
+
+ return successful
+}
+
+// HTTPBody is a helper that returns HTTP body of the response. It returns
+// empty string if building a new request fails.
+func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string {
+ w := httptest.NewRecorder()
+ req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
+ if err != nil {
+ return ""
+ }
+ handler(w, req)
+ return w.Body.String()
+}
+
+// HTTPBodyContains asserts that a specified handler returns a
+// body that contains a string.
+//
+// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ body := HTTPBody(handler, method, url, values)
+
+ contains := strings.Contains(body, fmt.Sprint(str))
+ if !contains {
+ Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
+ }
+
+ return contains
+}
+
+// HTTPBodyNotContains asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ body := HTTPBody(handler, method, url, values)
+
+ contains := strings.Contains(body, fmt.Sprint(str))
+ if contains {
+ Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
+ }
+
+ return !contains
+}
diff --git a/vendor/github.com/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go
new file mode 100644
index 00000000..169de392
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/doc.go
@@ -0,0 +1,28 @@
+// Package require implements the same assertions as the `assert` package but
+// stops test execution when a test fails.
+//
+// Example Usage
+//
+// The following is a complete example using require in a standard test function:
+// import (
+// "testing"
+// "github.com/stretchr/testify/require"
+// )
+//
+// func TestSomething(t *testing.T) {
+//
+// var a string = "Hello"
+// var b string = "Hello"
+//
+// require.Equal(t, a, b, "The two words should be the same.")
+//
+// }
+//
+// Assertions
+//
+// The `require` package have same global functions as in the `assert` package,
+// but instead of returning a boolean result they call `t.FailNow()`.
+//
+// Every assertion function also takes an optional string message as the final argument,
+// allowing custom error messages to be appended to the message the assertion method outputs.
+package require
diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go
new file mode 100644
index 00000000..1dcb2338
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/forward_requirements.go
@@ -0,0 +1,16 @@
+package require
+
+// Assertions provides assertion methods around the
+// TestingT interface.
+type Assertions struct {
+ t TestingT
+}
+
+// New makes a new Assertions object for the specified TestingT.
+func New(t TestingT) *Assertions {
+ return &Assertions{
+ t: t,
+ }
+}
+
+//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require_forward.go.tmpl -include-format-funcs"
diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go
new file mode 100644
index 00000000..ec4624b2
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/require.go
@@ -0,0 +1,1631 @@
+/*
+* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
+* THIS FILE MUST NOT BE EDITED BY HAND
+ */
+
+package require
+
+import (
+ assert "github.com/stretchr/testify/assert"
+ http "net/http"
+ url "net/url"
+ time "time"
+)
+
+// Condition uses a Comparison to assert a complex condition.
+func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Condition(t, comp, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Conditionf uses a Comparison to assert a complex condition.
+func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Conditionf(t, comp, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Contains asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// assert.Contains(t, "Hello World", "World")
+// assert.Contains(t, ["Hello", "World"], "World")
+// assert.Contains(t, {"Hello": "World"}, "Hello")
+func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Contains(t, s, contains, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Containsf asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted")
+// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted")
+// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted")
+func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Containsf(t, s, contains, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// DirExists checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func DirExists(t TestingT, path string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.DirExists(t, path, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// DirExistsf checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func DirExistsf(t TestingT, path string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.DirExistsf(t, path, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
+func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.ElementsMatch(t, listA, listB, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
+func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.ElementsMatchf(t, listA, listB, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// assert.Empty(t, obj)
+func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Empty(t, object, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// assert.Emptyf(t, obj, "error message %s", "formatted")
+func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Emptyf(t, object, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Equal asserts that two objects are equal.
+//
+// assert.Equal(t, 123, 123)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Equal(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// EqualError asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// assert.EqualError(t, err, expectedErrorString)
+func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.EqualError(t, theError, errString, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted")
+func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.EqualErrorf(t, theError, errString, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// EqualValues asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// assert.EqualValues(t, uint32(123), int32(123))
+func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.EqualValues(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// EqualValuesf asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")
+func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.EqualValuesf(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Equalf asserts that two objects are equal.
+//
+// assert.Equalf(t, 123, 123, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Equalf(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Error asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.Error(t, err) {
+// assert.Equal(t, expectedError, err)
+// }
+func Error(t TestingT, err error, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Error(t, err, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Errorf asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.Errorf(t, err, "error message %s", "formatted") {
+// assert.Equal(t, expectedErrorf, err)
+// }
+func Errorf(t TestingT, err error, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Errorf(t, err, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Eventually asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
+func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Eventually(t, condition, waitFor, tick, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Eventuallyf asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Eventuallyf(t, condition, waitFor, tick, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Exactly asserts that two objects are equal in value and type.
+//
+// assert.Exactly(t, int32(123), int64(123))
+func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Exactly(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Exactlyf asserts that two objects are equal in value and type.
+//
+// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted")
+func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Exactlyf(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Fail reports a failure through
+func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Fail(t, failureMessage, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// FailNow fails test
+func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.FailNow(t, failureMessage, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// FailNowf fails test
+func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.FailNowf(t, failureMessage, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Failf reports a failure through
+func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Failf(t, failureMessage, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// False asserts that the specified value is false.
+//
+// assert.False(t, myBool)
+func False(t TestingT, value bool, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.False(t, value, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Falsef asserts that the specified value is false.
+//
+// assert.Falsef(t, myBool, "error message %s", "formatted")
+func Falsef(t TestingT, value bool, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Falsef(t, value, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// FileExists checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func FileExists(t TestingT, path string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.FileExists(t, path, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// FileExistsf checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func FileExistsf(t TestingT, path string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.FileExistsf(t, path, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Greater asserts that the first element is greater than the second
+//
+// assert.Greater(t, 2, 1)
+// assert.Greater(t, float64(2), float64(1))
+// assert.Greater(t, "b", "a")
+func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Greater(t, e1, e2, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// GreaterOrEqual asserts that the first element is greater than or equal to the second
+//
+// assert.GreaterOrEqual(t, 2, 1)
+// assert.GreaterOrEqual(t, 2, 2)
+// assert.GreaterOrEqual(t, "b", "a")
+// assert.GreaterOrEqual(t, "b", "b")
+func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.GreaterOrEqual(t, e1, e2, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// GreaterOrEqualf asserts that the first element is greater than or equal to the second
+//
+// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted")
+// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted")
+// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted")
+// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted")
+func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.GreaterOrEqualf(t, e1, e2, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Greaterf asserts that the first element is greater than the second
+//
+// assert.Greaterf(t, 2, 1, "error message %s", "formatted")
+// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted")
+// assert.Greaterf(t, "b", "a", "error message %s", "formatted")
+func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Greaterf(t, e1, e2, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPBodyContains asserts that a specified handler returns a
+// body that contains a string.
+//
+// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPBodyContains(t, handler, method, url, values, str, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPBodyContainsf asserts that a specified handler returns a
+// body that contains a string.
+//
+// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPBodyContainsf(t, handler, method, url, values, str, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPBodyNotContains asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPBodyNotContains(t, handler, method, url, values, str, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPBodyNotContainsf asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPBodyNotContainsf(t, handler, method, url, values, str, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPError asserts that a specified handler returns an error status code.
+//
+// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPError(t, handler, method, url, values, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPErrorf asserts that a specified handler returns an error status code.
+//
+// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPErrorf(t, handler, method, url, values, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPRedirect asserts that a specified handler returns a redirect status code.
+//
+// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPRedirect(t, handler, method, url, values, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPRedirectf asserts that a specified handler returns a redirect status code.
+//
+// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPRedirectf(t, handler, method, url, values, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPStatusCode asserts that a specified handler returns a specified status code.
+//
+// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPStatusCode(t, handler, method, url, values, statuscode, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPStatusCodef asserts that a specified handler returns a specified status code.
+//
+// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPStatusCodef(t, handler, method, url, values, statuscode, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPSuccess asserts that a specified handler returns a success status code.
+//
+// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPSuccess(t, handler, method, url, values, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// HTTPSuccessf asserts that a specified handler returns a success status code.
+//
+// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.HTTPSuccessf(t, handler, method, url, values, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Implements asserts that an object is implemented by the specified interface.
+//
+// assert.Implements(t, (*MyInterface)(nil), new(MyObject))
+func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Implements(t, interfaceObject, object, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Implementsf asserts that an object is implemented by the specified interface.
+//
+// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
+func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Implementsf(t, interfaceObject, object, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InDelta asserts that the two numerals are within delta of each other.
+//
+// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
+func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InDelta(t, expected, actual, delta, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func InDeltaMapValues(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InDeltaMapValues(t, expected, actual, delta, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InDeltaMapValuesf(t, expected, actual, delta, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InDeltaSlice is the same as InDelta, except it compares two slices.
+func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InDeltaSlicef is the same as InDelta, except it compares two slices.
+func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InDeltaf asserts that the two numerals are within delta of each other.
+//
+// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
+func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InDeltaf(t, expected, actual, delta, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InEpsilon asserts that expected and actual have a relative error less than epsilon
+func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
+func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices.
+func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// InEpsilonf asserts that expected and actual have a relative error less than epsilon
+func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// IsType asserts that the specified objects are of the same type.
+func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.IsType(t, expectedType, object, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// IsTypef asserts that the specified objects are of the same type.
+func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.IsTypef(t, expectedType, object, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// JSONEq asserts that two JSON strings are equivalent.
+//
+// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
+func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.JSONEq(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// JSONEqf asserts that two JSON strings are equivalent.
+//
+// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
+func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.JSONEqf(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Len asserts that the specified object has specific length.
+// Len also fails if the object has a type that len() not accept.
+//
+// assert.Len(t, mySlice, 3)
+func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Len(t, object, length, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Lenf asserts that the specified object has specific length.
+// Lenf also fails if the object has a type that len() not accept.
+//
+// assert.Lenf(t, mySlice, 3, "error message %s", "formatted")
+func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Lenf(t, object, length, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Less asserts that the first element is less than the second
+//
+// assert.Less(t, 1, 2)
+// assert.Less(t, float64(1), float64(2))
+// assert.Less(t, "a", "b")
+func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Less(t, e1, e2, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// LessOrEqual asserts that the first element is less than or equal to the second
+//
+// assert.LessOrEqual(t, 1, 2)
+// assert.LessOrEqual(t, 2, 2)
+// assert.LessOrEqual(t, "a", "b")
+// assert.LessOrEqual(t, "b", "b")
+func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.LessOrEqual(t, e1, e2, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// LessOrEqualf asserts that the first element is less than or equal to the second
+//
+// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted")
+// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted")
+// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted")
+// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted")
+func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.LessOrEqualf(t, e1, e2, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Lessf asserts that the first element is less than the second
+//
+// assert.Lessf(t, 1, 2, "error message %s", "formatted")
+// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted")
+// assert.Lessf(t, "a", "b", "error message %s", "formatted")
+func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Lessf(t, e1, e2, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Never asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
+func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Never(t, condition, waitFor, tick, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Neverf asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Neverf(t, condition, waitFor, tick, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Nil asserts that the specified object is nil.
+//
+// assert.Nil(t, err)
+func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Nil(t, object, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Nilf asserts that the specified object is nil.
+//
+// assert.Nilf(t, err, "error message %s", "formatted")
+func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Nilf(t, object, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NoDirExists checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NoDirExists(t, path, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NoDirExistsf checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NoDirExistsf(t, path, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NoError asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.NoError(t, err) {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NoError(t, err, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NoErrorf asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if assert.NoErrorf(t, err, "error message %s", "formatted") {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func NoErrorf(t TestingT, err error, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NoErrorf(t, err, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NoFileExists checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NoFileExists(t, path, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NoFileExistsf checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NoFileExistsf(t, path, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// assert.NotContains(t, "Hello World", "Earth")
+// assert.NotContains(t, ["Hello", "World"], "Earth")
+// assert.NotContains(t, {"Hello": "World"}, "Earth")
+func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotContains(t, s, contains, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted")
+// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted")
+// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted")
+func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotContainsf(t, s, contains, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if assert.NotEmpty(t, obj) {
+// assert.Equal(t, "two", obj[1])
+// }
+func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotEmpty(t, object, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if assert.NotEmptyf(t, obj, "error message %s", "formatted") {
+// assert.Equal(t, "two", obj[1])
+// }
+func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotEmptyf(t, object, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotEqual asserts that the specified values are NOT equal.
+//
+// assert.NotEqual(t, obj1, obj2)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotEqual(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotEqualValues asserts that two objects are not equal even when converted to the same type
+//
+// assert.NotEqualValues(t, obj1, obj2)
+func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotEqualValues(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotEqualValuesf asserts that two objects are not equal even when converted to the same type
+//
+// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted")
+func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotEqualValuesf(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotEqualf asserts that the specified values are NOT equal.
+//
+// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotEqualf(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotNil asserts that the specified object is not nil.
+//
+// assert.NotNil(t, err)
+func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotNil(t, object, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotNilf asserts that the specified object is not nil.
+//
+// assert.NotNilf(t, err, "error message %s", "formatted")
+func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotNilf(t, object, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// assert.NotPanics(t, func(){ RemainCalm() })
+func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotPanics(t, f, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted")
+func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotPanicsf(t, f, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotRegexp asserts that a specified regexp does not match a string.
+//
+// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
+// assert.NotRegexp(t, "^start", "it's not starting")
+func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotRegexp(t, rx, str, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotRegexpf asserts that a specified regexp does not match a string.
+//
+// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
+// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted")
+func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotRegexpf(t, rx, str, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotSame asserts that two pointers do not reference the same object.
+//
+// assert.NotSame(t, ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func NotSame(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotSame(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotSamef asserts that two pointers do not reference the same object.
+//
+// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotSamef(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotSubset asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
+func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotSubset(t, list, subset, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotSubsetf asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted")
+func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotSubsetf(t, list, subset, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotZero asserts that i is not the zero value for its type.
+func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotZero(t, i, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotZerof asserts that i is not the zero value for its type.
+func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotZerof(t, i, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Panics asserts that the code inside the specified PanicTestFunc panics.
+//
+// assert.Panics(t, func(){ GoCrazy() })
+func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Panics(t, f, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// PanicsWithError asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
+func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.PanicsWithError(t, errString, f, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.PanicsWithErrorf(t, errString, f, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
+func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.PanicsWithValue(t, expected, f, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.PanicsWithValuef(t, expected, f, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Panicsf asserts that the code inside the specified PanicTestFunc panics.
+//
+// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted")
+func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Panicsf(t, f, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Regexp asserts that a specified regexp matches a string.
+//
+// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
+// assert.Regexp(t, "start...$", "it's not starting")
+func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Regexp(t, rx, str, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Regexpf asserts that a specified regexp matches a string.
+//
+// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
+// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted")
+func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Regexpf(t, rx, str, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Same asserts that two pointers reference the same object.
+//
+// assert.Same(t, ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func Same(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Same(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Samef asserts that two pointers reference the same object.
+//
+// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Samef(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Subset asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
+func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Subset(t, list, subset, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Subsetf asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted")
+func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Subsetf(t, list, subset, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// True asserts that the specified value is true.
+//
+// assert.True(t, myBool)
+func True(t TestingT, value bool, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.True(t, value, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Truef asserts that the specified value is true.
+//
+// assert.Truef(t, myBool, "error message %s", "formatted")
+func Truef(t TestingT, value bool, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Truef(t, value, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// WithinDuration asserts that the two times are within duration delta of each other.
+//
+// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
+func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// WithinDurationf asserts that the two times are within duration delta of each other.
+//
+// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
+func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.WithinDurationf(t, expected, actual, delta, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// YAMLEq asserts that two YAML strings are equivalent.
+func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.YAMLEq(t, expected, actual, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// YAMLEqf asserts that two YAML strings are equivalent.
+func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.YAMLEqf(t, expected, actual, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Zero asserts that i is the zero value for its type.
+func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Zero(t, i, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// Zerof asserts that i is the zero value for its type.
+func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.Zerof(t, i, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
diff --git a/vendor/github.com/stretchr/testify/require/require.go.tmpl b/vendor/github.com/stretchr/testify/require/require.go.tmpl
new file mode 100644
index 00000000..55e42dde
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/require.go.tmpl
@@ -0,0 +1,6 @@
+{{.Comment}}
+func {{.DocInfo.Name}}(t TestingT, {{.Params}}) {
+ if h, ok := t.(tHelper); ok { h.Helper() }
+ if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return }
+ t.FailNow()
+}
diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go
new file mode 100644
index 00000000..103d7dcb
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/require_forward.go
@@ -0,0 +1,1277 @@
+/*
+* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
+* THIS FILE MUST NOT BE EDITED BY HAND
+ */
+
+package require
+
+import (
+ assert "github.com/stretchr/testify/assert"
+ http "net/http"
+ url "net/url"
+ time "time"
+)
+
+// Condition uses a Comparison to assert a complex condition.
+func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Condition(a.t, comp, msgAndArgs...)
+}
+
+// Conditionf uses a Comparison to assert a complex condition.
+func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Conditionf(a.t, comp, msg, args...)
+}
+
+// Contains asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// a.Contains("Hello World", "World")
+// a.Contains(["Hello", "World"], "World")
+// a.Contains({"Hello": "World"}, "Hello")
+func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Contains(a.t, s, contains, msgAndArgs...)
+}
+
+// Containsf asserts that the specified string, list(array, slice...) or map contains the
+// specified substring or element.
+//
+// a.Containsf("Hello World", "World", "error message %s", "formatted")
+// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted")
+// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted")
+func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Containsf(a.t, s, contains, msg, args...)
+}
+
+// DirExists checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ DirExists(a.t, path, msgAndArgs...)
+}
+
+// DirExistsf checks whether a directory exists in the given path. It also fails
+// if the path is a file rather a directory or there is an error checking whether it exists.
+func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ DirExistsf(a.t, path, msg, args...)
+}
+
+// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2])
+func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ ElementsMatch(a.t, listA, listB, msgAndArgs...)
+}
+
+// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should match.
+//
+// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
+func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ ElementsMatchf(a.t, listA, listB, msg, args...)
+}
+
+// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// a.Empty(obj)
+func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Empty(a.t, object, msgAndArgs...)
+}
+
+// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// a.Emptyf(obj, "error message %s", "formatted")
+func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Emptyf(a.t, object, msg, args...)
+}
+
+// Equal asserts that two objects are equal.
+//
+// a.Equal(123, 123)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Equal(a.t, expected, actual, msgAndArgs...)
+}
+
+// EqualError asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// a.EqualError(err, expectedErrorString)
+func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ EqualError(a.t, theError, errString, msgAndArgs...)
+}
+
+// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted")
+func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ EqualErrorf(a.t, theError, errString, msg, args...)
+}
+
+// EqualValues asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// a.EqualValues(uint32(123), int32(123))
+func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ EqualValues(a.t, expected, actual, msgAndArgs...)
+}
+
+// EqualValuesf asserts that two objects are equal or convertable to the same types
+// and equal.
+//
+// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted")
+func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ EqualValuesf(a.t, expected, actual, msg, args...)
+}
+
+// Equalf asserts that two objects are equal.
+//
+// a.Equalf(123, 123, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses). Function equality
+// cannot be determined and will always fail.
+func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Equalf(a.t, expected, actual, msg, args...)
+}
+
+// Error asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.Error(err) {
+// assert.Equal(t, expectedError, err)
+// }
+func (a *Assertions) Error(err error, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Error(a.t, err, msgAndArgs...)
+}
+
+// Errorf asserts that a function returned an error (i.e. not `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.Errorf(err, "error message %s", "formatted") {
+// assert.Equal(t, expectedErrorf, err)
+// }
+func (a *Assertions) Errorf(err error, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Errorf(a.t, err, msg, args...)
+}
+
+// Eventually asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond)
+func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Eventually(a.t, condition, waitFor, tick, msgAndArgs...)
+}
+
+// Eventuallyf asserts that given condition will be met in waitFor time,
+// periodically checking target function each tick.
+//
+// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Eventuallyf(a.t, condition, waitFor, tick, msg, args...)
+}
+
+// Exactly asserts that two objects are equal in value and type.
+//
+// a.Exactly(int32(123), int64(123))
+func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Exactly(a.t, expected, actual, msgAndArgs...)
+}
+
+// Exactlyf asserts that two objects are equal in value and type.
+//
+// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted")
+func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Exactlyf(a.t, expected, actual, msg, args...)
+}
+
+// Fail reports a failure through
+func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Fail(a.t, failureMessage, msgAndArgs...)
+}
+
+// FailNow fails test
+func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ FailNow(a.t, failureMessage, msgAndArgs...)
+}
+
+// FailNowf fails test
+func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ FailNowf(a.t, failureMessage, msg, args...)
+}
+
+// Failf reports a failure through
+func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Failf(a.t, failureMessage, msg, args...)
+}
+
+// False asserts that the specified value is false.
+//
+// a.False(myBool)
+func (a *Assertions) False(value bool, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ False(a.t, value, msgAndArgs...)
+}
+
+// Falsef asserts that the specified value is false.
+//
+// a.Falsef(myBool, "error message %s", "formatted")
+func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Falsef(a.t, value, msg, args...)
+}
+
+// FileExists checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ FileExists(a.t, path, msgAndArgs...)
+}
+
+// FileExistsf checks whether a file exists in the given path. It also fails if
+// the path points to a directory or there is an error when trying to check the file.
+func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ FileExistsf(a.t, path, msg, args...)
+}
+
+// Greater asserts that the first element is greater than the second
+//
+// a.Greater(2, 1)
+// a.Greater(float64(2), float64(1))
+// a.Greater("b", "a")
+func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Greater(a.t, e1, e2, msgAndArgs...)
+}
+
+// GreaterOrEqual asserts that the first element is greater than or equal to the second
+//
+// a.GreaterOrEqual(2, 1)
+// a.GreaterOrEqual(2, 2)
+// a.GreaterOrEqual("b", "a")
+// a.GreaterOrEqual("b", "b")
+func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ GreaterOrEqual(a.t, e1, e2, msgAndArgs...)
+}
+
+// GreaterOrEqualf asserts that the first element is greater than or equal to the second
+//
+// a.GreaterOrEqualf(2, 1, "error message %s", "formatted")
+// a.GreaterOrEqualf(2, 2, "error message %s", "formatted")
+// a.GreaterOrEqualf("b", "a", "error message %s", "formatted")
+// a.GreaterOrEqualf("b", "b", "error message %s", "formatted")
+func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ GreaterOrEqualf(a.t, e1, e2, msg, args...)
+}
+
+// Greaterf asserts that the first element is greater than the second
+//
+// a.Greaterf(2, 1, "error message %s", "formatted")
+// a.Greaterf(float64(2), float64(1), "error message %s", "formatted")
+// a.Greaterf("b", "a", "error message %s", "formatted")
+func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Greaterf(a.t, e1, e2, msg, args...)
+}
+
+// HTTPBodyContains asserts that a specified handler returns a
+// body that contains a string.
+//
+// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...)
+}
+
+// HTTPBodyContainsf asserts that a specified handler returns a
+// body that contains a string.
+//
+// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...)
+}
+
+// HTTPBodyNotContains asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...)
+}
+
+// HTTPBodyNotContainsf asserts that a specified handler returns a
+// body that does not contain a string.
+//
+// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...)
+}
+
+// HTTPError asserts that a specified handler returns an error status code.
+//
+// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPError(a.t, handler, method, url, values, msgAndArgs...)
+}
+
+// HTTPErrorf asserts that a specified handler returns an error status code.
+//
+// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPErrorf(a.t, handler, method, url, values, msg, args...)
+}
+
+// HTTPRedirect asserts that a specified handler returns a redirect status code.
+//
+// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...)
+}
+
+// HTTPRedirectf asserts that a specified handler returns a redirect status code.
+//
+// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPRedirectf(a.t, handler, method, url, values, msg, args...)
+}
+
+// HTTPStatusCode asserts that a specified handler returns a specified status code.
+//
+// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...)
+}
+
+// HTTPStatusCodef asserts that a specified handler returns a specified status code.
+//
+// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...)
+}
+
+// HTTPSuccess asserts that a specified handler returns a success status code.
+//
+// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...)
+}
+
+// HTTPSuccessf asserts that a specified handler returns a success status code.
+//
+// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ HTTPSuccessf(a.t, handler, method, url, values, msg, args...)
+}
+
+// Implements asserts that an object is implemented by the specified interface.
+//
+// a.Implements((*MyInterface)(nil), new(MyObject))
+func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Implements(a.t, interfaceObject, object, msgAndArgs...)
+}
+
+// Implementsf asserts that an object is implemented by the specified interface.
+//
+// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
+func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Implementsf(a.t, interfaceObject, object, msg, args...)
+}
+
+// InDelta asserts that the two numerals are within delta of each other.
+//
+// a.InDelta(math.Pi, 22/7.0, 0.01)
+func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InDelta(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
+func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...)
+}
+
+// InDeltaSlice is the same as InDelta, except it compares two slices.
+func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// InDeltaSlicef is the same as InDelta, except it compares two slices.
+func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InDeltaSlicef(a.t, expected, actual, delta, msg, args...)
+}
+
+// InDeltaf asserts that the two numerals are within delta of each other.
+//
+// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
+func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InDeltaf(a.t, expected, actual, delta, msg, args...)
+}
+
+// InEpsilon asserts that expected and actual have a relative error less than epsilon
+func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...)
+}
+
+// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
+func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...)
+}
+
+// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices.
+func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...)
+}
+
+// InEpsilonf asserts that expected and actual have a relative error less than epsilon
+func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ InEpsilonf(a.t, expected, actual, epsilon, msg, args...)
+}
+
+// IsType asserts that the specified objects are of the same type.
+func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ IsType(a.t, expectedType, object, msgAndArgs...)
+}
+
+// IsTypef asserts that the specified objects are of the same type.
+func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ IsTypef(a.t, expectedType, object, msg, args...)
+}
+
+// JSONEq asserts that two JSON strings are equivalent.
+//
+// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
+func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ JSONEq(a.t, expected, actual, msgAndArgs...)
+}
+
+// JSONEqf asserts that two JSON strings are equivalent.
+//
+// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
+func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ JSONEqf(a.t, expected, actual, msg, args...)
+}
+
+// Len asserts that the specified object has specific length.
+// Len also fails if the object has a type that len() not accept.
+//
+// a.Len(mySlice, 3)
+func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Len(a.t, object, length, msgAndArgs...)
+}
+
+// Lenf asserts that the specified object has specific length.
+// Lenf also fails if the object has a type that len() not accept.
+//
+// a.Lenf(mySlice, 3, "error message %s", "formatted")
+func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Lenf(a.t, object, length, msg, args...)
+}
+
+// Less asserts that the first element is less than the second
+//
+// a.Less(1, 2)
+// a.Less(float64(1), float64(2))
+// a.Less("a", "b")
+func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Less(a.t, e1, e2, msgAndArgs...)
+}
+
+// LessOrEqual asserts that the first element is less than or equal to the second
+//
+// a.LessOrEqual(1, 2)
+// a.LessOrEqual(2, 2)
+// a.LessOrEqual("a", "b")
+// a.LessOrEqual("b", "b")
+func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ LessOrEqual(a.t, e1, e2, msgAndArgs...)
+}
+
+// LessOrEqualf asserts that the first element is less than or equal to the second
+//
+// a.LessOrEqualf(1, 2, "error message %s", "formatted")
+// a.LessOrEqualf(2, 2, "error message %s", "formatted")
+// a.LessOrEqualf("a", "b", "error message %s", "formatted")
+// a.LessOrEqualf("b", "b", "error message %s", "formatted")
+func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ LessOrEqualf(a.t, e1, e2, msg, args...)
+}
+
+// Lessf asserts that the first element is less than the second
+//
+// a.Lessf(1, 2, "error message %s", "formatted")
+// a.Lessf(float64(1), float64(2), "error message %s", "formatted")
+// a.Lessf("a", "b", "error message %s", "formatted")
+func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Lessf(a.t, e1, e2, msg, args...)
+}
+
+// Never asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond)
+func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Never(a.t, condition, waitFor, tick, msgAndArgs...)
+}
+
+// Neverf asserts that the given condition doesn't satisfy in waitFor time,
+// periodically checking the target function each tick.
+//
+// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Neverf(a.t, condition, waitFor, tick, msg, args...)
+}
+
+// Nil asserts that the specified object is nil.
+//
+// a.Nil(err)
+func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Nil(a.t, object, msgAndArgs...)
+}
+
+// Nilf asserts that the specified object is nil.
+//
+// a.Nilf(err, "error message %s", "formatted")
+func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Nilf(a.t, object, msg, args...)
+}
+
+// NoDirExists checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func (a *Assertions) NoDirExists(path string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NoDirExists(a.t, path, msgAndArgs...)
+}
+
+// NoDirExistsf checks whether a directory does not exist in the given path.
+// It fails if the path points to an existing _directory_ only.
+func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NoDirExistsf(a.t, path, msg, args...)
+}
+
+// NoError asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.NoError(err) {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NoError(a.t, err, msgAndArgs...)
+}
+
+// NoErrorf asserts that a function returned no error (i.e. `nil`).
+//
+// actualObj, err := SomeFunction()
+// if a.NoErrorf(err, "error message %s", "formatted") {
+// assert.Equal(t, expectedObj, actualObj)
+// }
+func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NoErrorf(a.t, err, msg, args...)
+}
+
+// NoFileExists checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func (a *Assertions) NoFileExists(path string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NoFileExists(a.t, path, msgAndArgs...)
+}
+
+// NoFileExistsf checks whether a file does not exist in a given path. It fails
+// if the path points to an existing _file_ only.
+func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NoFileExistsf(a.t, path, msg, args...)
+}
+
+// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// a.NotContains("Hello World", "Earth")
+// a.NotContains(["Hello", "World"], "Earth")
+// a.NotContains({"Hello": "World"}, "Earth")
+func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotContains(a.t, s, contains, msgAndArgs...)
+}
+
+// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the
+// specified substring or element.
+//
+// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted")
+// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted")
+// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted")
+func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotContainsf(a.t, s, contains, msg, args...)
+}
+
+// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if a.NotEmpty(obj) {
+// assert.Equal(t, "two", obj[1])
+// }
+func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotEmpty(a.t, object, msgAndArgs...)
+}
+
+// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
+// a slice or a channel with len == 0.
+//
+// if a.NotEmptyf(obj, "error message %s", "formatted") {
+// assert.Equal(t, "two", obj[1])
+// }
+func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotEmptyf(a.t, object, msg, args...)
+}
+
+// NotEqual asserts that the specified values are NOT equal.
+//
+// a.NotEqual(obj1, obj2)
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotEqual(a.t, expected, actual, msgAndArgs...)
+}
+
+// NotEqualValues asserts that two objects are not equal even when converted to the same type
+//
+// a.NotEqualValues(obj1, obj2)
+func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotEqualValues(a.t, expected, actual, msgAndArgs...)
+}
+
+// NotEqualValuesf asserts that two objects are not equal even when converted to the same type
+//
+// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted")
+func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotEqualValuesf(a.t, expected, actual, msg, args...)
+}
+
+// NotEqualf asserts that the specified values are NOT equal.
+//
+// a.NotEqualf(obj1, obj2, "error message %s", "formatted")
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotEqualf(a.t, expected, actual, msg, args...)
+}
+
+// NotNil asserts that the specified object is not nil.
+//
+// a.NotNil(err)
+func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotNil(a.t, object, msgAndArgs...)
+}
+
+// NotNilf asserts that the specified object is not nil.
+//
+// a.NotNilf(err, "error message %s", "formatted")
+func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotNilf(a.t, object, msg, args...)
+}
+
+// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// a.NotPanics(func(){ RemainCalm() })
+func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotPanics(a.t, f, msgAndArgs...)
+}
+
+// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.
+//
+// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted")
+func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotPanicsf(a.t, f, msg, args...)
+}
+
+// NotRegexp asserts that a specified regexp does not match a string.
+//
+// a.NotRegexp(regexp.MustCompile("starts"), "it's starting")
+// a.NotRegexp("^start", "it's not starting")
+func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotRegexp(a.t, rx, str, msgAndArgs...)
+}
+
+// NotRegexpf asserts that a specified regexp does not match a string.
+//
+// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
+// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted")
+func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotRegexpf(a.t, rx, str, msg, args...)
+}
+
+// NotSame asserts that two pointers do not reference the same object.
+//
+// a.NotSame(ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotSame(a.t, expected, actual, msgAndArgs...)
+}
+
+// NotSamef asserts that two pointers do not reference the same object.
+//
+// a.NotSamef(ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotSamef(a.t, expected, actual, msg, args...)
+}
+
+// NotSubset asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
+func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotSubset(a.t, list, subset, msgAndArgs...)
+}
+
+// NotSubsetf asserts that the specified list(array, slice...) contains not all
+// elements given in the specified subset(array, slice...).
+//
+// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted")
+func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotSubsetf(a.t, list, subset, msg, args...)
+}
+
+// NotZero asserts that i is not the zero value for its type.
+func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotZero(a.t, i, msgAndArgs...)
+}
+
+// NotZerof asserts that i is not the zero value for its type.
+func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotZerof(a.t, i, msg, args...)
+}
+
+// Panics asserts that the code inside the specified PanicTestFunc panics.
+//
+// a.Panics(func(){ GoCrazy() })
+func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Panics(a.t, f, msgAndArgs...)
+}
+
+// PanicsWithError asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// a.PanicsWithError("crazy error", func(){ GoCrazy() })
+func (a *Assertions) PanicsWithError(errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ PanicsWithError(a.t, errString, f, msgAndArgs...)
+}
+
+// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc
+// panics, and that the recovered panic value is an error that satisfies the
+// EqualError comparison.
+//
+// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func (a *Assertions) PanicsWithErrorf(errString string, f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ PanicsWithErrorf(a.t, errString, f, msg, args...)
+}
+
+// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// a.PanicsWithValue("crazy error", func(){ GoCrazy() })
+func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ PanicsWithValue(a.t, expected, f, msgAndArgs...)
+}
+
+// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that
+// the recovered panic value equals the expected panic value.
+//
+// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ PanicsWithValuef(a.t, expected, f, msg, args...)
+}
+
+// Panicsf asserts that the code inside the specified PanicTestFunc panics.
+//
+// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted")
+func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Panicsf(a.t, f, msg, args...)
+}
+
+// Regexp asserts that a specified regexp matches a string.
+//
+// a.Regexp(regexp.MustCompile("start"), "it's starting")
+// a.Regexp("start...$", "it's not starting")
+func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Regexp(a.t, rx, str, msgAndArgs...)
+}
+
+// Regexpf asserts that a specified regexp matches a string.
+//
+// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
+// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted")
+func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Regexpf(a.t, rx, str, msg, args...)
+}
+
+// Same asserts that two pointers reference the same object.
+//
+// a.Same(ptr1, ptr2)
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Same(a.t, expected, actual, msgAndArgs...)
+}
+
+// Samef asserts that two pointers reference the same object.
+//
+// a.Samef(ptr1, ptr2, "error message %s", "formatted")
+//
+// Both arguments must be pointer variables. Pointer variable sameness is
+// determined based on the equality of both type and value.
+func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Samef(a.t, expected, actual, msg, args...)
+}
+
+// Subset asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
+func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Subset(a.t, list, subset, msgAndArgs...)
+}
+
+// Subsetf asserts that the specified list(array, slice...) contains all
+// elements given in the specified subset(array, slice...).
+//
+// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted")
+func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Subsetf(a.t, list, subset, msg, args...)
+}
+
+// True asserts that the specified value is true.
+//
+// a.True(myBool)
+func (a *Assertions) True(value bool, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ True(a.t, value, msgAndArgs...)
+}
+
+// Truef asserts that the specified value is true.
+//
+// a.Truef(myBool, "error message %s", "formatted")
+func (a *Assertions) Truef(value bool, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Truef(a.t, value, msg, args...)
+}
+
+// WithinDuration asserts that the two times are within duration delta of each other.
+//
+// a.WithinDuration(time.Now(), time.Now(), 10*time.Second)
+func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ WithinDuration(a.t, expected, actual, delta, msgAndArgs...)
+}
+
+// WithinDurationf asserts that the two times are within duration delta of each other.
+//
+// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
+func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ WithinDurationf(a.t, expected, actual, delta, msg, args...)
+}
+
+// YAMLEq asserts that two YAML strings are equivalent.
+func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ YAMLEq(a.t, expected, actual, msgAndArgs...)
+}
+
+// YAMLEqf asserts that two YAML strings are equivalent.
+func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ YAMLEqf(a.t, expected, actual, msg, args...)
+}
+
+// Zero asserts that i is the zero value for its type.
+func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Zero(a.t, i, msgAndArgs...)
+}
+
+// Zerof asserts that i is the zero value for its type.
+func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ Zerof(a.t, i, msg, args...)
+}
diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl
new file mode 100644
index 00000000..54124df1
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl
@@ -0,0 +1,5 @@
+{{.CommentWithoutT "a"}}
+func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) {
+ if h, ok := a.t.(tHelper); ok { h.Helper() }
+ {{.DocInfo.Name}}(a.t, {{.ForwardedParams}})
+}
diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go
new file mode 100644
index 00000000..91772dfe
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/requirements.go
@@ -0,0 +1,29 @@
+package require
+
+// TestingT is an interface wrapper around *testing.T
+type TestingT interface {
+ Errorf(format string, args ...interface{})
+ FailNow()
+}
+
+type tHelper interface {
+ Helper()
+}
+
+// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
+// for table driven tests.
+type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{})
+
+// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
+// for table driven tests.
+type ValueAssertionFunc func(TestingT, interface{}, ...interface{})
+
+// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
+// for table driven tests.
+type BoolAssertionFunc func(TestingT, bool, ...interface{})
+
+// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
+// for table driven tests.
+type ErrorAssertionFunc func(TestingT, error, ...interface{})
+
+//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require.go.tmpl -include-format-funcs"
diff --git a/vendor/github.com/go-openapi/jsonpointer/LICENSE b/vendor/github.com/thales-e-security/pool/LICENSE
similarity index 99%
rename from vendor/github.com/go-openapi/jsonpointer/LICENSE
rename to vendor/github.com/thales-e-security/pool/LICENSE
index d6456956..7a4a3ea2 100644
--- a/vendor/github.com/go-openapi/jsonpointer/LICENSE
+++ b/vendor/github.com/thales-e-security/pool/LICENSE
@@ -199,4 +199,4 @@
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.
+ limitations under the License.
\ No newline at end of file
diff --git a/vendor/go.mongodb.org/mongo-driver/LICENSE b/vendor/go.mongodb.org/mongo-driver/LICENSE
deleted file mode 100644
index 261eeb9e..00000000
--- a/vendor/go.mongodb.org/mongo-driver/LICENSE
+++ /dev/null
@@ -1,201 +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/go.mongodb.org/mongo-driver/bson/bson.go b/vendor/go.mongodb.org/mongo-driver/bson/bson.go
deleted file mode 100644
index ae1a87fa..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bson.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-//
-// Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer
-// See THIRD-PARTY-NOTICES for original license terms.
-
-// +build go1.9
-
-package bson // import "go.mongodb.org/mongo-driver/bson"
-
-import (
- "go.mongodb.org/mongo-driver/bson/primitive"
-)
-
-// Zeroer allows custom struct types to implement a report of zero
-// state. All struct types that don't implement Zeroer or where IsZero
-// returns false are considered to be not zero.
-type Zeroer interface {
- IsZero() bool
-}
-
-// D is an ordered representation of a BSON document. This type should be used when the order of the elements matters,
-// such as MongoDB command documents. If the order of the elements does not matter, an M should be used instead.
-//
-// Example usage:
-//
-// bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}}
-type D = primitive.D
-
-// E represents a BSON element for a D. It is usually used inside a D.
-type E = primitive.E
-
-// M is an unordered representation of a BSON document. This type should be used when the order of the elements does not
-// matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be
-// serialized in an undefined, random order. If the order of the elements matters, a D should be used instead.
-//
-// Example usage:
-//
-// bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}
-type M = primitive.M
-
-// An A is an ordered representation of a BSON array.
-//
-// Example usage:
-//
-// bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}}
-type A = primitive.A
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bson_1_8.go b/vendor/go.mongodb.org/mongo-driver/bson/bson_1_8.go
deleted file mode 100644
index bbe77928..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bson_1_8.go
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-// +build !go1.9
-
-package bson // import "go.mongodb.org/mongo-driver/bson"
-
-import (
- "math"
- "strconv"
- "strings"
-)
-
-// Zeroer allows custom struct types to implement a report of zero
-// state. All struct types that don't implement Zeroer or where IsZero
-// returns false are considered to be not zero.
-type Zeroer interface {
- IsZero() bool
-}
-
-// D is an ordered representation of a BSON document. This type should be used when the order of the elements matters,
-// such as MongoDB command documents. If the order of the elements does not matter, an M should be used instead.
-//
-// Example usage:
-//
-// bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}}
-type D []E
-
-// Map creates a map from the elements of the D.
-func (d D) Map() M {
- m := make(M, len(d))
- for _, e := range d {
- m[e.Key] = e.Value
- }
- return m
-}
-
-// E represents a BSON element for a D. It is usually used inside a D.
-type E struct {
- Key string
- Value interface{}
-}
-
-// M is an unordered representation of a BSON document. This type should be used when the order of the elements does not
-// matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be
-// serialized in an undefined, random order. If the order of the elements matters, a D should be used instead.
-//
-// Example usage:
-//
-// bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}
-type M map[string]interface{}
-
-// An A is an ordered representation of a BSON array.
-//
-// Example usage:
-//
-// bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}}
-type A []interface{}
-
-func formatDouble(f float64) string {
- var s string
- if math.IsInf(f, 1) {
- s = "Infinity"
- } else if math.IsInf(f, -1) {
- s = "-Infinity"
- } else if math.IsNaN(f) {
- s = "NaN"
- } else {
- // Print exactly one decimalType place for integers; otherwise, print as many are necessary to
- // perfectly represent it.
- s = strconv.FormatFloat(f, 'G', -1, 64)
- if !strings.ContainsRune(s, '.') {
- s += ".0"
- }
- }
-
- return s
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go
deleted file mode 100644
index 0ebc9a15..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec // import "go.mongodb.org/mongo-driver/bson/bsoncodec"
-
-import (
- "fmt"
- "reflect"
- "strings"
-
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-// Marshaler is an interface implemented by types that can marshal themselves
-// into a BSON document represented as bytes. The bytes returned must be a valid
-// BSON document if the error is nil.
-type Marshaler interface {
- MarshalBSON() ([]byte, error)
-}
-
-// ValueMarshaler is an interface implemented by types that can marshal
-// themselves into a BSON value as bytes. The type must be the valid type for
-// the bytes returned. The bytes and byte type together must be valid if the
-// error is nil.
-type ValueMarshaler interface {
- MarshalBSONValue() (bsontype.Type, []byte, error)
-}
-
-// Unmarshaler is an interface implemented by types that can unmarshal a BSON
-// document representation of themselves. The BSON bytes can be assumed to be
-// valid. UnmarshalBSON must copy the BSON bytes if it wishes to retain the data
-// after returning.
-type Unmarshaler interface {
- UnmarshalBSON([]byte) error
-}
-
-// ValueUnmarshaler is an interface implemented by types that can unmarshal a
-// BSON value representaiton of themselves. The BSON bytes and type can be
-// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it
-// wishes to retain the data after returning.
-type ValueUnmarshaler interface {
- UnmarshalBSONValue(bsontype.Type, []byte) error
-}
-
-// ValueEncoderError is an error returned from a ValueEncoder when the provided value can't be
-// encoded by the ValueEncoder.
-type ValueEncoderError struct {
- Name string
- Types []reflect.Type
- Kinds []reflect.Kind
- Received reflect.Value
-}
-
-func (vee ValueEncoderError) Error() string {
- typeKinds := make([]string, 0, len(vee.Types)+len(vee.Kinds))
- for _, t := range vee.Types {
- typeKinds = append(typeKinds, t.String())
- }
- for _, k := range vee.Kinds {
- if k == reflect.Map {
- typeKinds = append(typeKinds, "map[string]*")
- continue
- }
- typeKinds = append(typeKinds, k.String())
- }
- received := vee.Received.Kind().String()
- if vee.Received.IsValid() {
- received = vee.Received.Type().String()
- }
- return fmt.Sprintf("%s can only encode valid %s, but got %s", vee.Name, strings.Join(typeKinds, ", "), received)
-}
-
-// ValueDecoderError is an error returned from a ValueDecoder when the provided value can't be
-// decoded by the ValueDecoder.
-type ValueDecoderError struct {
- Name string
- Types []reflect.Type
- Kinds []reflect.Kind
- Received reflect.Value
-}
-
-func (vde ValueDecoderError) Error() string {
- typeKinds := make([]string, 0, len(vde.Types)+len(vde.Kinds))
- for _, t := range vde.Types {
- typeKinds = append(typeKinds, t.String())
- }
- for _, k := range vde.Kinds {
- if k == reflect.Map {
- typeKinds = append(typeKinds, "map[string]*")
- continue
- }
- typeKinds = append(typeKinds, k.String())
- }
- received := vde.Received.Kind().String()
- if vde.Received.IsValid() {
- received = vde.Received.Type().String()
- }
- return fmt.Sprintf("%s can only decode valid and settable %s, but got %s", vde.Name, strings.Join(typeKinds, ", "), received)
-}
-
-// EncodeContext is the contextual information required for a Codec to encode a
-// value.
-type EncodeContext struct {
- *Registry
- MinSize bool
-}
-
-// DecodeContext is the contextual information required for a Codec to decode a
-// value.
-type DecodeContext struct {
- *Registry
- Truncate bool
- // Ancestor is the type of a containing document. This is mainly used to determine what type
- // should be used when decoding an embedded document into an empty interface. For example, if
- // Ancestor is a bson.M, BSON embedded document values being decoded into an empty interface
- // will be decoded into a bson.M.
- Ancestor reflect.Type
-}
-
-// ValueCodec is the interface that groups the methods to encode and decode
-// values.
-type ValueCodec interface {
- ValueEncoder
- ValueDecoder
-}
-
-// ValueEncoder is the interface implemented by types that can handle the encoding of a value.
-type ValueEncoder interface {
- EncodeValue(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
-}
-
-// ValueEncoderFunc is an adapter function that allows a function with the correct signature to be
-// used as a ValueEncoder.
-type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
-
-// EncodeValue implements the ValueEncoder interface.
-func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- return fn(ec, vw, val)
-}
-
-// ValueDecoder is the interface implemented by types that can handle the decoding of a value.
-type ValueDecoder interface {
- DecodeValue(DecodeContext, bsonrw.ValueReader, reflect.Value) error
-}
-
-// ValueDecoderFunc is an adapter function that allows a function with the correct signature to be
-// used as a ValueDecoder.
-type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) error
-
-// DecodeValue implements the ValueDecoder interface.
-func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- return fn(dc, vr, val)
-}
-
-// CodecZeroer is the interface implemented by Codecs that can also determine if
-// a value of the type that would be encoded is zero.
-type CodecZeroer interface {
- IsTypeZero(interface{}) bool
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/byte_slice_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/byte_slice_codec.go
deleted file mode 100644
index 9eed911a..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/byte_slice_codec.go
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "fmt"
- "reflect"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-var defaultByteSliceCodec = NewByteSliceCodec()
-
-// ByteSliceCodec is the Codec used for []byte values.
-type ByteSliceCodec struct {
- EncodeNilAsEmpty bool
-}
-
-var _ ValueCodec = &ByteSliceCodec{}
-
-// NewByteSliceCodec returns a StringCodec with options opts.
-func NewByteSliceCodec(opts ...*bsonoptions.ByteSliceCodecOptions) *ByteSliceCodec {
- byteSliceOpt := bsonoptions.MergeByteSliceCodecOptions(opts...)
- codec := ByteSliceCodec{}
- if byteSliceOpt.EncodeNilAsEmpty != nil {
- codec.EncodeNilAsEmpty = *byteSliceOpt.EncodeNilAsEmpty
- }
- return &codec
-}
-
-// EncodeValue is the ValueEncoder for []byte.
-func (bsc *ByteSliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tByteSlice {
- return ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: val}
- }
- if val.IsNil() && !bsc.EncodeNilAsEmpty {
- return vw.WriteNull()
- }
- return vw.WriteBinary(val.Interface().([]byte))
-}
-
-// DecodeValue is the ValueDecoder for []byte.
-func (bsc *ByteSliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tByteSlice {
- return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val}
- }
-
- var data []byte
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.String:
- str, err := vr.ReadString()
- if err != nil {
- return err
- }
- data = []byte(str)
- case bsontype.Symbol:
- sym, err := vr.ReadSymbol()
- if err != nil {
- return err
- }
- data = []byte(sym)
- case bsontype.Binary:
- var subtype byte
- data, subtype, err = vr.ReadBinary()
- if err != nil {
- return err
- }
- if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld {
- return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype)
- }
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a []byte", vrType)
- }
-
- val.Set(reflect.ValueOf(data))
- return nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/cond_addr_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/cond_addr_codec.go
deleted file mode 100644
index cb8180f2..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/cond_addr_codec.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "reflect"
-
- "go.mongodb.org/mongo-driver/bson/bsonrw"
-)
-
-// condAddrEncoder is the encoder used when a pointer to the encoding value has an encoder.
-type condAddrEncoder struct {
- canAddrEnc ValueEncoder
- elseEnc ValueEncoder
-}
-
-var _ ValueEncoder = (*condAddrEncoder)(nil)
-
-// newCondAddrEncoder returns an condAddrEncoder.
-func newCondAddrEncoder(canAddrEnc, elseEnc ValueEncoder) *condAddrEncoder {
- encoder := condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
- return &encoder
-}
-
-// EncodeValue is the ValueEncoderFunc for a value that may be addressable.
-func (cae *condAddrEncoder) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if val.CanAddr() {
- return cae.canAddrEnc.EncodeValue(ec, vw, val)
- }
- if cae.elseEnc != nil {
- return cae.elseEnc.EncodeValue(ec, vw, val)
- }
- return ErrNoEncoder{Type: val.Type()}
-}
-
-// condAddrDecoder is the decoder used when a pointer to the value has a decoder.
-type condAddrDecoder struct {
- canAddrDec ValueDecoder
- elseDec ValueDecoder
-}
-
-var _ ValueDecoder = (*condAddrDecoder)(nil)
-
-// newCondAddrDecoder returns an CondAddrDecoder.
-func newCondAddrDecoder(canAddrDec, elseDec ValueDecoder) *condAddrDecoder {
- decoder := condAddrDecoder{canAddrDec: canAddrDec, elseDec: elseDec}
- return &decoder
-}
-
-// DecodeValue is the ValueDecoderFunc for a value that may be addressable.
-func (cad *condAddrDecoder) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if val.CanAddr() {
- return cad.canAddrDec.DecodeValue(dc, vr, val)
- }
- if cad.elseDec != nil {
- return cad.elseDec.DecodeValue(dc, vr, val)
- }
- return ErrNoDecoder{Type: val.Type()}
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go
deleted file mode 100644
index 52d2365a..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go
+++ /dev/null
@@ -1,1249 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "math"
- "net/url"
- "reflect"
- "strconv"
- "time"
-
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
- "go.mongodb.org/mongo-driver/bson/primitive"
- "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
-)
-
-var defaultValueDecoders DefaultValueDecoders
-
-// DefaultValueDecoders is a namespace type for the default ValueDecoders used
-// when creating a registry.
-type DefaultValueDecoders struct{}
-
-// RegisterDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with
-// the provided RegistryBuilder.
-//
-// There is no support for decoding map[string]interface{} becuase there is no decoder for
-// interface{}, so users must either register this decoder themselves or use the
-// EmptyInterfaceDecoder avaialble in the bson package.
-func (dvd DefaultValueDecoders) RegisterDefaultDecoders(rb *RegistryBuilder) {
- if rb == nil {
- panic(errors.New("argument to RegisterDefaultDecoders must not be nil"))
- }
-
- rb.
- RegisterTypeDecoder(tBinary, ValueDecoderFunc(dvd.BinaryDecodeValue)).
- RegisterTypeDecoder(tUndefined, ValueDecoderFunc(dvd.UndefinedDecodeValue)).
- RegisterTypeDecoder(tDateTime, ValueDecoderFunc(dvd.DateTimeDecodeValue)).
- RegisterTypeDecoder(tNull, ValueDecoderFunc(dvd.NullDecodeValue)).
- RegisterTypeDecoder(tRegex, ValueDecoderFunc(dvd.RegexDecodeValue)).
- RegisterTypeDecoder(tDBPointer, ValueDecoderFunc(dvd.DBPointerDecodeValue)).
- RegisterTypeDecoder(tTimestamp, ValueDecoderFunc(dvd.TimestampDecodeValue)).
- RegisterTypeDecoder(tMinKey, ValueDecoderFunc(dvd.MinKeyDecodeValue)).
- RegisterTypeDecoder(tMaxKey, ValueDecoderFunc(dvd.MaxKeyDecodeValue)).
- RegisterTypeDecoder(tJavaScript, ValueDecoderFunc(dvd.JavaScriptDecodeValue)).
- RegisterTypeDecoder(tSymbol, ValueDecoderFunc(dvd.SymbolDecodeValue)).
- RegisterTypeDecoder(tByteSlice, defaultByteSliceCodec).
- RegisterTypeDecoder(tTime, defaultTimeCodec).
- RegisterTypeDecoder(tEmpty, defaultEmptyInterfaceCodec).
- RegisterTypeDecoder(tOID, ValueDecoderFunc(dvd.ObjectIDDecodeValue)).
- RegisterTypeDecoder(tDecimal, ValueDecoderFunc(dvd.Decimal128DecodeValue)).
- RegisterTypeDecoder(tJSONNumber, ValueDecoderFunc(dvd.JSONNumberDecodeValue)).
- RegisterTypeDecoder(tURL, ValueDecoderFunc(dvd.URLDecodeValue)).
- RegisterTypeDecoder(tCoreDocument, ValueDecoderFunc(dvd.CoreDocumentDecodeValue)).
- RegisterTypeDecoder(tCodeWithScope, ValueDecoderFunc(dvd.CodeWithScopeDecodeValue)).
- RegisterDefaultDecoder(reflect.Bool, ValueDecoderFunc(dvd.BooleanDecodeValue)).
- RegisterDefaultDecoder(reflect.Int, ValueDecoderFunc(dvd.IntDecodeValue)).
- RegisterDefaultDecoder(reflect.Int8, ValueDecoderFunc(dvd.IntDecodeValue)).
- RegisterDefaultDecoder(reflect.Int16, ValueDecoderFunc(dvd.IntDecodeValue)).
- RegisterDefaultDecoder(reflect.Int32, ValueDecoderFunc(dvd.IntDecodeValue)).
- RegisterDefaultDecoder(reflect.Int64, ValueDecoderFunc(dvd.IntDecodeValue)).
- RegisterDefaultDecoder(reflect.Uint, defaultUIntCodec).
- RegisterDefaultDecoder(reflect.Uint8, defaultUIntCodec).
- RegisterDefaultDecoder(reflect.Uint16, defaultUIntCodec).
- RegisterDefaultDecoder(reflect.Uint32, defaultUIntCodec).
- RegisterDefaultDecoder(reflect.Uint64, defaultUIntCodec).
- RegisterDefaultDecoder(reflect.Float32, ValueDecoderFunc(dvd.FloatDecodeValue)).
- RegisterDefaultDecoder(reflect.Float64, ValueDecoderFunc(dvd.FloatDecodeValue)).
- RegisterDefaultDecoder(reflect.Array, ValueDecoderFunc(dvd.ArrayDecodeValue)).
- RegisterDefaultDecoder(reflect.Map, defaultMapCodec).
- RegisterDefaultDecoder(reflect.Slice, defaultSliceCodec).
- RegisterDefaultDecoder(reflect.String, defaultStringCodec).
- RegisterDefaultDecoder(reflect.Struct, defaultStructCodec).
- RegisterDefaultDecoder(reflect.Ptr, NewPointerCodec()).
- RegisterTypeMapEntry(bsontype.Double, tFloat64).
- RegisterTypeMapEntry(bsontype.String, tString).
- RegisterTypeMapEntry(bsontype.Array, tA).
- RegisterTypeMapEntry(bsontype.Binary, tBinary).
- RegisterTypeMapEntry(bsontype.Undefined, tUndefined).
- RegisterTypeMapEntry(bsontype.ObjectID, tOID).
- RegisterTypeMapEntry(bsontype.Boolean, tBool).
- RegisterTypeMapEntry(bsontype.DateTime, tDateTime).
- RegisterTypeMapEntry(bsontype.Regex, tRegex).
- RegisterTypeMapEntry(bsontype.DBPointer, tDBPointer).
- RegisterTypeMapEntry(bsontype.JavaScript, tJavaScript).
- RegisterTypeMapEntry(bsontype.Symbol, tSymbol).
- RegisterTypeMapEntry(bsontype.CodeWithScope, tCodeWithScope).
- RegisterTypeMapEntry(bsontype.Int32, tInt32).
- RegisterTypeMapEntry(bsontype.Int64, tInt64).
- RegisterTypeMapEntry(bsontype.Timestamp, tTimestamp).
- RegisterTypeMapEntry(bsontype.Decimal128, tDecimal).
- RegisterTypeMapEntry(bsontype.MinKey, tMinKey).
- RegisterTypeMapEntry(bsontype.MaxKey, tMaxKey).
- RegisterTypeMapEntry(bsontype.Type(0), tD).
- RegisterTypeMapEntry(bsontype.EmbeddedDocument, tD).
- RegisterHookDecoder(tValueUnmarshaler, ValueDecoderFunc(dvd.ValueUnmarshalerDecodeValue)).
- RegisterHookDecoder(tUnmarshaler, ValueDecoderFunc(dvd.UnmarshalerDecodeValue))
-}
-
-// BooleanDecodeValue is the ValueDecoderFunc for bool types.
-func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.IsValid() || !val.CanSet() || val.Kind() != reflect.Bool {
- return ValueDecoderError{Name: "BooleanDecodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val}
- }
-
- var b bool
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Int32:
- i32, err := vr.ReadInt32()
- if err != nil {
- return err
- }
- b = (i32 != 0)
- case bsontype.Int64:
- i64, err := vr.ReadInt64()
- if err != nil {
- return err
- }
- b = (i64 != 0)
- case bsontype.Double:
- f64, err := vr.ReadDouble()
- if err != nil {
- return err
- }
- b = (f64 != 0)
- case bsontype.Boolean:
- b, err = vr.ReadBoolean()
- if err != nil {
- return err
- }
- case bsontype.Null:
- if err = vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into a boolean", vrType)
- }
- val.SetBool(b)
- return nil
-}
-
-// IntDecodeValue is the ValueDecoderFunc for int types.
-func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() {
- return ValueDecoderError{
- Name: "IntDecodeValue",
- Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int},
- Received: val,
- }
- }
-
- var i64 int64
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Int32:
- i32, err := vr.ReadInt32()
- if err != nil {
- return err
- }
- i64 = int64(i32)
- case bsontype.Int64:
- i64, err = vr.ReadInt64()
- if err != nil {
- return err
- }
- case bsontype.Double:
- f64, err := vr.ReadDouble()
- if err != nil {
- return err
- }
- if !dc.Truncate && math.Floor(f64) != f64 {
- return errors.New("IntDecodeValue can only truncate float64 to an integer type when truncation is enabled")
- }
- if f64 > float64(math.MaxInt64) {
- return fmt.Errorf("%g overflows int64", f64)
- }
- i64 = int64(f64)
- case bsontype.Boolean:
- b, err := vr.ReadBoolean()
- if err != nil {
- return err
- }
- if b {
- i64 = 1
- }
- case bsontype.Null:
- if err = vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into an integer type", vrType)
- }
-
- switch val.Kind() {
- case reflect.Int8:
- if i64 < math.MinInt8 || i64 > math.MaxInt8 {
- return fmt.Errorf("%d overflows int8", i64)
- }
- case reflect.Int16:
- if i64 < math.MinInt16 || i64 > math.MaxInt16 {
- return fmt.Errorf("%d overflows int16", i64)
- }
- case reflect.Int32:
- if i64 < math.MinInt32 || i64 > math.MaxInt32 {
- return fmt.Errorf("%d overflows int32", i64)
- }
- case reflect.Int64:
- case reflect.Int:
- if int64(int(i64)) != i64 { // Can we fit this inside of an int
- return fmt.Errorf("%d overflows int", i64)
- }
- default:
- return ValueDecoderError{
- Name: "IntDecodeValue",
- Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int},
- Received: val,
- }
- }
-
- val.SetInt(i64)
- return nil
-}
-
-// UintDecodeValue is the ValueDecoderFunc for uint types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use UIntCodec.DecodeValue instead.
-func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- var i64 int64
- var err error
- switch vr.Type() {
- case bsontype.Int32:
- i32, err := vr.ReadInt32()
- if err != nil {
- return err
- }
- i64 = int64(i32)
- case bsontype.Int64:
- i64, err = vr.ReadInt64()
- if err != nil {
- return err
- }
- case bsontype.Double:
- f64, err := vr.ReadDouble()
- if err != nil {
- return err
- }
- if !dc.Truncate && math.Floor(f64) != f64 {
- return errors.New("UintDecodeValue can only truncate float64 to an integer type when truncation is enabled")
- }
- if f64 > float64(math.MaxInt64) {
- return fmt.Errorf("%g overflows int64", f64)
- }
- i64 = int64(f64)
- case bsontype.Boolean:
- b, err := vr.ReadBoolean()
- if err != nil {
- return err
- }
- if b {
- i64 = 1
- }
- default:
- return fmt.Errorf("cannot decode %v into an integer type", vr.Type())
- }
-
- if !val.CanSet() {
- return ValueDecoderError{
- Name: "UintDecodeValue",
- Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint},
- Received: val,
- }
- }
-
- switch val.Kind() {
- case reflect.Uint8:
- if i64 < 0 || i64 > math.MaxUint8 {
- return fmt.Errorf("%d overflows uint8", i64)
- }
- case reflect.Uint16:
- if i64 < 0 || i64 > math.MaxUint16 {
- return fmt.Errorf("%d overflows uint16", i64)
- }
- case reflect.Uint32:
- if i64 < 0 || i64 > math.MaxUint32 {
- return fmt.Errorf("%d overflows uint32", i64)
- }
- case reflect.Uint64:
- if i64 < 0 {
- return fmt.Errorf("%d overflows uint64", i64)
- }
- case reflect.Uint:
- if i64 < 0 || int64(uint(i64)) != i64 { // Can we fit this inside of an uint
- return fmt.Errorf("%d overflows uint", i64)
- }
- default:
- return ValueDecoderError{
- Name: "UintDecodeValue",
- Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint},
- Received: val,
- }
- }
-
- val.SetUint(uint64(i64))
- return nil
-}
-
-// FloatDecodeValue is the ValueDecoderFunc for float types.
-func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() {
- return ValueDecoderError{
- Name: "FloatDecodeValue",
- Kinds: []reflect.Kind{reflect.Float32, reflect.Float64},
- Received: val,
- }
- }
-
- var f float64
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Int32:
- i32, err := vr.ReadInt32()
- if err != nil {
- return err
- }
- f = float64(i32)
- case bsontype.Int64:
- i64, err := vr.ReadInt64()
- if err != nil {
- return err
- }
- f = float64(i64)
- case bsontype.Double:
- f, err = vr.ReadDouble()
- if err != nil {
- return err
- }
- case bsontype.Boolean:
- b, err := vr.ReadBoolean()
- if err != nil {
- return err
- }
- if b {
- f = 1
- }
- case bsontype.Null:
- if err = vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into a float32 or float64 type", vrType)
- }
-
- switch val.Kind() {
- case reflect.Float32:
- if !ec.Truncate && float64(float32(f)) != f {
- return errors.New("FloatDecodeValue can only convert float64 to float32 when truncation is allowed")
- }
- case reflect.Float64:
- default:
- return ValueDecoderError{Name: "FloatDecodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, Received: val}
- }
-
- val.SetFloat(f)
- return nil
-}
-
-// StringDecodeValue is the ValueDecoderFunc for string types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use StringCodec.DecodeValue instead.
-func (dvd DefaultValueDecoders) StringDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- var str string
- var err error
- switch vr.Type() {
- // TODO(GODRIVER-577): Handle JavaScript and Symbol BSON types when allowed.
- case bsontype.String:
- str, err = vr.ReadString()
- if err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into a string type", vr.Type())
- }
- if !val.CanSet() || val.Kind() != reflect.String {
- return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val}
- }
-
- val.SetString(str)
- return nil
-}
-
-// JavaScriptDecodeValue is the ValueDecoderFunc for the primitive.JavaScript type.
-func (DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tJavaScript {
- return ValueDecoderError{Name: "JavaScriptDecodeValue", Types: []reflect.Type{tJavaScript}, Received: val}
- }
-
- var js string
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.JavaScript:
- js, err = vr.ReadJavascript()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a primitive.JavaScript", vrType)
- }
-
- if err != nil {
- return err
- }
- val.SetString(js)
- return nil
-}
-
-// SymbolDecodeValue is the ValueDecoderFunc for the primitive.Symbol type.
-func (DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tSymbol {
- return ValueDecoderError{Name: "SymbolDecodeValue", Types: []reflect.Type{tSymbol}, Received: val}
- }
-
- var symbol string
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.String:
- symbol, err = vr.ReadString()
- if err != nil {
- return err
- }
- case bsontype.Symbol:
- symbol, err = vr.ReadSymbol()
- if err != nil {
- return err
- }
- case bsontype.Binary:
- data, subtype, err := vr.ReadBinary()
- if err != nil {
- return err
- }
- if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld {
- return fmt.Errorf("SymbolDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype)
- }
- symbol = string(data)
- case bsontype.Null:
- if err = vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into a primitive.Symbol", vrType)
- }
-
- val.SetString(symbol)
- return nil
-}
-
-// BinaryDecodeValue is the ValueDecoderFunc for Binary.
-func (DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tBinary {
- return ValueDecoderError{Name: "BinaryDecodeValue", Types: []reflect.Type{tBinary}, Received: val}
- }
-
- var data []byte
- var subtype byte
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Binary:
- data, subtype, err = vr.ReadBinary()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a Binary", vrType)
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.Binary{Subtype: subtype, Data: data}))
- return nil
-}
-
-// UndefinedDecodeValue is the ValueDecoderFunc for Undefined.
-func (DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tUndefined {
- return ValueDecoderError{Name: "UndefinedDecodeValue", Types: []reflect.Type{tUndefined}, Received: val}
- }
-
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Undefined:
- err = vr.ReadUndefined()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into an Undefined", vr.Type())
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.Undefined{}))
- return nil
-}
-
-// ObjectIDDecodeValue is the ValueDecoderFunc for primitive.ObjectID.
-func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tOID {
- return ValueDecoderError{Name: "ObjectIDDecodeValue", Types: []reflect.Type{tOID}, Received: val}
- }
-
- var oid primitive.ObjectID
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.ObjectID:
- oid, err = vr.ReadObjectID()
- if err != nil {
- return err
- }
- case bsontype.String:
- str, err := vr.ReadString()
- if err != nil {
- return err
- }
- if len(str) != 12 {
- return fmt.Errorf("an ObjectID string must be exactly 12 bytes long (got %v)", len(str))
- }
- byteArr := []byte(str)
- copy(oid[:], byteArr)
- case bsontype.Null:
- if err = vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into an ObjectID", vrType)
- }
-
- val.Set(reflect.ValueOf(oid))
- return nil
-}
-
-// DateTimeDecodeValue is the ValueDecoderFunc for DateTime.
-func (DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tDateTime {
- return ValueDecoderError{Name: "DateTimeDecodeValue", Types: []reflect.Type{tDateTime}, Received: val}
- }
-
- var dt int64
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.DateTime:
- dt, err = vr.ReadDateTime()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a DateTime", vrType)
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.DateTime(dt)))
- return nil
-}
-
-// NullDecodeValue is the ValueDecoderFunc for Null.
-func (DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tNull {
- return ValueDecoderError{Name: "NullDecodeValue", Types: []reflect.Type{tNull}, Received: val}
- }
-
- if vrType := vr.Type(); vrType != bsontype.Null {
- return fmt.Errorf("cannot decode %v into a Null", vrType)
- }
-
- val.Set(reflect.ValueOf(primitive.Null{}))
- return vr.ReadNull()
-}
-
-// RegexDecodeValue is the ValueDecoderFunc for Regex.
-func (DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tRegex {
- return ValueDecoderError{Name: "RegexDecodeValue", Types: []reflect.Type{tRegex}, Received: val}
- }
-
- var pattern, options string
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Regex:
- pattern, options, err = vr.ReadRegex()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a Regex", vrType)
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.Regex{Pattern: pattern, Options: options}))
- return nil
-}
-
-// DBPointerDecodeValue is the ValueDecoderFunc for DBPointer.
-func (DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tDBPointer {
- return ValueDecoderError{Name: "DBPointerDecodeValue", Types: []reflect.Type{tDBPointer}, Received: val}
- }
-
- var ns string
- var pointer primitive.ObjectID
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.DBPointer:
- ns, pointer, err = vr.ReadDBPointer()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a DBPointer", vrType)
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.DBPointer{DB: ns, Pointer: pointer}))
- return nil
-}
-
-// TimestampDecodeValue is the ValueDecoderFunc for Timestamp.
-func (DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tTimestamp {
- return ValueDecoderError{Name: "TimestampDecodeValue", Types: []reflect.Type{tTimestamp}, Received: val}
- }
-
- var t, incr uint32
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Timestamp:
- t, incr, err = vr.ReadTimestamp()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a Timestamp", vrType)
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.Timestamp{T: t, I: incr}))
- return nil
-}
-
-// MinKeyDecodeValue is the ValueDecoderFunc for MinKey.
-func (DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tMinKey {
- return ValueDecoderError{Name: "MinKeyDecodeValue", Types: []reflect.Type{tMinKey}, Received: val}
- }
-
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.MinKey:
- err = vr.ReadMinKey()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a MinKey", vr.Type())
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.MinKey{}))
- return nil
-}
-
-// MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey.
-func (DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tMaxKey {
- return ValueDecoderError{Name: "MaxKeyDecodeValue", Types: []reflect.Type{tMaxKey}, Received: val}
- }
-
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.MaxKey:
- err = vr.ReadMaxKey()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a MaxKey", vr.Type())
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.MaxKey{}))
- return nil
-}
-
-// Decimal128DecodeValue is the ValueDecoderFunc for primitive.Decimal128.
-func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tDecimal {
- return ValueDecoderError{Name: "Decimal128DecodeValue", Types: []reflect.Type{tDecimal}, Received: val}
- }
-
- var d128 primitive.Decimal128
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Decimal128:
- d128, err = vr.ReadDecimal128()
- case bsontype.Null:
- err = vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a primitive.Decimal128", vr.Type())
- }
-
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(d128))
- return err
-}
-
-// JSONNumberDecodeValue is the ValueDecoderFunc for json.Number.
-func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tJSONNumber {
- return ValueDecoderError{Name: "JSONNumberDecodeValue", Types: []reflect.Type{tJSONNumber}, Received: val}
- }
-
- switch vrType := vr.Type(); vrType {
- case bsontype.Double:
- f64, err := vr.ReadDouble()
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(json.Number(strconv.FormatFloat(f64, 'f', -1, 64))))
- case bsontype.Int32:
- i32, err := vr.ReadInt32()
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(json.Number(strconv.FormatInt(int64(i32), 10))))
- case bsontype.Int64:
- i64, err := vr.ReadInt64()
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(json.Number(strconv.FormatInt(i64, 10))))
- case bsontype.Null:
- if err := vr.ReadNull(); err != nil {
- return err
- }
- val.SetString("")
- default:
- return fmt.Errorf("cannot decode %v into a json.Number", vrType)
- }
-
- return nil
-}
-
-// URLDecodeValue is the ValueDecoderFunc for url.URL.
-func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tURL {
- return ValueDecoderError{Name: "URLDecodeValue", Types: []reflect.Type{tURL}, Received: val}
- }
-
- switch vrType := vr.Type(); vrType {
- case bsontype.String:
- str, err := vr.ReadString()
- if err != nil {
- return err
- }
-
- parsedURL, err := url.Parse(str)
- if err != nil {
- return err
- }
- val.Set(reflect.ValueOf(parsedURL).Elem())
- return nil
- case bsontype.Null:
- if err := vr.ReadNull(); err != nil {
- return err
- }
- val.Set(reflect.ValueOf(url.URL{}))
- return nil
- default:
- return fmt.Errorf("cannot decode %v into a *url.URL", vrType)
- }
-}
-
-// TimeDecodeValue is the ValueDecoderFunc for time.Time.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use Time.DecodeValue instead.
-func (dvd DefaultValueDecoders) TimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if vr.Type() != bsontype.DateTime {
- return fmt.Errorf("cannot decode %v into a time.Time", vr.Type())
- }
-
- dt, err := vr.ReadDateTime()
- if err != nil {
- return err
- }
-
- if !val.CanSet() || val.Type() != tTime {
- return ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: val}
- }
-
- val.Set(reflect.ValueOf(time.Unix(dt/1000, dt%1000*1000000).UTC()))
- return nil
-}
-
-// ByteSliceDecodeValue is the ValueDecoderFunc for []byte.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use ByteSliceCodec.DecodeValue instead.
-func (dvd DefaultValueDecoders) ByteSliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if vr.Type() != bsontype.Binary && vr.Type() != bsontype.Null {
- return fmt.Errorf("cannot decode %v into a []byte", vr.Type())
- }
-
- if !val.CanSet() || val.Type() != tByteSlice {
- return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val}
- }
-
- if vr.Type() == bsontype.Null {
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- }
-
- data, subtype, err := vr.ReadBinary()
- if err != nil {
- return err
- }
- if subtype != 0x00 {
- return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 for %s, got %v", bsontype.Binary, subtype)
- }
-
- val.Set(reflect.ValueOf(data))
- return nil
-}
-
-// MapDecodeValue is the ValueDecoderFunc for map[string]* types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use Map.DecodeValue instead.
-func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String {
- return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val}
- }
-
- switch vr.Type() {
- case bsontype.Type(0), bsontype.EmbeddedDocument:
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a %s", vr.Type(), val.Type())
- }
-
- dr, err := vr.ReadDocument()
- if err != nil {
- return err
- }
-
- if val.IsNil() {
- val.Set(reflect.MakeMap(val.Type()))
- }
-
- eType := val.Type().Elem()
- decoder, err := dc.LookupDecoder(eType)
- if err != nil {
- return err
- }
-
- if eType == tEmpty {
- dc.Ancestor = val.Type()
- }
-
- keyType := val.Type().Key()
- for {
- key, vr, err := dr.ReadElement()
- if err == bsonrw.ErrEOD {
- break
- }
- if err != nil {
- return err
- }
-
- elem := reflect.New(eType).Elem()
-
- err = decoder.DecodeValue(dc, vr, elem)
- if err != nil {
- return err
- }
-
- val.SetMapIndex(reflect.ValueOf(key).Convert(keyType), elem)
- }
- return nil
-}
-
-// ArrayDecodeValue is the ValueDecoderFunc for array types.
-func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Array {
- return ValueDecoderError{Name: "ArrayDecodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val}
- }
-
- switch vrType := vr.Type(); vrType {
- case bsontype.Array:
- case bsontype.Type(0), bsontype.EmbeddedDocument:
- if val.Type().Elem() != tE {
- return fmt.Errorf("cannot decode document into %s", val.Type())
- }
- case bsontype.Binary:
- if val.Type().Elem() != tByte {
- return fmt.Errorf("ArrayDecodeValue can only be used to decode binary into a byte array, got %v", vrType)
- }
- data, subtype, err := vr.ReadBinary()
- if err != nil {
- return err
- }
- if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld {
- return fmt.Errorf("ArrayDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype)
- }
-
- if len(data) > val.Len() {
- return fmt.Errorf("more elements returned in array than can fit inside %s", val.Type())
- }
-
- for idx, elem := range data {
- val.Index(idx).Set(reflect.ValueOf(elem))
- }
- return nil
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into an array", vrType)
- }
-
- var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error)
- switch val.Type().Elem() {
- case tE:
- elemsFunc = dvd.decodeD
- default:
- elemsFunc = dvd.decodeDefault
- }
-
- elems, err := elemsFunc(dc, vr, val)
- if err != nil {
- return err
- }
-
- if len(elems) > val.Len() {
- return fmt.Errorf("more elements returned in array than can fit inside %s, got %v elements", val.Type(), len(elems))
- }
-
- for idx, elem := range elems {
- val.Index(idx).Set(elem)
- }
-
- return nil
-}
-
-// SliceDecodeValue is the ValueDecoderFunc for slice types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use SliceCodec.DecodeValue instead.
-func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Kind() != reflect.Slice {
- return ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val}
- }
-
- switch vr.Type() {
- case bsontype.Array:
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- case bsontype.Type(0), bsontype.EmbeddedDocument:
- if val.Type().Elem() != tE {
- return fmt.Errorf("cannot decode document into %s", val.Type())
- }
- default:
- return fmt.Errorf("cannot decode %v into a slice", vr.Type())
- }
-
- var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error)
- switch val.Type().Elem() {
- case tE:
- dc.Ancestor = val.Type()
- elemsFunc = dvd.decodeD
- default:
- elemsFunc = dvd.decodeDefault
- }
-
- elems, err := elemsFunc(dc, vr, val)
- if err != nil {
- return err
- }
-
- if val.IsNil() {
- val.Set(reflect.MakeSlice(val.Type(), 0, len(elems)))
- }
-
- val.SetLen(0)
- val.Set(reflect.Append(val, elems...))
-
- return nil
-}
-
-// ValueUnmarshalerDecodeValue is the ValueDecoderFunc for ValueUnmarshaler implementations.
-func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.IsValid() || (!val.Type().Implements(tValueUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tValueUnmarshaler)) {
- return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val}
- }
-
- if val.Kind() == reflect.Ptr && val.IsNil() {
- if !val.CanSet() {
- return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val}
- }
- val.Set(reflect.New(val.Type().Elem()))
- }
-
- if !val.Type().Implements(tValueUnmarshaler) {
- if !val.CanAddr() {
- return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val}
- }
- val = val.Addr() // If they type doesn't implement the interface, a pointer to it must.
- }
-
- t, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
- if err != nil {
- return err
- }
-
- fn := val.Convert(tValueUnmarshaler).MethodByName("UnmarshalBSONValue")
- errVal := fn.Call([]reflect.Value{reflect.ValueOf(t), reflect.ValueOf(src)})[0]
- if !errVal.IsNil() {
- return errVal.Interface().(error)
- }
- return nil
-}
-
-// UnmarshalerDecodeValue is the ValueDecoderFunc for Unmarshaler implementations.
-func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.IsValid() || (!val.Type().Implements(tUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tUnmarshaler)) {
- return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val}
- }
-
- if val.Kind() == reflect.Ptr && val.IsNil() {
- if !val.CanSet() {
- return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val}
- }
- val.Set(reflect.New(val.Type().Elem()))
- }
-
- if !val.Type().Implements(tUnmarshaler) {
- if !val.CanAddr() {
- return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val}
- }
- val = val.Addr() // If they type doesn't implement the interface, a pointer to it must.
- }
-
- _, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
- if err != nil {
- return err
- }
-
- fn := val.Convert(tUnmarshaler).MethodByName("UnmarshalBSON")
- errVal := fn.Call([]reflect.Value{reflect.ValueOf(src)})[0]
- if !errVal.IsNil() {
- return errVal.Interface().(error)
- }
- return nil
-}
-
-// EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use EmptyInterfaceCodec.DecodeValue instead.
-func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tEmpty {
- return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val}
- }
-
- rtype, err := dc.LookupTypeMapEntry(vr.Type())
- if err != nil {
- switch vr.Type() {
- case bsontype.EmbeddedDocument:
- if dc.Ancestor != nil {
- rtype = dc.Ancestor
- break
- }
- rtype = tD
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- default:
- return err
- }
- }
-
- decoder, err := dc.LookupDecoder(rtype)
- if err != nil {
- return err
- }
-
- elem := reflect.New(rtype).Elem()
- err = decoder.DecodeValue(dc, vr, elem)
- if err != nil {
- return err
- }
-
- val.Set(elem)
- return nil
-}
-
-// CoreDocumentDecodeValue is the ValueDecoderFunc for bsoncore.Document.
-func (DefaultValueDecoders) CoreDocumentDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tCoreDocument {
- return ValueDecoderError{Name: "CoreDocumentDecodeValue", Types: []reflect.Type{tCoreDocument}, Received: val}
- }
-
- if val.IsNil() {
- val.Set(reflect.MakeSlice(val.Type(), 0, 0))
- }
-
- val.SetLen(0)
-
- cdoc, err := bsonrw.Copier{}.AppendDocumentBytes(val.Interface().(bsoncore.Document), vr)
- val.Set(reflect.ValueOf(cdoc))
- return err
-}
-
-func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) ([]reflect.Value, error) {
- elems := make([]reflect.Value, 0)
-
- ar, err := vr.ReadArray()
- if err != nil {
- return nil, err
- }
-
- eType := val.Type().Elem()
-
- decoder, err := dc.LookupDecoder(eType)
- if err != nil {
- return nil, err
- }
-
- for {
- vr, err := ar.ReadValue()
- if err == bsonrw.ErrEOA {
- break
- }
- if err != nil {
- return nil, err
- }
-
- elem := reflect.New(eType).Elem()
-
- err = decoder.DecodeValue(dc, vr, elem)
- if err != nil {
- return nil, err
- }
- elems = append(elems, elem)
- }
-
- return elems, nil
-}
-
-// CodeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope.
-func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tCodeWithScope {
- return ValueDecoderError{Name: "CodeWithScopeDecodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val}
- }
-
- switch vrType := vr.Type(); vrType {
- case bsontype.CodeWithScope:
- code, dr, err := vr.ReadCodeWithScope()
- if err != nil {
- return err
- }
-
- scope := reflect.New(tD).Elem()
- elems, err := dvd.decodeElemsFromDocumentReader(dc, dr)
- if err != nil {
- return err
- }
-
- scope.Set(reflect.MakeSlice(tD, 0, len(elems)))
- scope.Set(reflect.Append(scope, elems...))
-
- val.Set(reflect.ValueOf(primitive.CodeWithScope{
- Code: primitive.JavaScript(code),
- Scope: scope.Interface().(primitive.D),
- }))
- return nil
- case bsontype.Null:
- if err := vr.ReadNull(); err != nil {
- return err
- }
- val.Set(reflect.ValueOf(primitive.CodeWithScope{}))
- return nil
- default:
- return fmt.Errorf("cannot decode %v into a primitive.CodeWithScope", vrType)
- }
-}
-
-func (dvd DefaultValueDecoders) decodeD(dc DecodeContext, vr bsonrw.ValueReader, _ reflect.Value) ([]reflect.Value, error) {
- switch vr.Type() {
- case bsontype.Type(0), bsontype.EmbeddedDocument:
- default:
- return nil, fmt.Errorf("cannot decode %v into a D", vr.Type())
- }
-
- dr, err := vr.ReadDocument()
- if err != nil {
- return nil, err
- }
-
- return dvd.decodeElemsFromDocumentReader(dc, dr)
-}
-
-func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr bsonrw.DocumentReader) ([]reflect.Value, error) {
- decoder, err := dc.LookupDecoder(tEmpty)
- if err != nil {
- return nil, err
- }
-
- elems := make([]reflect.Value, 0)
- for {
- key, vr, err := dr.ReadElement()
- if err == bsonrw.ErrEOD {
- break
- }
- if err != nil {
- return nil, err
- }
-
- val := reflect.New(tEmpty).Elem()
- err = decoder.DecodeValue(dc, vr, val)
- if err != nil {
- return nil, err
- }
-
- elems = append(elems, reflect.ValueOf(primitive.E{Key: key, Value: val.Interface()}))
- }
-
- return elems, nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go
deleted file mode 100644
index 08078b30..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go
+++ /dev/null
@@ -1,771 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "math"
- "net/url"
- "reflect"
- "sync"
- "time"
-
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
- "go.mongodb.org/mongo-driver/bson/primitive"
- "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
-)
-
-var defaultValueEncoders DefaultValueEncoders
-
-var bvwPool = bsonrw.NewBSONValueWriterPool()
-
-var errInvalidValue = errors.New("cannot encode invalid element")
-
-var sliceWriterPool = sync.Pool{
- New: func() interface{} {
- sw := make(bsonrw.SliceWriter, 0, 0)
- return &sw
- },
-}
-
-func encodeElement(ec EncodeContext, dw bsonrw.DocumentWriter, e primitive.E) error {
- vw, err := dw.WriteDocumentElement(e.Key)
- if err != nil {
- return err
- }
-
- if e.Value == nil {
- return vw.WriteNull()
- }
- encoder, err := ec.LookupEncoder(reflect.TypeOf(e.Value))
- if err != nil {
- return err
- }
-
- err = encoder.EncodeValue(ec, vw, reflect.ValueOf(e.Value))
- if err != nil {
- return err
- }
- return nil
-}
-
-// DefaultValueEncoders is a namespace type for the default ValueEncoders used
-// when creating a registry.
-type DefaultValueEncoders struct{}
-
-// RegisterDefaultEncoders will register the encoder methods attached to DefaultValueEncoders with
-// the provided RegistryBuilder.
-func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder) {
- if rb == nil {
- panic(errors.New("argument to RegisterDefaultEncoders must not be nil"))
- }
- rb.
- RegisterTypeEncoder(tByteSlice, defaultByteSliceCodec).
- RegisterTypeEncoder(tTime, defaultTimeCodec).
- RegisterTypeEncoder(tEmpty, defaultEmptyInterfaceCodec).
- RegisterTypeEncoder(tOID, ValueEncoderFunc(dve.ObjectIDEncodeValue)).
- RegisterTypeEncoder(tDecimal, ValueEncoderFunc(dve.Decimal128EncodeValue)).
- RegisterTypeEncoder(tJSONNumber, ValueEncoderFunc(dve.JSONNumberEncodeValue)).
- RegisterTypeEncoder(tURL, ValueEncoderFunc(dve.URLEncodeValue)).
- RegisterTypeEncoder(tJavaScript, ValueEncoderFunc(dve.JavaScriptEncodeValue)).
- RegisterTypeEncoder(tSymbol, ValueEncoderFunc(dve.SymbolEncodeValue)).
- RegisterTypeEncoder(tBinary, ValueEncoderFunc(dve.BinaryEncodeValue)).
- RegisterTypeEncoder(tUndefined, ValueEncoderFunc(dve.UndefinedEncodeValue)).
- RegisterTypeEncoder(tDateTime, ValueEncoderFunc(dve.DateTimeEncodeValue)).
- RegisterTypeEncoder(tNull, ValueEncoderFunc(dve.NullEncodeValue)).
- RegisterTypeEncoder(tRegex, ValueEncoderFunc(dve.RegexEncodeValue)).
- RegisterTypeEncoder(tDBPointer, ValueEncoderFunc(dve.DBPointerEncodeValue)).
- RegisterTypeEncoder(tTimestamp, ValueEncoderFunc(dve.TimestampEncodeValue)).
- RegisterTypeEncoder(tMinKey, ValueEncoderFunc(dve.MinKeyEncodeValue)).
- RegisterTypeEncoder(tMaxKey, ValueEncoderFunc(dve.MaxKeyEncodeValue)).
- RegisterTypeEncoder(tCoreDocument, ValueEncoderFunc(dve.CoreDocumentEncodeValue)).
- RegisterTypeEncoder(tCodeWithScope, ValueEncoderFunc(dve.CodeWithScopeEncodeValue)).
- RegisterDefaultEncoder(reflect.Bool, ValueEncoderFunc(dve.BooleanEncodeValue)).
- RegisterDefaultEncoder(reflect.Int, ValueEncoderFunc(dve.IntEncodeValue)).
- RegisterDefaultEncoder(reflect.Int8, ValueEncoderFunc(dve.IntEncodeValue)).
- RegisterDefaultEncoder(reflect.Int16, ValueEncoderFunc(dve.IntEncodeValue)).
- RegisterDefaultEncoder(reflect.Int32, ValueEncoderFunc(dve.IntEncodeValue)).
- RegisterDefaultEncoder(reflect.Int64, ValueEncoderFunc(dve.IntEncodeValue)).
- RegisterDefaultEncoder(reflect.Uint, defaultUIntCodec).
- RegisterDefaultEncoder(reflect.Uint8, defaultUIntCodec).
- RegisterDefaultEncoder(reflect.Uint16, defaultUIntCodec).
- RegisterDefaultEncoder(reflect.Uint32, defaultUIntCodec).
- RegisterDefaultEncoder(reflect.Uint64, defaultUIntCodec).
- RegisterDefaultEncoder(reflect.Float32, ValueEncoderFunc(dve.FloatEncodeValue)).
- RegisterDefaultEncoder(reflect.Float64, ValueEncoderFunc(dve.FloatEncodeValue)).
- RegisterDefaultEncoder(reflect.Array, ValueEncoderFunc(dve.ArrayEncodeValue)).
- RegisterDefaultEncoder(reflect.Map, defaultMapCodec).
- RegisterDefaultEncoder(reflect.Slice, defaultSliceCodec).
- RegisterDefaultEncoder(reflect.String, defaultStringCodec).
- RegisterDefaultEncoder(reflect.Struct, defaultStructCodec).
- RegisterDefaultEncoder(reflect.Ptr, NewPointerCodec()).
- RegisterHookEncoder(tValueMarshaler, ValueEncoderFunc(dve.ValueMarshalerEncodeValue)).
- RegisterHookEncoder(tMarshaler, ValueEncoderFunc(dve.MarshalerEncodeValue)).
- RegisterHookEncoder(tProxy, ValueEncoderFunc(dve.ProxyEncodeValue))
-}
-
-// BooleanEncodeValue is the ValueEncoderFunc for bool types.
-func (dve DefaultValueEncoders) BooleanEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Bool {
- return ValueEncoderError{Name: "BooleanEncodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val}
- }
- return vw.WriteBoolean(val.Bool())
-}
-
-func fitsIn32Bits(i int64) bool {
- return math.MinInt32 <= i && i <= math.MaxInt32
-}
-
-// IntEncodeValue is the ValueEncoderFunc for int types.
-func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- switch val.Kind() {
- case reflect.Int8, reflect.Int16, reflect.Int32:
- return vw.WriteInt32(int32(val.Int()))
- case reflect.Int:
- i64 := val.Int()
- if fitsIn32Bits(i64) {
- return vw.WriteInt32(int32(i64))
- }
- return vw.WriteInt64(i64)
- case reflect.Int64:
- i64 := val.Int()
- if ec.MinSize && fitsIn32Bits(i64) {
- return vw.WriteInt32(int32(i64))
- }
- return vw.WriteInt64(i64)
- }
-
- return ValueEncoderError{
- Name: "IntEncodeValue",
- Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int},
- Received: val,
- }
-}
-
-// UintEncodeValue is the ValueEncoderFunc for uint types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use UIntCodec.EncodeValue instead.
-func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- switch val.Kind() {
- case reflect.Uint8, reflect.Uint16:
- return vw.WriteInt32(int32(val.Uint()))
- case reflect.Uint, reflect.Uint32, reflect.Uint64:
- u64 := val.Uint()
- if ec.MinSize && u64 <= math.MaxInt32 {
- return vw.WriteInt32(int32(u64))
- }
- if u64 > math.MaxInt64 {
- return fmt.Errorf("%d overflows int64", u64)
- }
- return vw.WriteInt64(int64(u64))
- }
-
- return ValueEncoderError{
- Name: "UintEncodeValue",
- Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint},
- Received: val,
- }
-}
-
-// FloatEncodeValue is the ValueEncoderFunc for float types.
-func (dve DefaultValueEncoders) FloatEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- switch val.Kind() {
- case reflect.Float32, reflect.Float64:
- return vw.WriteDouble(val.Float())
- }
-
- return ValueEncoderError{Name: "FloatEncodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, Received: val}
-}
-
-// StringEncodeValue is the ValueEncoderFunc for string types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use StringCodec.EncodeValue instead.
-func (dve DefaultValueEncoders) StringEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if val.Kind() != reflect.String {
- return ValueEncoderError{
- Name: "StringEncodeValue",
- Kinds: []reflect.Kind{reflect.String},
- Received: val,
- }
- }
-
- return vw.WriteString(val.String())
-}
-
-// ObjectIDEncodeValue is the ValueEncoderFunc for primitive.ObjectID.
-func (dve DefaultValueEncoders) ObjectIDEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tOID {
- return ValueEncoderError{Name: "ObjectIDEncodeValue", Types: []reflect.Type{tOID}, Received: val}
- }
- return vw.WriteObjectID(val.Interface().(primitive.ObjectID))
-}
-
-// Decimal128EncodeValue is the ValueEncoderFunc for primitive.Decimal128.
-func (dve DefaultValueEncoders) Decimal128EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tDecimal {
- return ValueEncoderError{Name: "Decimal128EncodeValue", Types: []reflect.Type{tDecimal}, Received: val}
- }
- return vw.WriteDecimal128(val.Interface().(primitive.Decimal128))
-}
-
-// JSONNumberEncodeValue is the ValueEncoderFunc for json.Number.
-func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tJSONNumber {
- return ValueEncoderError{Name: "JSONNumberEncodeValue", Types: []reflect.Type{tJSONNumber}, Received: val}
- }
- jsnum := val.Interface().(json.Number)
-
- // Attempt int first, then float64
- if i64, err := jsnum.Int64(); err == nil {
- return dve.IntEncodeValue(ec, vw, reflect.ValueOf(i64))
- }
-
- f64, err := jsnum.Float64()
- if err != nil {
- return err
- }
-
- return dve.FloatEncodeValue(ec, vw, reflect.ValueOf(f64))
-}
-
-// URLEncodeValue is the ValueEncoderFunc for url.URL.
-func (dve DefaultValueEncoders) URLEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tURL {
- return ValueEncoderError{Name: "URLEncodeValue", Types: []reflect.Type{tURL}, Received: val}
- }
- u := val.Interface().(url.URL)
- return vw.WriteString(u.String())
-}
-
-// TimeEncodeValue is the ValueEncoderFunc for time.TIme.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use TimeCodec.EncodeValue instead.
-func (dve DefaultValueEncoders) TimeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tTime {
- return ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: val}
- }
- tt := val.Interface().(time.Time)
- return vw.WriteDateTime(tt.Unix()*1000 + int64(tt.Nanosecond()/1e6))
-}
-
-// ByteSliceEncodeValue is the ValueEncoderFunc for []byte.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use ByteSliceCodec.EncodeValue instead.
-func (dve DefaultValueEncoders) ByteSliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tByteSlice {
- return ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: val}
- }
- if val.IsNil() {
- return vw.WriteNull()
- }
- return vw.WriteBinary(val.Interface().([]byte))
-}
-
-// MapEncodeValue is the ValueEncoderFunc for map[string]* types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use MapCodec.EncodeValue instead.
-func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String {
- return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val}
- }
-
- if val.IsNil() {
- // If we have a nill map but we can't WriteNull, that means we're probably trying to encode
- // to a TopLevel document. We can't currently tell if this is what actually happened, but if
- // there's a deeper underlying problem, the error will also be returned from WriteDocument,
- // so just continue. The operations on a map reflection value are valid, so we can call
- // MapKeys within mapEncodeValue without a problem.
- err := vw.WriteNull()
- if err == nil {
- return nil
- }
- }
-
- dw, err := vw.WriteDocument()
- if err != nil {
- return err
- }
-
- return dve.mapEncodeValue(ec, dw, val, nil)
-}
-
-// mapEncodeValue handles encoding of the values of a map. The collisionFn returns
-// true if the provided key exists, this is mainly used for inline maps in the
-// struct codec.
-func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error {
-
- elemType := val.Type().Elem()
- encoder, err := ec.LookupEncoder(elemType)
- if err != nil && elemType.Kind() != reflect.Interface {
- return err
- }
-
- keys := val.MapKeys()
- for _, key := range keys {
- if collisionFn != nil && collisionFn(key.String()) {
- return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key)
- }
-
- currEncoder, currVal, lookupErr := dve.lookupElementEncoder(ec, encoder, val.MapIndex(key))
- if lookupErr != nil && lookupErr != errInvalidValue {
- return lookupErr
- }
-
- vw, err := dw.WriteDocumentElement(key.String())
- if err != nil {
- return err
- }
-
- if lookupErr == errInvalidValue {
- err = vw.WriteNull()
- if err != nil {
- return err
- }
- continue
- }
-
- if enc, ok := currEncoder.(ValueEncoder); ok {
- err = enc.EncodeValue(ec, vw, currVal)
- if err != nil {
- return err
- }
- continue
- }
- err = encoder.EncodeValue(ec, vw, currVal)
- if err != nil {
- return err
- }
- }
-
- return dw.WriteDocumentEnd()
-}
-
-// ArrayEncodeValue is the ValueEncoderFunc for array types.
-func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Array {
- return ValueEncoderError{Name: "ArrayEncodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val}
- }
-
- // If we have a []primitive.E we want to treat it as a document instead of as an array.
- if val.Type().Elem() == tE {
- dw, err := vw.WriteDocument()
- if err != nil {
- return err
- }
-
- for idx := 0; idx < val.Len(); idx++ {
- e := val.Index(idx).Interface().(primitive.E)
- err = encodeElement(ec, dw, e)
- if err != nil {
- return err
- }
- }
-
- return dw.WriteDocumentEnd()
- }
-
- // If we have a []byte we want to treat it as a binary instead of as an array.
- if val.Type().Elem() == tByte {
- var byteSlice []byte
- for idx := 0; idx < val.Len(); idx++ {
- byteSlice = append(byteSlice, val.Index(idx).Interface().(byte))
- }
- return vw.WriteBinary(byteSlice)
- }
-
- aw, err := vw.WriteArray()
- if err != nil {
- return err
- }
-
- elemType := val.Type().Elem()
- encoder, err := ec.LookupEncoder(elemType)
- if err != nil && elemType.Kind() != reflect.Interface {
- return err
- }
-
- for idx := 0; idx < val.Len(); idx++ {
- currEncoder, currVal, lookupErr := dve.lookupElementEncoder(ec, encoder, val.Index(idx))
- if lookupErr != nil && lookupErr != errInvalidValue {
- return lookupErr
- }
-
- vw, err := aw.WriteArrayElement()
- if err != nil {
- return err
- }
-
- if lookupErr == errInvalidValue {
- err = vw.WriteNull()
- if err != nil {
- return err
- }
- continue
- }
-
- err = currEncoder.EncodeValue(ec, vw, currVal)
- if err != nil {
- return err
- }
- }
- return aw.WriteArrayEnd()
-}
-
-// SliceEncodeValue is the ValueEncoderFunc for slice types.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use SliceCodec.EncodeValue instead.
-func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Slice {
- return ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val}
- }
-
- if val.IsNil() {
- return vw.WriteNull()
- }
-
- // If we have a []primitive.E we want to treat it as a document instead of as an array.
- if val.Type().ConvertibleTo(tD) {
- d := val.Convert(tD).Interface().(primitive.D)
-
- dw, err := vw.WriteDocument()
- if err != nil {
- return err
- }
-
- for _, e := range d {
- err = encodeElement(ec, dw, e)
- if err != nil {
- return err
- }
- }
-
- return dw.WriteDocumentEnd()
- }
-
- aw, err := vw.WriteArray()
- if err != nil {
- return err
- }
-
- elemType := val.Type().Elem()
- encoder, err := ec.LookupEncoder(elemType)
- if err != nil && elemType.Kind() != reflect.Interface {
- return err
- }
-
- for idx := 0; idx < val.Len(); idx++ {
- currEncoder, currVal, lookupErr := dve.lookupElementEncoder(ec, encoder, val.Index(idx))
- if lookupErr != nil && lookupErr != errInvalidValue {
- return lookupErr
- }
-
- vw, err := aw.WriteArrayElement()
- if err != nil {
- return err
- }
-
- if lookupErr == errInvalidValue {
- err = vw.WriteNull()
- if err != nil {
- return err
- }
- continue
- }
-
- err = currEncoder.EncodeValue(ec, vw, currVal)
- if err != nil {
- return err
- }
- }
- return aw.WriteArrayEnd()
-}
-
-func (dve DefaultValueEncoders) lookupElementEncoder(ec EncodeContext, origEncoder ValueEncoder, currVal reflect.Value) (ValueEncoder, reflect.Value, error) {
- if origEncoder != nil || (currVal.Kind() != reflect.Interface) {
- return origEncoder, currVal, nil
- }
- currVal = currVal.Elem()
- if !currVal.IsValid() {
- return nil, currVal, errInvalidValue
- }
- currEncoder, err := ec.LookupEncoder(currVal.Type())
-
- return currEncoder, currVal, err
-}
-
-// EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}.
-// This method is deprecated and does not have any stability guarantees. It may be removed in the
-// future. Use EmptyInterfaceCodec.EncodeValue instead.
-func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tEmpty {
- return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val}
- }
-
- if val.IsNil() {
- return vw.WriteNull()
- }
- encoder, err := ec.LookupEncoder(val.Elem().Type())
- if err != nil {
- return err
- }
-
- return encoder.EncodeValue(ec, vw, val.Elem())
-}
-
-// ValueMarshalerEncodeValue is the ValueEncoderFunc for ValueMarshaler implementations.
-func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- // Either val or a pointer to val must implement ValueMarshaler
- switch {
- case !val.IsValid():
- return ValueEncoderError{Name: "ValueMarshalerEncodeValue", Types: []reflect.Type{tValueMarshaler}, Received: val}
- case val.Type().Implements(tValueMarshaler):
- // If ValueMarshaler is implemented on a concrete type, make sure that val isn't a nil pointer
- if isImplementationNil(val, tValueMarshaler) {
- return vw.WriteNull()
- }
- case reflect.PtrTo(val.Type()).Implements(tValueMarshaler) && val.CanAddr():
- val = val.Addr()
- default:
- return ValueEncoderError{Name: "ValueMarshalerEncodeValue", Types: []reflect.Type{tValueMarshaler}, Received: val}
- }
-
- fn := val.Convert(tValueMarshaler).MethodByName("MarshalBSONValue")
- returns := fn.Call(nil)
- if !returns[2].IsNil() {
- return returns[2].Interface().(error)
- }
- t, data := returns[0].Interface().(bsontype.Type), returns[1].Interface().([]byte)
- return bsonrw.Copier{}.CopyValueFromBytes(vw, t, data)
-}
-
-// MarshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations.
-func (dve DefaultValueEncoders) MarshalerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- // Either val or a pointer to val must implement Marshaler
- switch {
- case !val.IsValid():
- return ValueEncoderError{Name: "MarshalerEncodeValue", Types: []reflect.Type{tMarshaler}, Received: val}
- case val.Type().Implements(tMarshaler):
- // If Marshaler is implemented on a concrete type, make sure that val isn't a nil pointer
- if isImplementationNil(val, tMarshaler) {
- return vw.WriteNull()
- }
- case reflect.PtrTo(val.Type()).Implements(tMarshaler) && val.CanAddr():
- val = val.Addr()
- default:
- return ValueEncoderError{Name: "MarshalerEncodeValue", Types: []reflect.Type{tMarshaler}, Received: val}
- }
-
- fn := val.Convert(tMarshaler).MethodByName("MarshalBSON")
- returns := fn.Call(nil)
- if !returns[1].IsNil() {
- return returns[1].Interface().(error)
- }
- data := returns[0].Interface().([]byte)
- return bsonrw.Copier{}.CopyValueFromBytes(vw, bsontype.EmbeddedDocument, data)
-}
-
-// ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations.
-func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- // Either val or a pointer to val must implement Proxy
- switch {
- case !val.IsValid():
- return ValueEncoderError{Name: "ProxyEncodeValue", Types: []reflect.Type{tProxy}, Received: val}
- case val.Type().Implements(tProxy):
- // If Proxy is implemented on a concrete type, make sure that val isn't a nil pointer
- if isImplementationNil(val, tProxy) {
- return vw.WriteNull()
- }
- case reflect.PtrTo(val.Type()).Implements(tProxy) && val.CanAddr():
- val = val.Addr()
- default:
- return ValueEncoderError{Name: "ProxyEncodeValue", Types: []reflect.Type{tProxy}, Received: val}
- }
-
- fn := val.Convert(tProxy).MethodByName("ProxyBSON")
- returns := fn.Call(nil)
- if !returns[1].IsNil() {
- return returns[1].Interface().(error)
- }
- data := returns[0]
- var encoder ValueEncoder
- var err error
- if data.Elem().IsValid() {
- encoder, err = ec.LookupEncoder(data.Elem().Type())
- } else {
- encoder, err = ec.LookupEncoder(nil)
- }
- if err != nil {
- return err
- }
- return encoder.EncodeValue(ec, vw, data.Elem())
-}
-
-// JavaScriptEncodeValue is the ValueEncoderFunc for the primitive.JavaScript type.
-func (DefaultValueEncoders) JavaScriptEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tJavaScript {
- return ValueEncoderError{Name: "JavaScriptEncodeValue", Types: []reflect.Type{tJavaScript}, Received: val}
- }
-
- return vw.WriteJavascript(val.String())
-}
-
-// SymbolEncodeValue is the ValueEncoderFunc for the primitive.Symbol type.
-func (DefaultValueEncoders) SymbolEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tSymbol {
- return ValueEncoderError{Name: "SymbolEncodeValue", Types: []reflect.Type{tSymbol}, Received: val}
- }
-
- return vw.WriteSymbol(val.String())
-}
-
-// BinaryEncodeValue is the ValueEncoderFunc for Binary.
-func (DefaultValueEncoders) BinaryEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tBinary {
- return ValueEncoderError{Name: "BinaryEncodeValue", Types: []reflect.Type{tBinary}, Received: val}
- }
- b := val.Interface().(primitive.Binary)
-
- return vw.WriteBinaryWithSubtype(b.Data, b.Subtype)
-}
-
-// UndefinedEncodeValue is the ValueEncoderFunc for Undefined.
-func (DefaultValueEncoders) UndefinedEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tUndefined {
- return ValueEncoderError{Name: "UndefinedEncodeValue", Types: []reflect.Type{tUndefined}, Received: val}
- }
-
- return vw.WriteUndefined()
-}
-
-// DateTimeEncodeValue is the ValueEncoderFunc for DateTime.
-func (DefaultValueEncoders) DateTimeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tDateTime {
- return ValueEncoderError{Name: "DateTimeEncodeValue", Types: []reflect.Type{tDateTime}, Received: val}
- }
-
- return vw.WriteDateTime(val.Int())
-}
-
-// NullEncodeValue is the ValueEncoderFunc for Null.
-func (DefaultValueEncoders) NullEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tNull {
- return ValueEncoderError{Name: "NullEncodeValue", Types: []reflect.Type{tNull}, Received: val}
- }
-
- return vw.WriteNull()
-}
-
-// RegexEncodeValue is the ValueEncoderFunc for Regex.
-func (DefaultValueEncoders) RegexEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tRegex {
- return ValueEncoderError{Name: "RegexEncodeValue", Types: []reflect.Type{tRegex}, Received: val}
- }
-
- regex := val.Interface().(primitive.Regex)
-
- return vw.WriteRegex(regex.Pattern, regex.Options)
-}
-
-// DBPointerEncodeValue is the ValueEncoderFunc for DBPointer.
-func (DefaultValueEncoders) DBPointerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tDBPointer {
- return ValueEncoderError{Name: "DBPointerEncodeValue", Types: []reflect.Type{tDBPointer}, Received: val}
- }
-
- dbp := val.Interface().(primitive.DBPointer)
-
- return vw.WriteDBPointer(dbp.DB, dbp.Pointer)
-}
-
-// TimestampEncodeValue is the ValueEncoderFunc for Timestamp.
-func (DefaultValueEncoders) TimestampEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tTimestamp {
- return ValueEncoderError{Name: "TimestampEncodeValue", Types: []reflect.Type{tTimestamp}, Received: val}
- }
-
- ts := val.Interface().(primitive.Timestamp)
-
- return vw.WriteTimestamp(ts.T, ts.I)
-}
-
-// MinKeyEncodeValue is the ValueEncoderFunc for MinKey.
-func (DefaultValueEncoders) MinKeyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tMinKey {
- return ValueEncoderError{Name: "MinKeyEncodeValue", Types: []reflect.Type{tMinKey}, Received: val}
- }
-
- return vw.WriteMinKey()
-}
-
-// MaxKeyEncodeValue is the ValueEncoderFunc for MaxKey.
-func (DefaultValueEncoders) MaxKeyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tMaxKey {
- return ValueEncoderError{Name: "MaxKeyEncodeValue", Types: []reflect.Type{tMaxKey}, Received: val}
- }
-
- return vw.WriteMaxKey()
-}
-
-// CoreDocumentEncodeValue is the ValueEncoderFunc for bsoncore.Document.
-func (DefaultValueEncoders) CoreDocumentEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tCoreDocument {
- return ValueEncoderError{Name: "CoreDocumentEncodeValue", Types: []reflect.Type{tCoreDocument}, Received: val}
- }
-
- cdoc := val.Interface().(bsoncore.Document)
-
- return bsonrw.Copier{}.CopyDocumentFromBytes(vw, cdoc)
-}
-
-// CodeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope.
-func (dve DefaultValueEncoders) CodeWithScopeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tCodeWithScope {
- return ValueEncoderError{Name: "CodeWithScopeEncodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val}
- }
-
- cws := val.Interface().(primitive.CodeWithScope)
-
- dw, err := vw.WriteCodeWithScope(string(cws.Code))
- if err != nil {
- return err
- }
-
- sw := sliceWriterPool.Get().(*bsonrw.SliceWriter)
- defer sliceWriterPool.Put(sw)
- *sw = (*sw)[:0]
-
- scopeVW := bvwPool.Get(sw)
- defer bvwPool.Put(scopeVW)
-
- encoder, err := ec.LookupEncoder(reflect.TypeOf(cws.Scope))
- if err != nil {
- return err
- }
-
- err = encoder.EncodeValue(ec, scopeVW, reflect.ValueOf(cws.Scope))
- if err != nil {
- return err
- }
-
- err = bsonrw.Copier{}.CopyBytesToDocumentWriter(dw, *sw)
- if err != nil {
- return err
- }
- return dw.WriteDocumentEnd()
-}
-
-// isImplementationNil returns if val is a nil pointer and inter is implemented on a concrete type
-func isImplementationNil(val reflect.Value, inter reflect.Type) bool {
- vt := val.Type()
- for vt.Kind() == reflect.Ptr {
- vt = vt.Elem()
- }
- return vt.Implements(inter) && val.Kind() == reflect.Ptr && val.IsNil()
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go
deleted file mode 100644
index c1e20f94..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Package bsoncodec provides a system for encoding values to BSON representations and decoding
-// values from BSON representations. This package considers both binary BSON and ExtendedJSON as
-// BSON representations. The types in this package enable a flexible system for handling this
-// encoding and decoding.
-//
-// The codec system is composed of two parts:
-//
-// 1) ValueEncoders and ValueDecoders that handle encoding and decoding Go values to and from BSON
-// representations.
-//
-// 2) A Registry that holds these ValueEncoders and ValueDecoders and provides methods for
-// retrieving them.
-//
-// ValueEncoders and ValueDecoders
-//
-// The ValueEncoder interface is implemented by types that can encode a provided Go type to BSON.
-// The value to encode is provided as a reflect.Value and a bsonrw.ValueWriter is used within the
-// EncodeValue method to actually create the BSON representation. For convenience, ValueEncoderFunc
-// is provided to allow use of a function with the correct signature as a ValueEncoder. An
-// EncodeContext instance is provided to allow implementations to lookup further ValueEncoders and
-// to provide configuration information.
-//
-// The ValueDecoder interface is the inverse of the ValueEncoder. Implementations should ensure that
-// the value they receive is settable. Similar to ValueEncoderFunc, ValueDecoderFunc is provided to
-// allow the use of a function with the correct signature as a ValueDecoder. A DecodeContext
-// instance is provided and serves similar functionality to the EncodeContext.
-//
-// Registry and RegistryBuilder
-//
-// A Registry is an immutable store for ValueEncoders, ValueDecoders, and a type map. See the Registry type
-// documentation for examples of registering various custom encoders and decoders. A Registry can be constructed using a
-// RegistryBuilder, which handles three main types of codecs:
-//
-// 1. Type encoders/decoders - These can be registered using the RegisterTypeEncoder and RegisterTypeDecoder methods.
-// The registered codec will be invoked when encoding/decoding a value whose type matches the registered type exactly.
-// If the registered type is an interface, the codec will be invoked when encoding or decoding values whose type is the
-// interface, but not for values with concrete types that implement the interface.
-//
-// 2. Hook encoders/decoders - These can be registered using the RegisterHookEncoder and RegisterHookDecoder methods.
-// These methods only accept interface types and the registered codecs will be invoked when encoding or decoding values
-// whose types implement the interface. An example of a hook defined by the driver is bson.Marshaler. The driver will
-// call the MarshalBSON method for any value whose type implements bson.Marshaler, regardless of the value's concrete
-// type.
-//
-// 3. Type map entries - This can be used to associate a BSON type with a Go type. These type associations are used when
-// decoding into a bson.D/bson.M or a struct field of type interface{}. For example, by default, BSON int32 and int64
-// values decode as Go int32 and int64 instances, respectively, when decoding into a bson.D. The following code would
-// change the behavior so these values decode as Go int instances instead:
-//
-// intType := reflect.TypeOf(int(0))
-// registryBuilder.RegisterTypeMapEntry(bsontype.Int32, intType).RegisterTypeMapEntry(bsontype.Int64, intType)
-//
-// 4. Kind encoder/decoders - These can be registered using the RegisterDefaultEncoder and RegisterDefaultDecoder
-// methods. The registered codec will be invoked when encoding or decoding values whose reflect.Kind matches the
-// registered reflect.Kind as long as the value's type doesn't match a registered type or hook encoder/decoder first.
-// These methods should be used to change the behavior for all values for a specific kind.
-//
-// Registry Lookup Procedure
-//
-// When looking up an encoder in a Registry, the precedence rules are as follows:
-//
-// 1. A type encoder registered for the exact type of the value.
-//
-// 2. A hook encoder registered for an interface that is implemented by the value or by a pointer to the value. If the
-// value matches multiple hooks (e.g. the type implements bsoncodec.Marshaler and bsoncodec.ValueMarshaler), the first
-// one registered will be selected. Note that registries constructed using bson.NewRegistryBuilder have driver-defined
-// hooks registered for the bsoncodec.Marshaler, bsoncodec.ValueMarshaler, and bsoncodec.Proxy interfaces, so those
-// will take precedence over any new hooks.
-//
-// 3. A kind encoder registered for the value's kind.
-//
-// If all of these lookups fail to find an encoder, an error of type ErrNoEncoder is returned. The same precedence
-// rules apply for decoders, with the exception that an error of type ErrNoDecoder will be returned if no decoder is
-// found.
-//
-// DefaultValueEncoders and DefaultValueDecoders
-//
-// The DefaultValueEncoders and DefaultValueDecoders types provide a full set of ValueEncoders and
-// ValueDecoders for handling a wide range of Go types, including all of the types within the
-// primitive package. To make registering these codecs easier, a helper method on each type is
-// provided. For the DefaultValueEncoders type the method is called RegisterDefaultEncoders and for
-// the DefaultValueDecoders type the method is called RegisterDefaultDecoders, this method also
-// handles registering type map entries for each BSON type.
-package bsoncodec
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/empty_interface_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/empty_interface_codec.go
deleted file mode 100644
index c215ec38..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/empty_interface_codec.go
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "reflect"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
- "go.mongodb.org/mongo-driver/bson/primitive"
-)
-
-var defaultEmptyInterfaceCodec = NewEmptyInterfaceCodec()
-
-// EmptyInterfaceCodec is the Codec used for interface{} values.
-type EmptyInterfaceCodec struct {
- DecodeBinaryAsSlice bool
-}
-
-var _ ValueCodec = &EmptyInterfaceCodec{}
-
-// NewEmptyInterfaceCodec returns a EmptyInterfaceCodec with options opts.
-func NewEmptyInterfaceCodec(opts ...*bsonoptions.EmptyInterfaceCodecOptions) *EmptyInterfaceCodec {
- interfaceOpt := bsonoptions.MergeEmptyInterfaceCodecOptions(opts...)
-
- codec := EmptyInterfaceCodec{}
- if interfaceOpt.DecodeBinaryAsSlice != nil {
- codec.DecodeBinaryAsSlice = *interfaceOpt.DecodeBinaryAsSlice
- }
- return &codec
-}
-
-// EncodeValue is the ValueEncoderFunc for interface{}.
-func (eic EmptyInterfaceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tEmpty {
- return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val}
- }
-
- if val.IsNil() {
- return vw.WriteNull()
- }
- encoder, err := ec.LookupEncoder(val.Elem().Type())
- if err != nil {
- return err
- }
-
- return encoder.EncodeValue(ec, vw, val.Elem())
-}
-
-func (eic EmptyInterfaceCodec) getEmptyInterfaceDecodeType(dc DecodeContext, valueType bsontype.Type) (reflect.Type, error) {
- isDocument := valueType == bsontype.Type(0) || valueType == bsontype.EmbeddedDocument
- if isDocument && dc.Ancestor != nil {
- // Using ancestor information rather than looking up the type map entry forces consistent decoding.
- // If we're decoding into a bson.D, subdocuments should also be decoded as bson.D, even if a type map entry
- // has been registered.
- return dc.Ancestor, nil
- }
-
- rtype, err := dc.LookupTypeMapEntry(valueType)
- if err == nil {
- return rtype, nil
- }
-
- if isDocument {
- // For documents, fallback to looking up a type map entry for bsontype.Type(0) or bsontype.EmbeddedDocument,
- // depending on the original valueType.
- var lookupType bsontype.Type
- switch valueType {
- case bsontype.Type(0):
- lookupType = bsontype.EmbeddedDocument
- case bsontype.EmbeddedDocument:
- lookupType = bsontype.Type(0)
- }
-
- rtype, err = dc.LookupTypeMapEntry(lookupType)
- if err == nil {
- return rtype, nil
- }
- }
-
- return nil, err
-}
-
-// DecodeValue is the ValueDecoderFunc for interface{}.
-func (eic EmptyInterfaceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tEmpty {
- return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val}
- }
-
- rtype, err := eic.getEmptyInterfaceDecodeType(dc, vr.Type())
- if err != nil {
- switch vr.Type() {
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- default:
- return err
- }
- }
-
- decoder, err := dc.LookupDecoder(rtype)
- if err != nil {
- return err
- }
-
- elem := reflect.New(rtype).Elem()
- err = decoder.DecodeValue(dc, vr, elem)
- if err != nil {
- return err
- }
- if eic.DecodeBinaryAsSlice && rtype == tBinary {
- binElem := elem.Interface().(primitive.Binary)
- if binElem.Subtype == bsontype.BinaryGeneric || binElem.Subtype == bsontype.BinaryBinaryOld {
- elem = reflect.ValueOf(binElem.Data)
- }
- }
-
- val.Set(elem)
- return nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/map_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/map_codec.go
deleted file mode 100644
index 85ae9c6a..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/map_codec.go
+++ /dev/null
@@ -1,206 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "fmt"
- "reflect"
- "strconv"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-var defaultMapCodec = NewMapCodec()
-
-// MapCodec is the Codec used for map values.
-type MapCodec struct {
- DecodeZerosMap bool
- EncodeNilAsEmpty bool
-}
-
-var _ ValueCodec = &MapCodec{}
-
-// NewMapCodec returns a MapCodec with options opts.
-func NewMapCodec(opts ...*bsonoptions.MapCodecOptions) *MapCodec {
- mapOpt := bsonoptions.MergeMapCodecOptions(opts...)
-
- codec := MapCodec{}
- if mapOpt.DecodeZerosMap != nil {
- codec.DecodeZerosMap = *mapOpt.DecodeZerosMap
- }
- if mapOpt.EncodeNilAsEmpty != nil {
- codec.EncodeNilAsEmpty = *mapOpt.EncodeNilAsEmpty
- }
- return &codec
-}
-
-// EncodeValue is the ValueEncoder for map[*]* types.
-func (mc *MapCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Map {
- return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val}
- }
-
- if val.IsNil() && !mc.EncodeNilAsEmpty {
- // If we have a nil map but we can't WriteNull, that means we're probably trying to encode
- // to a TopLevel document. We can't currently tell if this is what actually happened, but if
- // there's a deeper underlying problem, the error will also be returned from WriteDocument,
- // so just continue. The operations on a map reflection value are valid, so we can call
- // MapKeys within mapEncodeValue without a problem.
- err := vw.WriteNull()
- if err == nil {
- return nil
- }
- }
-
- dw, err := vw.WriteDocument()
- if err != nil {
- return err
- }
-
- return mc.mapEncodeValue(ec, dw, val, nil)
-}
-
-// mapEncodeValue handles encoding of the values of a map. The collisionFn returns
-// true if the provided key exists, this is mainly used for inline maps in the
-// struct codec.
-func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error {
-
- elemType := val.Type().Elem()
- encoder, err := ec.LookupEncoder(elemType)
- if err != nil && elemType.Kind() != reflect.Interface {
- return err
- }
-
- keys := val.MapKeys()
- for _, key := range keys {
- keyStr := fmt.Sprint(key)
- if collisionFn != nil && collisionFn(keyStr) {
- return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key)
- }
-
- currEncoder, currVal, lookupErr := defaultValueEncoders.lookupElementEncoder(ec, encoder, val.MapIndex(key))
- if lookupErr != nil && lookupErr != errInvalidValue {
- return lookupErr
- }
-
- vw, err := dw.WriteDocumentElement(keyStr)
- if err != nil {
- return err
- }
-
- if lookupErr == errInvalidValue {
- err = vw.WriteNull()
- if err != nil {
- return err
- }
- continue
- }
-
- if enc, ok := currEncoder.(ValueEncoder); ok {
- err = enc.EncodeValue(ec, vw, currVal)
- if err != nil {
- return err
- }
- continue
- }
- err = encoder.EncodeValue(ec, vw, currVal)
- if err != nil {
- return err
- }
- }
-
- return dw.WriteDocumentEnd()
-}
-
-// DecodeValue is the ValueDecoder for map[string/decimal]* types.
-func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if val.Kind() != reflect.Map || (!val.CanSet() && val.IsNil()) {
- return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val}
- }
-
- switch vrType := vr.Type(); vrType {
- case bsontype.Type(0), bsontype.EmbeddedDocument:
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- default:
- return fmt.Errorf("cannot decode %v into a %s", vrType, val.Type())
- }
-
- dr, err := vr.ReadDocument()
- if err != nil {
- return err
- }
-
- if val.IsNil() {
- val.Set(reflect.MakeMap(val.Type()))
- }
-
- if val.Len() > 0 && mc.DecodeZerosMap {
- clearMap(val)
- }
-
- eType := val.Type().Elem()
- decoder, err := dc.LookupDecoder(eType)
- if err != nil {
- return err
- }
-
- if eType == tEmpty {
- dc.Ancestor = val.Type()
- }
-
- keyType := val.Type().Key()
- keyKind := keyType.Kind()
-
- for {
- key, vr, err := dr.ReadElement()
- if err == bsonrw.ErrEOD {
- break
- }
- if err != nil {
- return err
- }
-
- k := reflect.ValueOf(key)
- if keyType != tString {
- switch keyKind {
- 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:
- parsed, err := strconv.ParseFloat(k.String(), 64)
- if err != nil {
- return fmt.Errorf("Map key is defined to be a decimal type (%v) but got error %v", keyKind, err)
- }
- k = reflect.ValueOf(parsed)
- case reflect.String: // if keyType wraps string
- default:
- return fmt.Errorf("BSON map must have string or decimal keys. Got:%v", val.Type())
- }
-
- k = k.Convert(keyType)
- }
-
- elem := reflect.New(eType).Elem()
- err = decoder.DecodeValue(dc, vr, elem)
- if err != nil {
- return err
- }
-
- val.SetMapIndex(k, elem)
- }
- return nil
-}
-
-func clearMap(m reflect.Value) {
- var none reflect.Value
- for _, k := range m.MapKeys() {
- m.SetMapIndex(k, none)
- }
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/mode.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/mode.go
deleted file mode 100644
index fbd9f0a9..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/mode.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import "fmt"
-
-type mode int
-
-const (
- _ mode = iota
- mTopLevel
- mDocument
- mArray
- mValue
- mElement
- mCodeWithScope
- mSpacer
-)
-
-func (m mode) String() string {
- var str string
-
- switch m {
- case mTopLevel:
- str = "TopLevel"
- case mDocument:
- str = "DocumentMode"
- case mArray:
- str = "ArrayMode"
- case mValue:
- str = "ValueMode"
- case mElement:
- str = "ElementMode"
- case mCodeWithScope:
- str = "CodeWithScopeMode"
- case mSpacer:
- str = "CodeWithScopeSpacerFrame"
- default:
- str = "UnknownMode"
- }
-
- return str
-}
-
-// TransitionError is an error returned when an invalid progressing a
-// ValueReader or ValueWriter state machine occurs.
-type TransitionError struct {
- parent mode
- current mode
- destination mode
-}
-
-func (te TransitionError) Error() string {
- if te.destination == mode(0) {
- return fmt.Sprintf("invalid state transition: cannot read/write value while in %s", te.current)
- }
- if te.parent == mode(0) {
- return fmt.Sprintf("invalid state transition: %s -> %s", te.current, te.destination)
- }
- return fmt.Sprintf("invalid state transition: %s -> %s; parent %s", te.current, te.destination, te.parent)
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go
deleted file mode 100644
index 0d9502f2..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "reflect"
- "sync"
-
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-var defaultPointerCodec = &PointerCodec{
- ecache: make(map[reflect.Type]ValueEncoder),
- dcache: make(map[reflect.Type]ValueDecoder),
-}
-
-var _ ValueEncoder = &PointerCodec{}
-var _ ValueDecoder = &PointerCodec{}
-
-// PointerCodec is the Codec used for pointers.
-type PointerCodec struct {
- ecache map[reflect.Type]ValueEncoder
- dcache map[reflect.Type]ValueDecoder
- l sync.RWMutex
-}
-
-// NewPointerCodec returns a PointerCodec that has been initialized.
-func NewPointerCodec() *PointerCodec {
- return &PointerCodec{
- ecache: make(map[reflect.Type]ValueEncoder),
- dcache: make(map[reflect.Type]ValueDecoder),
- }
-}
-
-// EncodeValue handles encoding a pointer by either encoding it to BSON Null if the pointer is nil
-// or looking up an encoder for the type of value the pointer points to.
-func (pc *PointerCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if val.Kind() != reflect.Ptr {
- if !val.IsValid() {
- return vw.WriteNull()
- }
- return ValueEncoderError{Name: "PointerCodec.EncodeValue", Kinds: []reflect.Kind{reflect.Ptr}, Received: val}
- }
-
- if val.IsNil() {
- return vw.WriteNull()
- }
-
- pc.l.RLock()
- enc, ok := pc.ecache[val.Type()]
- pc.l.RUnlock()
- if ok {
- if enc == nil {
- return ErrNoEncoder{Type: val.Type()}
- }
- return enc.EncodeValue(ec, vw, val.Elem())
- }
-
- enc, err := ec.LookupEncoder(val.Type().Elem())
- pc.l.Lock()
- pc.ecache[val.Type()] = enc
- pc.l.Unlock()
- if err != nil {
- return err
- }
-
- return enc.EncodeValue(ec, vw, val.Elem())
-}
-
-// DecodeValue handles decoding a pointer by looking up a decoder for the type it points to and
-// using that to decode. If the BSON value is Null, this method will set the pointer to nil.
-func (pc *PointerCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Kind() != reflect.Ptr {
- return ValueDecoderError{Name: "PointerCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Ptr}, Received: val}
- }
-
- if vr.Type() == bsontype.Null {
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- }
-
- if val.IsNil() {
- val.Set(reflect.New(val.Type().Elem()))
- }
-
- pc.l.RLock()
- dec, ok := pc.dcache[val.Type()]
- pc.l.RUnlock()
- if ok {
- if dec == nil {
- return ErrNoDecoder{Type: val.Type()}
- }
- return dec.DecodeValue(dc, vr, val.Elem())
- }
-
- dec, err := dc.LookupDecoder(val.Type().Elem())
- pc.l.Lock()
- pc.dcache[val.Type()] = dec
- pc.l.Unlock()
- if err != nil {
- return err
- }
-
- return dec.DecodeValue(dc, vr, val.Elem())
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/proxy.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/proxy.go
deleted file mode 100644
index 4cf2b01a..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/proxy.go
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-// Proxy is an interface implemented by types that cannot themselves be directly encoded. Types
-// that implement this interface with have ProxyBSON called during the encoding process and that
-// value will be encoded in place for the implementer.
-type Proxy interface {
- ProxyBSON() (interface{}, error)
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go
deleted file mode 100644
index 02b63bbe..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go
+++ /dev/null
@@ -1,472 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "errors"
- "fmt"
- "reflect"
- "sync"
-
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-// ErrNilType is returned when nil is passed to either LookupEncoder or LookupDecoder.
-var ErrNilType = errors.New("cannot perform a decoder lookup on ")
-
-// ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder.
-var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder")
-
-// ErrNoEncoder is returned when there wasn't an encoder available for a type.
-type ErrNoEncoder struct {
- Type reflect.Type
-}
-
-func (ene ErrNoEncoder) Error() string {
- if ene.Type == nil {
- return "no encoder found for "
- }
- return "no encoder found for " + ene.Type.String()
-}
-
-// ErrNoDecoder is returned when there wasn't a decoder available for a type.
-type ErrNoDecoder struct {
- Type reflect.Type
-}
-
-func (end ErrNoDecoder) Error() string {
- return "no decoder found for " + end.Type.String()
-}
-
-// ErrNoTypeMapEntry is returned when there wasn't a type available for the provided BSON type.
-type ErrNoTypeMapEntry struct {
- Type bsontype.Type
-}
-
-func (entme ErrNoTypeMapEntry) Error() string {
- return "no type map entry found for " + entme.Type.String()
-}
-
-// ErrNotInterface is returned when the provided type is not an interface.
-var ErrNotInterface = errors.New("The provided type is not an interface")
-
-var defaultRegistry *Registry
-
-func init() {
- defaultRegistry = buildDefaultRegistry()
-}
-
-// A RegistryBuilder is used to build a Registry. This type is not goroutine
-// safe.
-type RegistryBuilder struct {
- typeEncoders map[reflect.Type]ValueEncoder
- interfaceEncoders []interfaceValueEncoder
- kindEncoders map[reflect.Kind]ValueEncoder
-
- typeDecoders map[reflect.Type]ValueDecoder
- interfaceDecoders []interfaceValueDecoder
- kindDecoders map[reflect.Kind]ValueDecoder
-
- typeMap map[bsontype.Type]reflect.Type
-}
-
-// A Registry is used to store and retrieve codecs for types and interfaces. This type is the main
-// typed passed around and Encoders and Decoders are constructed from it.
-type Registry struct {
- typeEncoders map[reflect.Type]ValueEncoder
- typeDecoders map[reflect.Type]ValueDecoder
-
- interfaceEncoders []interfaceValueEncoder
- interfaceDecoders []interfaceValueDecoder
-
- kindEncoders map[reflect.Kind]ValueEncoder
- kindDecoders map[reflect.Kind]ValueDecoder
-
- typeMap map[bsontype.Type]reflect.Type
-
- mu sync.RWMutex
-}
-
-// NewRegistryBuilder creates a new empty RegistryBuilder.
-func NewRegistryBuilder() *RegistryBuilder {
- return &RegistryBuilder{
- typeEncoders: make(map[reflect.Type]ValueEncoder),
- typeDecoders: make(map[reflect.Type]ValueDecoder),
-
- interfaceEncoders: make([]interfaceValueEncoder, 0),
- interfaceDecoders: make([]interfaceValueDecoder, 0),
-
- kindEncoders: make(map[reflect.Kind]ValueEncoder),
- kindDecoders: make(map[reflect.Kind]ValueDecoder),
-
- typeMap: make(map[bsontype.Type]reflect.Type),
- }
-}
-
-func buildDefaultRegistry() *Registry {
- rb := NewRegistryBuilder()
- defaultValueEncoders.RegisterDefaultEncoders(rb)
- defaultValueDecoders.RegisterDefaultDecoders(rb)
- return rb.Build()
-}
-
-// RegisterCodec will register the provided ValueCodec for the provided type.
-func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *RegistryBuilder {
- rb.RegisterTypeEncoder(t, codec)
- rb.RegisterTypeDecoder(t, codec)
- return rb
-}
-
-// RegisterTypeEncoder will register the provided ValueEncoder for the provided type.
-//
-// The type will be used directly, so an encoder can be registered for a type and a different encoder can be registered
-// for a pointer to that type.
-//
-// If the given type is an interface, the encoder will be called when marshalling a type that is that interface. It
-// will not be called when marshalling a non-interface type that implements the interface.
-func (rb *RegistryBuilder) RegisterTypeEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder {
- rb.typeEncoders[t] = enc
- return rb
-}
-
-// RegisterHookEncoder will register an encoder for the provided interface type t. This encoder will be called when
-// marshalling a type if the type implements t or a pointer to the type implements t. If the provided type is not
-// an interface (i.e. t.Kind() != reflect.Interface), this method will panic.
-func (rb *RegistryBuilder) RegisterHookEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder {
- if t.Kind() != reflect.Interface {
- panicStr := fmt.Sprintf("RegisterHookEncoder expects a type with kind reflect.Interface, "+
- "got type %s with kind %s", t, t.Kind())
- panic(panicStr)
- }
-
- for idx, encoder := range rb.interfaceEncoders {
- if encoder.i == t {
- rb.interfaceEncoders[idx].ve = enc
- return rb
- }
- }
-
- rb.interfaceEncoders = append(rb.interfaceEncoders, interfaceValueEncoder{i: t, ve: enc})
- return rb
-}
-
-// RegisterTypeDecoder will register the provided ValueDecoder for the provided type.
-//
-// The type will be used directly, so a decoder can be registered for a type and a different decoder can be registered
-// for a pointer to that type.
-//
-// If the given type is an interface, the decoder will be called when unmarshalling into a type that is that interface.
-// It will not be called when unmarshalling into a non-interface type that implements the interface.
-func (rb *RegistryBuilder) RegisterTypeDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder {
- rb.typeDecoders[t] = dec
- return rb
-}
-
-// RegisterHookDecoder will register an decoder for the provided interface type t. This decoder will be called when
-// unmarshalling into a type if the type implements t or a pointer to the type implements t. If the provided type is not
-// an interface (i.e. t.Kind() != reflect.Interface), this method will panic.
-func (rb *RegistryBuilder) RegisterHookDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder {
- if t.Kind() != reflect.Interface {
- panicStr := fmt.Sprintf("RegisterHookDecoder expects a type with kind reflect.Interface, "+
- "got type %s with kind %s", t, t.Kind())
- panic(panicStr)
- }
-
- for idx, decoder := range rb.interfaceDecoders {
- if decoder.i == t {
- rb.interfaceDecoders[idx].vd = dec
- return rb
- }
- }
-
- rb.interfaceDecoders = append(rb.interfaceDecoders, interfaceValueDecoder{i: t, vd: dec})
- return rb
-}
-
-// RegisterEncoder has been deprecated and will be removed in a future major version release. Use RegisterTypeEncoder
-// or RegisterHookEncoder instead.
-func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder {
- if t == tEmpty {
- rb.typeEncoders[t] = enc
- return rb
- }
- switch t.Kind() {
- case reflect.Interface:
- for idx, ir := range rb.interfaceEncoders {
- if ir.i == t {
- rb.interfaceEncoders[idx].ve = enc
- return rb
- }
- }
-
- rb.interfaceEncoders = append(rb.interfaceEncoders, interfaceValueEncoder{i: t, ve: enc})
- default:
- rb.typeEncoders[t] = enc
- }
- return rb
-}
-
-// RegisterDecoder has been deprecated and will be removed in a future major version release. Use RegisterTypeDecoder
-// or RegisterHookDecoder instead.
-func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder {
- if t == nil {
- rb.typeDecoders[nil] = dec
- return rb
- }
- if t == tEmpty {
- rb.typeDecoders[t] = dec
- return rb
- }
- switch t.Kind() {
- case reflect.Interface:
- for idx, ir := range rb.interfaceDecoders {
- if ir.i == t {
- rb.interfaceDecoders[idx].vd = dec
- return rb
- }
- }
-
- rb.interfaceDecoders = append(rb.interfaceDecoders, interfaceValueDecoder{i: t, vd: dec})
- default:
- rb.typeDecoders[t] = dec
- }
- return rb
-}
-
-// RegisterDefaultEncoder will registr the provided ValueEncoder to the provided
-// kind.
-func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder {
- rb.kindEncoders[kind] = enc
- return rb
-}
-
-// RegisterDefaultDecoder will register the provided ValueDecoder to the
-// provided kind.
-func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder {
- rb.kindDecoders[kind] = dec
- return rb
-}
-
-// RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this
-// mapping is decoding situations where an empty interface is used and a default type needs to be
-// created and decoded into.
-//
-// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON
-// documents, a type map entry for bsontype.EmbeddedDocument should be registered. For example, to force BSON documents
-// to decode to bson.Raw, use the following code:
-// rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.Raw{}))
-func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder {
- rb.typeMap[bt] = rt
- return rb
-}
-
-// Build creates a Registry from the current state of this RegistryBuilder.
-func (rb *RegistryBuilder) Build() *Registry {
- registry := new(Registry)
-
- registry.typeEncoders = make(map[reflect.Type]ValueEncoder)
- for t, enc := range rb.typeEncoders {
- registry.typeEncoders[t] = enc
- }
-
- registry.typeDecoders = make(map[reflect.Type]ValueDecoder)
- for t, dec := range rb.typeDecoders {
- registry.typeDecoders[t] = dec
- }
-
- registry.interfaceEncoders = make([]interfaceValueEncoder, len(rb.interfaceEncoders))
- copy(registry.interfaceEncoders, rb.interfaceEncoders)
-
- registry.interfaceDecoders = make([]interfaceValueDecoder, len(rb.interfaceDecoders))
- copy(registry.interfaceDecoders, rb.interfaceDecoders)
-
- registry.kindEncoders = make(map[reflect.Kind]ValueEncoder)
- for kind, enc := range rb.kindEncoders {
- registry.kindEncoders[kind] = enc
- }
-
- registry.kindDecoders = make(map[reflect.Kind]ValueDecoder)
- for kind, dec := range rb.kindDecoders {
- registry.kindDecoders[kind] = dec
- }
-
- registry.typeMap = make(map[bsontype.Type]reflect.Type)
- for bt, rt := range rb.typeMap {
- registry.typeMap[bt] = rt
- }
-
- return registry
-}
-
-// LookupEncoder inspects the registry for an encoder for the given type. The lookup precendence works as follows:
-//
-// 1. An encoder registered for the exact type. If the given type represents an interface, an encoder registered using
-// RegisterTypeEncoder for the interface will be selected.
-//
-// 2. An encoder registered using RegisterHookEncoder for an interface implemented by the type or by a pointer to the
-// type.
-//
-// 3. An encoder registered for the reflect.Kind of the value.
-//
-// If no encoder is found, an error of type ErrNoEncoder is returned.
-func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error) {
- encodererr := ErrNoEncoder{Type: t}
- r.mu.RLock()
- enc, found := r.lookupTypeEncoder(t)
- r.mu.RUnlock()
- if found {
- if enc == nil {
- return nil, ErrNoEncoder{Type: t}
- }
- return enc, nil
- }
-
- enc, found = r.lookupInterfaceEncoder(t, true)
- if found {
- r.mu.Lock()
- r.typeEncoders[t] = enc
- r.mu.Unlock()
- return enc, nil
- }
-
- if t == nil {
- r.mu.Lock()
- r.typeEncoders[t] = nil
- r.mu.Unlock()
- return nil, encodererr
- }
-
- enc, found = r.kindEncoders[t.Kind()]
- if !found {
- r.mu.Lock()
- r.typeEncoders[t] = nil
- r.mu.Unlock()
- return nil, encodererr
- }
-
- r.mu.Lock()
- r.typeEncoders[t] = enc
- r.mu.Unlock()
- return enc, nil
-}
-
-func (r *Registry) lookupTypeEncoder(t reflect.Type) (ValueEncoder, bool) {
- enc, found := r.typeEncoders[t]
- return enc, found
-}
-
-func (r *Registry) lookupInterfaceEncoder(t reflect.Type, allowAddr bool) (ValueEncoder, bool) {
- if t == nil {
- return nil, false
- }
- for _, ienc := range r.interfaceEncoders {
- if t.Implements(ienc.i) {
- return ienc.ve, true
- }
- if allowAddr && t.Kind() != reflect.Ptr && reflect.PtrTo(t).Implements(ienc.i) {
- // if *t implements an interface, this will catch if t implements an interface further ahead
- // in interfaceEncoders
- defaultEnc, found := r.lookupInterfaceEncoder(t, false)
- if !found {
- defaultEnc, _ = r.kindEncoders[t.Kind()]
- }
- return newCondAddrEncoder(ienc.ve, defaultEnc), true
- }
- }
- return nil, false
-}
-
-// LookupDecoder inspects the registry for an decoder for the given type. The lookup precendence works as follows:
-//
-// 1. A decoder registered for the exact type. If the given type represents an interface, a decoder registered using
-// RegisterTypeDecoder for the interface will be selected.
-//
-// 2. A decoder registered using RegisterHookDecoder for an interface implemented by the type or by a pointer to the
-// type.
-//
-// 3. A decoder registered for the reflect.Kind of the value.
-//
-// If no decoder is found, an error of type ErrNoDecoder is returned.
-func (r *Registry) LookupDecoder(t reflect.Type) (ValueDecoder, error) {
- if t == nil {
- return nil, ErrNilType
- }
- decodererr := ErrNoDecoder{Type: t}
- r.mu.RLock()
- dec, found := r.lookupTypeDecoder(t)
- r.mu.RUnlock()
- if found {
- if dec == nil {
- return nil, ErrNoDecoder{Type: t}
- }
- return dec, nil
- }
-
- dec, found = r.lookupInterfaceDecoder(t, true)
- if found {
- r.mu.Lock()
- r.typeDecoders[t] = dec
- r.mu.Unlock()
- return dec, nil
- }
-
- dec, found = r.kindDecoders[t.Kind()]
- if !found {
- r.mu.Lock()
- r.typeDecoders[t] = nil
- r.mu.Unlock()
- return nil, decodererr
- }
-
- r.mu.Lock()
- r.typeDecoders[t] = dec
- r.mu.Unlock()
- return dec, nil
-}
-
-func (r *Registry) lookupTypeDecoder(t reflect.Type) (ValueDecoder, bool) {
- dec, found := r.typeDecoders[t]
- return dec, found
-}
-
-func (r *Registry) lookupInterfaceDecoder(t reflect.Type, allowAddr bool) (ValueDecoder, bool) {
- for _, idec := range r.interfaceDecoders {
- if t.Implements(idec.i) {
- return idec.vd, true
- }
- if allowAddr && t.Kind() != reflect.Ptr && reflect.PtrTo(t).Implements(idec.i) {
- // if *t implements an interface, this will catch if t implements an interface further ahead
- // in interfaceDecoders
- defaultDec, found := r.lookupInterfaceDecoder(t, false)
- if !found {
- defaultDec, _ = r.kindDecoders[t.Kind()]
- }
- return newCondAddrDecoder(idec.vd, defaultDec), true
- }
- }
- return nil, false
-}
-
-// LookupTypeMapEntry inspects the registry's type map for a Go type for the corresponding BSON
-// type. If no type is found, ErrNoTypeMapEntry is returned.
-func (r *Registry) LookupTypeMapEntry(bt bsontype.Type) (reflect.Type, error) {
- t, ok := r.typeMap[bt]
- if !ok || t == nil {
- return nil, ErrNoTypeMapEntry{Type: bt}
- }
- return t, nil
-}
-
-type interfaceValueEncoder struct {
- i reflect.Type
- ve ValueEncoder
-}
-
-type interfaceValueDecoder struct {
- i reflect.Type
- vd ValueDecoder
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/slice_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/slice_codec.go
deleted file mode 100644
index f0282eb2..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/slice_codec.go
+++ /dev/null
@@ -1,196 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "fmt"
- "reflect"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
- "go.mongodb.org/mongo-driver/bson/primitive"
-)
-
-var defaultSliceCodec = NewSliceCodec()
-
-// SliceCodec is the Codec used for slice values.
-type SliceCodec struct {
- EncodeNilAsEmpty bool
-}
-
-var _ ValueCodec = &MapCodec{}
-
-// NewSliceCodec returns a MapCodec with options opts.
-func NewSliceCodec(opts ...*bsonoptions.SliceCodecOptions) *SliceCodec {
- sliceOpt := bsonoptions.MergeSliceCodecOptions(opts...)
-
- codec := SliceCodec{}
- if sliceOpt.EncodeNilAsEmpty != nil {
- codec.EncodeNilAsEmpty = *sliceOpt.EncodeNilAsEmpty
- }
- return &codec
-}
-
-// EncodeValue is the ValueEncoder for slice types.
-func (sc SliceCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Slice {
- return ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val}
- }
-
- if val.IsNil() && !sc.EncodeNilAsEmpty {
- return vw.WriteNull()
- }
-
- // If we have a []byte we want to treat it as a binary instead of as an array.
- if val.Type().Elem() == tByte {
- var byteSlice []byte
- for idx := 0; idx < val.Len(); idx++ {
- byteSlice = append(byteSlice, val.Index(idx).Interface().(byte))
- }
- return vw.WriteBinary(byteSlice)
- }
-
- // If we have a []primitive.E we want to treat it as a document instead of as an array.
- if val.Type().ConvertibleTo(tD) {
- d := val.Convert(tD).Interface().(primitive.D)
-
- dw, err := vw.WriteDocument()
- if err != nil {
- return err
- }
-
- for _, e := range d {
- err = encodeElement(ec, dw, e)
- if err != nil {
- return err
- }
- }
-
- return dw.WriteDocumentEnd()
- }
-
- aw, err := vw.WriteArray()
- if err != nil {
- return err
- }
-
- elemType := val.Type().Elem()
- encoder, err := ec.LookupEncoder(elemType)
- if err != nil && elemType.Kind() != reflect.Interface {
- return err
- }
-
- for idx := 0; idx < val.Len(); idx++ {
- currEncoder, currVal, lookupErr := defaultValueEncoders.lookupElementEncoder(ec, encoder, val.Index(idx))
- if lookupErr != nil && lookupErr != errInvalidValue {
- return lookupErr
- }
-
- vw, err := aw.WriteArrayElement()
- if err != nil {
- return err
- }
-
- if lookupErr == errInvalidValue {
- err = vw.WriteNull()
- if err != nil {
- return err
- }
- continue
- }
-
- err = currEncoder.EncodeValue(ec, vw, currVal)
- if err != nil {
- return err
- }
- }
- return aw.WriteArrayEnd()
-}
-
-// DecodeValue is the ValueDecoder for slice types.
-func (sc *SliceCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Kind() != reflect.Slice {
- return ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val}
- }
-
- switch vrType := vr.Type(); vrType {
- case bsontype.Array:
- case bsontype.Null:
- val.Set(reflect.Zero(val.Type()))
- return vr.ReadNull()
- case bsontype.Type(0), bsontype.EmbeddedDocument:
- if val.Type().Elem() != tE {
- return fmt.Errorf("cannot decode document into %s", val.Type())
- }
- case bsontype.Binary:
- if val.Type().Elem() != tByte {
- return fmt.Errorf("SliceDecodeValue can only decode a binary into a byte array, got %v", vrType)
- }
- data, subtype, err := vr.ReadBinary()
- if err != nil {
- return err
- }
- if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld {
- return fmt.Errorf("SliceDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype)
- }
-
- if val.IsNil() {
- val.Set(reflect.MakeSlice(val.Type(), 0, len(data)))
- }
-
- val.SetLen(0)
- for _, elem := range data {
- val.Set(reflect.Append(val, reflect.ValueOf(elem)))
- }
- return nil
- case bsontype.String:
- if val.Type().Elem() != tByte {
- return fmt.Errorf("SliceDecodeValue can only decode a string into a byte array, got %v", vrType)
- }
- str, err := vr.ReadString()
- if err != nil {
- return err
- }
- byteStr := []byte(str)
-
- if val.IsNil() {
- val.Set(reflect.MakeSlice(val.Type(), 0, len(byteStr)))
- }
-
- val.SetLen(0)
- for _, elem := range byteStr {
- val.Set(reflect.Append(val, reflect.ValueOf(elem)))
- }
- return nil
- default:
- return fmt.Errorf("cannot decode %v into a slice", vrType)
- }
-
- var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error)
- switch val.Type().Elem() {
- case tE:
- dc.Ancestor = val.Type()
- elemsFunc = defaultValueDecoders.decodeD
- default:
- elemsFunc = defaultValueDecoders.decodeDefault
- }
-
- elems, err := elemsFunc(dc, vr, val)
- if err != nil {
- return err
- }
-
- if val.IsNil() {
- val.Set(reflect.MakeSlice(val.Type(), 0, len(elems)))
- }
-
- val.SetLen(0)
- val.Set(reflect.Append(val, elems...))
-
- return nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/string_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/string_codec.go
deleted file mode 100644
index c672cf5a..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/string_codec.go
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "fmt"
- "reflect"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-var defaultStringCodec = NewStringCodec()
-
-// StringCodec is the Codec used for struct values.
-type StringCodec struct {
- DecodeObjectIDAsHex bool
-}
-
-var _ ValueCodec = &StringCodec{}
-
-// NewStringCodec returns a StringCodec with options opts.
-func NewStringCodec(opts ...*bsonoptions.StringCodecOptions) *StringCodec {
- stringOpt := bsonoptions.MergeStringCodecOptions(opts...)
- return &StringCodec{*stringOpt.DecodeObjectIDAsHex}
-}
-
-// EncodeValue is the ValueEncoder for string types.
-func (sc *StringCodec) EncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if val.Kind() != reflect.String {
- return ValueEncoderError{
- Name: "StringEncodeValue",
- Kinds: []reflect.Kind{reflect.String},
- Received: val,
- }
- }
-
- return vw.WriteString(val.String())
-}
-
-// DecodeValue is the ValueDecoder for string types.
-func (sc *StringCodec) DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Kind() != reflect.String {
- return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val}
- }
- var str string
- var err error
- switch vr.Type() {
- case bsontype.String:
- str, err = vr.ReadString()
- if err != nil {
- return err
- }
- case bsontype.ObjectID:
- oid, err := vr.ReadObjectID()
- if err != nil {
- return err
- }
- if sc.DecodeObjectIDAsHex {
- str = oid.Hex()
- } else {
- byteArray := [12]byte(oid)
- str = string(byteArray[:])
- }
- case bsontype.Symbol:
- str, err = vr.ReadSymbol()
- if err != nil {
- return err
- }
- case bsontype.Binary:
- data, subtype, err := vr.ReadBinary()
- if err != nil {
- return err
- }
- if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld {
- return fmt.Errorf("SliceDecodeValue can only be used to decode subtype 0x00 or 0x02 for %s, got %v", bsontype.Binary, subtype)
- }
- str = string(data)
- case bsontype.Null:
- if err = vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into a string type", vr.Type())
- }
-
- val.SetString(str)
- return nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go
deleted file mode 100644
index 777cdfb6..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go
+++ /dev/null
@@ -1,536 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "errors"
- "fmt"
- "reflect"
- "strings"
- "sync"
- "time"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-var defaultStructCodec = &StructCodec{
- cache: make(map[reflect.Type]*structDescription),
- parser: DefaultStructTagParser,
-}
-
-// Zeroer allows custom struct types to implement a report of zero
-// state. All struct types that don't implement Zeroer or where IsZero
-// returns false are considered to be not zero.
-type Zeroer interface {
- IsZero() bool
-}
-
-// StructCodec is the Codec used for struct values.
-type StructCodec struct {
- cache map[reflect.Type]*structDescription
- l sync.RWMutex
- parser StructTagParser
- DecodeZeroStruct bool
- DecodeDeepZeroInline bool
- EncodeOmitDefaultStruct bool
- AllowUnexportedFields bool
-}
-
-var _ ValueEncoder = &StructCodec{}
-var _ ValueDecoder = &StructCodec{}
-
-// NewStructCodec returns a StructCodec that uses p for struct tag parsing.
-func NewStructCodec(p StructTagParser, opts ...*bsonoptions.StructCodecOptions) (*StructCodec, error) {
- if p == nil {
- return nil, errors.New("a StructTagParser must be provided to NewStructCodec")
- }
-
- structOpt := bsonoptions.MergeStructCodecOptions(opts...)
-
- codec := &StructCodec{
- cache: make(map[reflect.Type]*structDescription),
- parser: p,
- }
-
- if structOpt.DecodeZeroStruct != nil {
- codec.DecodeZeroStruct = *structOpt.DecodeZeroStruct
- }
- if structOpt.DecodeDeepZeroInline != nil {
- codec.DecodeDeepZeroInline = *structOpt.DecodeDeepZeroInline
- }
- if structOpt.EncodeOmitDefaultStruct != nil {
- codec.EncodeOmitDefaultStruct = *structOpt.EncodeOmitDefaultStruct
- }
- if structOpt.AllowUnexportedFields != nil {
- codec.AllowUnexportedFields = *structOpt.AllowUnexportedFields
- }
-
- return codec, nil
-}
-
-// EncodeValue handles encoding generic struct types.
-func (sc *StructCodec) EncodeValue(r EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Kind() != reflect.Struct {
- return ValueEncoderError{Name: "StructCodec.EncodeValue", Kinds: []reflect.Kind{reflect.Struct}, Received: val}
- }
-
- sd, err := sc.describeStruct(r.Registry, val.Type())
- if err != nil {
- return err
- }
-
- dw, err := vw.WriteDocument()
- if err != nil {
- return err
- }
- var rv reflect.Value
- for _, desc := range sd.fl {
- if desc.inline == nil {
- rv = val.Field(desc.idx)
- } else {
- rv, err = fieldByIndexErr(val, desc.inline)
- if err != nil {
- continue
- }
- }
-
- desc.encoder, rv, err = defaultValueEncoders.lookupElementEncoder(r, desc.encoder, rv)
-
- if err != nil && err != errInvalidValue {
- return err
- }
-
- if err == errInvalidValue {
- if desc.omitEmpty {
- continue
- }
- vw2, err := dw.WriteDocumentElement(desc.name)
- if err != nil {
- return err
- }
- err = vw2.WriteNull()
- if err != nil {
- return err
- }
- continue
- }
-
- if desc.encoder == nil {
- return ErrNoEncoder{Type: rv.Type()}
- }
-
- encoder := desc.encoder
-
- var isZero bool
- rvInterface := rv.Interface()
- if cz, ok := encoder.(CodecZeroer); ok {
- isZero = cz.IsTypeZero(rvInterface)
- } else if rv.Kind() == reflect.Interface {
- // sc.isZero will not treat an interface rv as an interface, so we need to check for the zero interface separately.
- isZero = rv.IsNil()
- } else {
- isZero = sc.isZero(rvInterface)
- }
- if desc.omitEmpty && isZero {
- continue
- }
-
- vw2, err := dw.WriteDocumentElement(desc.name)
- if err != nil {
- return err
- }
-
- ectx := EncodeContext{Registry: r.Registry, MinSize: desc.minSize}
- err = encoder.EncodeValue(ectx, vw2, rv)
- if err != nil {
- return err
- }
- }
-
- if sd.inlineMap >= 0 {
- rv := val.Field(sd.inlineMap)
- collisionFn := func(key string) bool {
- _, exists := sd.fm[key]
- return exists
- }
-
- return defaultMapCodec.mapEncodeValue(r, dw, rv, collisionFn)
- }
-
- return dw.WriteDocumentEnd()
-}
-
-// DecodeValue implements the Codec interface.
-// By default, map types in val will not be cleared. If a map has existing key/value pairs, it will be extended with the new ones from vr.
-// For slices, the decoder will set the length of the slice to zero and append all elements. The underlying array will not be cleared.
-func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Kind() != reflect.Struct {
- return ValueDecoderError{Name: "StructCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Struct}, Received: val}
- }
-
- switch vrType := vr.Type(); vrType {
- case bsontype.Type(0), bsontype.EmbeddedDocument:
- case bsontype.Null:
- if err := vr.ReadNull(); err != nil {
- return err
- }
-
- val.Set(reflect.Zero(val.Type()))
- return nil
- default:
- return fmt.Errorf("cannot decode %v into a %s", vrType, val.Type())
- }
-
- sd, err := sc.describeStruct(r.Registry, val.Type())
- if err != nil {
- return err
- }
-
- if sc.DecodeZeroStruct {
- val.Set(reflect.Zero(val.Type()))
- }
- if sc.DecodeDeepZeroInline && sd.inline {
- val.Set(deepZero(val.Type()))
- }
-
- var decoder ValueDecoder
- var inlineMap reflect.Value
- if sd.inlineMap >= 0 {
- inlineMap = val.Field(sd.inlineMap)
- decoder, err = r.LookupDecoder(inlineMap.Type().Elem())
- if err != nil {
- return err
- }
- }
-
- dr, err := vr.ReadDocument()
- if err != nil {
- return err
- }
-
- for {
- name, vr, err := dr.ReadElement()
- if err == bsonrw.ErrEOD {
- break
- }
- if err != nil {
- return err
- }
-
- fd, exists := sd.fm[name]
- if !exists {
- // if the original name isn't found in the struct description, try again with the name in lowercase
- // this could match if a BSON tag isn't specified because by default, describeStruct lowercases all field
- // names
- fd, exists = sd.fm[strings.ToLower(name)]
- }
-
- if !exists {
- if sd.inlineMap < 0 {
- // The encoding/json package requires a flag to return on error for non-existent fields.
- // This functionality seems appropriate for the struct codec.
- err = vr.Skip()
- if err != nil {
- return err
- }
- continue
- }
-
- if inlineMap.IsNil() {
- inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
- }
-
- elem := reflect.New(inlineMap.Type().Elem()).Elem()
- r.Ancestor = inlineMap.Type()
- err = decoder.DecodeValue(r, vr, elem)
- if err != nil {
- return err
- }
- inlineMap.SetMapIndex(reflect.ValueOf(name), elem)
- continue
- }
-
- var field reflect.Value
- if fd.inline == nil {
- field = val.Field(fd.idx)
- } else {
- field, err = getInlineField(val, fd.inline)
- if err != nil {
- return err
- }
- }
-
- if !field.CanSet() { // Being settable is a super set of being addressable.
- return fmt.Errorf("cannot decode element '%s' into field %v; it is not settable", name, field)
- }
- if field.Kind() == reflect.Ptr && field.IsNil() {
- field.Set(reflect.New(field.Type().Elem()))
- }
- field = field.Addr()
-
- dctx := DecodeContext{Registry: r.Registry, Truncate: fd.truncate || r.Truncate}
- if fd.decoder == nil {
- return ErrNoDecoder{Type: field.Elem().Type()}
- }
-
- if decoder, ok := fd.decoder.(ValueDecoder); ok {
- err = decoder.DecodeValue(dctx, vr, field.Elem())
- if err != nil {
- return err
- }
- continue
- }
- err = fd.decoder.DecodeValue(dctx, vr, field)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (sc *StructCodec) isZero(i interface{}) bool {
- v := reflect.ValueOf(i)
-
- // check the value validity
- if !v.IsValid() {
- return true
- }
-
- if z, ok := v.Interface().(Zeroer); ok && (v.Kind() != reflect.Ptr || !v.IsNil()) {
- return z.IsZero()
- }
-
- switch v.Kind() {
- case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
- return v.Len() == 0
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.Interface, reflect.Ptr:
- return v.IsNil()
- case reflect.Struct:
- if sc.EncodeOmitDefaultStruct {
- vt := v.Type()
- if vt == tTime {
- return v.Interface().(time.Time).IsZero()
- }
- for i := 0; i < v.NumField(); i++ {
- if vt.Field(i).PkgPath != "" && !vt.Field(i).Anonymous {
- continue // Private field
- }
- fld := v.Field(i)
- if !sc.isZero(fld.Interface()) {
- return false
- }
- }
- return true
- }
- }
-
- return false
-}
-
-type structDescription struct {
- fm map[string]fieldDescription
- fl []fieldDescription
- inlineMap int
- inline bool
-}
-
-type fieldDescription struct {
- name string
- idx int
- omitEmpty bool
- minSize bool
- truncate bool
- inline []int
- encoder ValueEncoder
- decoder ValueDecoder
-}
-
-func (sc *StructCodec) describeStruct(r *Registry, t reflect.Type) (*structDescription, error) {
- // We need to analyze the struct, including getting the tags, collecting
- // information about inlining, and create a map of the field name to the field.
- sc.l.RLock()
- ds, exists := sc.cache[t]
- sc.l.RUnlock()
- if exists {
- return ds, nil
- }
-
- numFields := t.NumField()
- sd := &structDescription{
- fm: make(map[string]fieldDescription, numFields),
- fl: make([]fieldDescription, 0, numFields),
- inlineMap: -1,
- }
-
- for i := 0; i < numFields; i++ {
- sf := t.Field(i)
- if sf.PkgPath != "" && (!sc.AllowUnexportedFields || !sf.Anonymous) {
- // field is private or unexported fields aren't allowed, ignore
- continue
- }
-
- sfType := sf.Type
- encoder, err := r.LookupEncoder(sfType)
- if err != nil {
- encoder = nil
- }
- decoder, err := r.LookupDecoder(sfType)
- if err != nil {
- decoder = nil
- }
-
- description := fieldDescription{idx: i, encoder: encoder, decoder: decoder}
-
- stags, err := sc.parser.ParseStructTags(sf)
- if err != nil {
- return nil, err
- }
- if stags.Skip {
- continue
- }
- description.name = stags.Name
- description.omitEmpty = stags.OmitEmpty
- description.minSize = stags.MinSize
- description.truncate = stags.Truncate
-
- if stags.Inline {
- sd.inline = true
- switch sfType.Kind() {
- case reflect.Map:
- if sd.inlineMap >= 0 {
- return nil, errors.New("(struct " + t.String() + ") multiple inline maps")
- }
- if sfType.Key() != tString {
- return nil, errors.New("(struct " + t.String() + ") inline map must have a string keys")
- }
- sd.inlineMap = description.idx
- case reflect.Ptr:
- sfType = sfType.Elem()
- if sfType.Kind() != reflect.Struct {
- return nil, fmt.Errorf("(struct %s) inline fields must be a struct, a struct pointer, or a map", t.String())
- }
- fallthrough
- case reflect.Struct:
- inlinesf, err := sc.describeStruct(r, sfType)
- if err != nil {
- return nil, err
- }
- for _, fd := range inlinesf.fl {
- if _, exists := sd.fm[fd.name]; exists {
- return nil, fmt.Errorf("(struct %s) duplicated key %s", t.String(), fd.name)
- }
- if fd.inline == nil {
- fd.inline = []int{i, fd.idx}
- } else {
- fd.inline = append([]int{i}, fd.inline...)
- }
- sd.fm[fd.name] = fd
- sd.fl = append(sd.fl, fd)
- }
- default:
- return nil, fmt.Errorf("(struct %s) inline fields must be a struct, a struct pointer, or a map", t.String())
- }
- continue
- }
-
- if _, exists := sd.fm[description.name]; exists {
- return nil, fmt.Errorf("struct %s) duplicated key %s", t.String(), description.name)
- }
-
- sd.fm[description.name] = description
- sd.fl = append(sd.fl, description)
- }
-
- sc.l.Lock()
- sc.cache[t] = sd
- sc.l.Unlock()
-
- return sd, nil
-}
-
-func fieldByIndexErr(v reflect.Value, index []int) (result reflect.Value, err error) {
- defer func() {
- if recovered := recover(); recovered != nil {
- switch r := recovered.(type) {
- case string:
- err = fmt.Errorf("%s", r)
- case error:
- err = r
- }
- }
- }()
-
- result = v.FieldByIndex(index)
- return
-}
-
-func getInlineField(val reflect.Value, index []int) (reflect.Value, error) {
- field, err := fieldByIndexErr(val, index)
- if err == nil {
- return field, nil
- }
-
- // if parent of this element doesn't exist, fix its parent
- inlineParent := index[:len(index)-1]
- var fParent reflect.Value
- if fParent, err = fieldByIndexErr(val, inlineParent); err != nil {
- fParent, err = getInlineField(val, inlineParent)
- if err != nil {
- return fParent, err
- }
- }
- fParent.Set(reflect.New(fParent.Type().Elem()))
-
- return fieldByIndexErr(val, index)
-}
-
-// DeepZero returns recursive zero object
-func deepZero(st reflect.Type) (result reflect.Value) {
- result = reflect.Indirect(reflect.New(st))
-
- if result.Kind() == reflect.Struct {
- for i := 0; i < result.NumField(); i++ {
- if f := result.Field(i); f.Kind() == reflect.Ptr {
- if f.CanInterface() {
- if ft := reflect.TypeOf(f.Interface()); ft.Elem().Kind() == reflect.Struct {
- result.Field(i).Set(recursivePointerTo(deepZero(ft.Elem())))
- }
- }
- }
- }
- }
-
- return
-}
-
-// recursivePointerTo calls reflect.New(v.Type) but recursively for its fields inside
-func recursivePointerTo(v reflect.Value) reflect.Value {
- v = reflect.Indirect(v)
- result := reflect.New(v.Type())
- if v.Kind() == reflect.Struct {
- for i := 0; i < v.NumField(); i++ {
- if f := v.Field(i); f.Kind() == reflect.Ptr {
- if f.Elem().Kind() == reflect.Struct {
- result.Elem().Field(i).Set(recursivePointerTo(f))
- }
- }
- }
- }
-
- return result
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go
deleted file mode 100644
index 69d0ae4d..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "reflect"
- "strings"
-)
-
-// StructTagParser returns the struct tags for a given struct field.
-type StructTagParser interface {
- ParseStructTags(reflect.StructField) (StructTags, error)
-}
-
-// StructTagParserFunc is an adapter that allows a generic function to be used
-// as a StructTagParser.
-type StructTagParserFunc func(reflect.StructField) (StructTags, error)
-
-// ParseStructTags implements the StructTagParser interface.
-func (stpf StructTagParserFunc) ParseStructTags(sf reflect.StructField) (StructTags, error) {
- return stpf(sf)
-}
-
-// StructTags represents the struct tag fields that the StructCodec uses during
-// the encoding and decoding process.
-//
-// In the case of a struct, the lowercased field name is used as the key for each exported
-// field but this behavior may be changed using a struct tag. The tag may also contain flags to
-// adjust the marshalling behavior for the field.
-//
-// The properties are defined below:
-//
-// OmitEmpty Only include the field if it's not set to the zero value for the type or to
-// empty slices or maps.
-//
-// MinSize Marshal an integer of a type larger than 32 bits value as an int32, if that's
-// feasible while preserving the numeric value.
-//
-// Truncate When unmarshaling a BSON double, it is permitted to lose precision to fit within
-// a float32.
-//
-// Inline Inline the field, which must be a struct or a map, causing all of its fields
-// or keys to be processed as if they were part of the outer struct. For maps,
-// keys must not conflict with the bson keys of other struct fields.
-//
-// Skip This struct field should be skipped. This is usually denoted by parsing a "-"
-// for the name.
-//
-// TODO(skriptble): Add tags for undefined as nil and for null as nil.
-type StructTags struct {
- Name string
- OmitEmpty bool
- MinSize bool
- Truncate bool
- Inline bool
- Skip bool
-}
-
-// DefaultStructTagParser is the StructTagParser used by the StructCodec by default.
-// It will handle the bson struct tag. See the documentation for StructTags to see
-// what each of the returned fields means.
-//
-// If there is no name in the struct tag fields, the struct field name is lowercased.
-// The tag formats accepted are:
-//
-// "[][,[,]]"
-//
-// `(...) bson:"[][,[,]]" (...)`
-//
-// An example:
-//
-// type T struct {
-// A bool
-// B int "myb"
-// C string "myc,omitempty"
-// D string `bson:",omitempty" json:"jsonkey"`
-// E int64 ",minsize"
-// F int64 "myf,omitempty,minsize"
-// }
-//
-// A struct tag either consisting entirely of '-' or with a bson key with a
-// value consisting entirely of '-' will return a StructTags with Skip true and
-// the remaining fields will be their default values.
-var DefaultStructTagParser StructTagParserFunc = func(sf reflect.StructField) (StructTags, error) {
- key := strings.ToLower(sf.Name)
- tag, ok := sf.Tag.Lookup("bson")
- if !ok && !strings.Contains(string(sf.Tag), ":") && len(sf.Tag) > 0 {
- tag = string(sf.Tag)
- }
- var st StructTags
- if tag == "-" {
- st.Skip = true
- return st, nil
- }
-
- for idx, str := range strings.Split(tag, ",") {
- if idx == 0 && str != "" {
- key = str
- }
- switch str {
- case "omitempty":
- st.OmitEmpty = true
- case "minsize":
- st.MinSize = true
- case "truncate":
- st.Truncate = true
- case "inline":
- st.Inline = true
- }
- }
-
- st.Name = key
-
- return st, nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/time_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/time_codec.go
deleted file mode 100644
index 6f1b724d..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/time_codec.go
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "fmt"
- "reflect"
- "time"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-const (
- timeFormatString = "2006-01-02T15:04:05.999Z07:00"
-)
-
-var defaultTimeCodec = NewTimeCodec()
-
-// TimeCodec is the Codec used for time.Time values.
-type TimeCodec struct {
- UseLocalTimeZone bool
-}
-
-var _ ValueCodec = &TimeCodec{}
-
-// NewTimeCodec returns a TimeCodec with options opts.
-func NewTimeCodec(opts ...*bsonoptions.TimeCodecOptions) *TimeCodec {
- timeOpt := bsonoptions.MergeTimeCodecOptions(opts...)
-
- codec := TimeCodec{}
- if timeOpt.UseLocalTimeZone != nil {
- codec.UseLocalTimeZone = *timeOpt.UseLocalTimeZone
- }
- return &codec
-}
-
-// DecodeValue is the ValueDecoderFunc for time.Time.
-func (tc *TimeCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() || val.Type() != tTime {
- return ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: val}
- }
-
- var timeVal time.Time
- switch vrType := vr.Type(); vrType {
- case bsontype.DateTime:
- dt, err := vr.ReadDateTime()
- if err != nil {
- return err
- }
- timeVal = time.Unix(dt/1000, dt%1000*1000000)
- case bsontype.String:
- // assume strings are in the isoTimeFormat
- timeStr, err := vr.ReadString()
- if err != nil {
- return err
- }
- timeVal, err = time.Parse(timeFormatString, timeStr)
- if err != nil {
- return err
- }
- case bsontype.Int64:
- i64, err := vr.ReadInt64()
- if err != nil {
- return err
- }
- timeVal = time.Unix(i64/1000, i64%1000*1000000)
- case bsontype.Timestamp:
- t, _, err := vr.ReadTimestamp()
- if err != nil {
- return err
- }
- timeVal = time.Unix(int64(t), 0)
- case bsontype.Null:
- if err := vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into a time.Time", vrType)
- }
-
- if !tc.UseLocalTimeZone {
- timeVal = timeVal.UTC()
- }
- val.Set(reflect.ValueOf(timeVal))
- return nil
-}
-
-// EncodeValue is the ValueEncoderFunc for time.TIme.
-func (tc *TimeCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- if !val.IsValid() || val.Type() != tTime {
- return ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: val}
- }
- tt := val.Interface().(time.Time)
- return vw.WriteDateTime(tt.Unix()*1000 + int64(tt.Nanosecond()/1e6))
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go
deleted file mode 100644
index bbb6bb9c..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "encoding/json"
- "net/url"
- "reflect"
- "time"
-
- "go.mongodb.org/mongo-driver/bson/primitive"
- "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
-)
-
-var ptBool = reflect.TypeOf((*bool)(nil))
-var ptInt8 = reflect.TypeOf((*int8)(nil))
-var ptInt16 = reflect.TypeOf((*int16)(nil))
-var ptInt32 = reflect.TypeOf((*int32)(nil))
-var ptInt64 = reflect.TypeOf((*int64)(nil))
-var ptInt = reflect.TypeOf((*int)(nil))
-var ptUint8 = reflect.TypeOf((*uint8)(nil))
-var ptUint16 = reflect.TypeOf((*uint16)(nil))
-var ptUint32 = reflect.TypeOf((*uint32)(nil))
-var ptUint64 = reflect.TypeOf((*uint64)(nil))
-var ptUint = reflect.TypeOf((*uint)(nil))
-var ptFloat32 = reflect.TypeOf((*float32)(nil))
-var ptFloat64 = reflect.TypeOf((*float64)(nil))
-var ptString = reflect.TypeOf((*string)(nil))
-
-var tBool = reflect.TypeOf(false)
-var tFloat32 = reflect.TypeOf(float32(0))
-var tFloat64 = reflect.TypeOf(float64(0))
-var tInt = reflect.TypeOf(int(0))
-var tInt8 = reflect.TypeOf(int8(0))
-var tInt16 = reflect.TypeOf(int16(0))
-var tInt32 = reflect.TypeOf(int32(0))
-var tInt64 = reflect.TypeOf(int64(0))
-var tString = reflect.TypeOf("")
-var tTime = reflect.TypeOf(time.Time{})
-var tUint = reflect.TypeOf(uint(0))
-var tUint8 = reflect.TypeOf(uint8(0))
-var tUint16 = reflect.TypeOf(uint16(0))
-var tUint32 = reflect.TypeOf(uint32(0))
-var tUint64 = reflect.TypeOf(uint64(0))
-
-var tEmpty = reflect.TypeOf((*interface{})(nil)).Elem()
-var tByteSlice = reflect.TypeOf([]byte(nil))
-var tByte = reflect.TypeOf(byte(0x00))
-var tURL = reflect.TypeOf(url.URL{})
-var tJSONNumber = reflect.TypeOf(json.Number(""))
-
-var tValueMarshaler = reflect.TypeOf((*ValueMarshaler)(nil)).Elem()
-var tValueUnmarshaler = reflect.TypeOf((*ValueUnmarshaler)(nil)).Elem()
-var tMarshaler = reflect.TypeOf((*Marshaler)(nil)).Elem()
-var tUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
-var tProxy = reflect.TypeOf((*Proxy)(nil)).Elem()
-
-var tBinary = reflect.TypeOf(primitive.Binary{})
-var tUndefined = reflect.TypeOf(primitive.Undefined{})
-var tOID = reflect.TypeOf(primitive.ObjectID{})
-var tDateTime = reflect.TypeOf(primitive.DateTime(0))
-var tNull = reflect.TypeOf(primitive.Null{})
-var tRegex = reflect.TypeOf(primitive.Regex{})
-var tCodeWithScope = reflect.TypeOf(primitive.CodeWithScope{})
-var tDBPointer = reflect.TypeOf(primitive.DBPointer{})
-var tJavaScript = reflect.TypeOf(primitive.JavaScript(""))
-var tSymbol = reflect.TypeOf(primitive.Symbol(""))
-var tTimestamp = reflect.TypeOf(primitive.Timestamp{})
-var tDecimal = reflect.TypeOf(primitive.Decimal128{})
-var tMinKey = reflect.TypeOf(primitive.MinKey{})
-var tMaxKey = reflect.TypeOf(primitive.MaxKey{})
-var tD = reflect.TypeOf(primitive.D{})
-var tM = reflect.TypeOf(primitive.M{})
-var tA = reflect.TypeOf(primitive.A{})
-var tE = reflect.TypeOf(primitive.E{})
-
-var tCoreDocument = reflect.TypeOf(bsoncore.Document{})
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/uint_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/uint_codec.go
deleted file mode 100644
index e0df0583..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/uint_codec.go
+++ /dev/null
@@ -1,150 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsoncodec
-
-import (
- "errors"
- "fmt"
- "math"
- "reflect"
-
- "go.mongodb.org/mongo-driver/bson/bsonoptions"
- "go.mongodb.org/mongo-driver/bson/bsonrw"
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-var defaultUIntCodec = NewUIntCodec()
-
-// UIntCodec is the Codec used for uint values.
-type UIntCodec struct {
- EncodeToMinSize bool
-}
-
-var _ ValueCodec = &UIntCodec{}
-
-// NewUIntCodec returns a UIntCodec with options opts.
-func NewUIntCodec(opts ...*bsonoptions.UIntCodecOptions) *UIntCodec {
- uintOpt := bsonoptions.MergeUIntCodecOptions(opts...)
-
- codec := UIntCodec{}
- if uintOpt.EncodeToMinSize != nil {
- codec.EncodeToMinSize = *uintOpt.EncodeToMinSize
- }
- return &codec
-}
-
-// EncodeValue is the ValueEncoder for uint types.
-func (uic *UIntCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
- switch val.Kind() {
- case reflect.Uint8, reflect.Uint16:
- return vw.WriteInt32(int32(val.Uint()))
- case reflect.Uint, reflect.Uint32, reflect.Uint64:
- u64 := val.Uint()
-
- // If ec.MinSize or if encodeToMinSize is true for a non-uint64 value we should write val as an int32
- useMinSize := ec.MinSize || (uic.EncodeToMinSize && val.Kind() != reflect.Uint64)
-
- if u64 <= math.MaxInt32 && useMinSize {
- return vw.WriteInt32(int32(u64))
- }
- if u64 > math.MaxInt64 {
- return fmt.Errorf("%d overflows int64", u64)
- }
- return vw.WriteInt64(int64(u64))
- }
-
- return ValueEncoderError{
- Name: "UintEncodeValue",
- Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint},
- Received: val,
- }
-}
-
-// DecodeValue is the ValueDecoder for uint types.
-func (uic *UIntCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
- if !val.CanSet() {
- return ValueDecoderError{
- Name: "UintDecodeValue",
- Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint},
- Received: val,
- }
- }
-
- var i64 int64
- var err error
- switch vrType := vr.Type(); vrType {
- case bsontype.Int32:
- i32, err := vr.ReadInt32()
- if err != nil {
- return err
- }
- i64 = int64(i32)
- case bsontype.Int64:
- i64, err = vr.ReadInt64()
- if err != nil {
- return err
- }
- case bsontype.Double:
- f64, err := vr.ReadDouble()
- if err != nil {
- return err
- }
- if !dc.Truncate && math.Floor(f64) != f64 {
- return errors.New("UintDecodeValue can only truncate float64 to an integer type when truncation is enabled")
- }
- if f64 > float64(math.MaxInt64) {
- return fmt.Errorf("%g overflows int64", f64)
- }
- i64 = int64(f64)
- case bsontype.Boolean:
- b, err := vr.ReadBoolean()
- if err != nil {
- return err
- }
- if b {
- i64 = 1
- }
- case bsontype.Null:
- if err = vr.ReadNull(); err != nil {
- return err
- }
- default:
- return fmt.Errorf("cannot decode %v into an integer type", vrType)
- }
-
- switch val.Kind() {
- case reflect.Uint8:
- if i64 < 0 || i64 > math.MaxUint8 {
- return fmt.Errorf("%d overflows uint8", i64)
- }
- case reflect.Uint16:
- if i64 < 0 || i64 > math.MaxUint16 {
- return fmt.Errorf("%d overflows uint16", i64)
- }
- case reflect.Uint32:
- if i64 < 0 || i64 > math.MaxUint32 {
- return fmt.Errorf("%d overflows uint32", i64)
- }
- case reflect.Uint64:
- if i64 < 0 {
- return fmt.Errorf("%d overflows uint64", i64)
- }
- case reflect.Uint:
- if i64 < 0 || int64(uint(i64)) != i64 { // Can we fit this inside of an uint
- return fmt.Errorf("%d overflows uint", i64)
- }
- default:
- return ValueDecoderError{
- Name: "UintDecodeValue",
- Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint},
- Received: val,
- }
- }
-
- val.SetUint(uint64(i64))
- return nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/byte_slice_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/byte_slice_codec_options.go
deleted file mode 100644
index b1256a4d..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/byte_slice_codec_options.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-// ByteSliceCodecOptions represents all possible options for byte slice encoding and decoding.
-type ByteSliceCodecOptions struct {
- EncodeNilAsEmpty *bool // Specifies if a nil byte slice should encode as an empty binary instead of null. Defaults to false.
-}
-
-// ByteSliceCodec creates a new *ByteSliceCodecOptions
-func ByteSliceCodec() *ByteSliceCodecOptions {
- return &ByteSliceCodecOptions{}
-}
-
-// SetEncodeNilAsEmpty specifies if a nil byte slice should encode as an empty binary instead of null. Defaults to false.
-func (bs *ByteSliceCodecOptions) SetEncodeNilAsEmpty(b bool) *ByteSliceCodecOptions {
- bs.EncodeNilAsEmpty = &b
- return bs
-}
-
-// MergeByteSliceCodecOptions combines the given *ByteSliceCodecOptions into a single *ByteSliceCodecOptions in a last one wins fashion.
-func MergeByteSliceCodecOptions(opts ...*ByteSliceCodecOptions) *ByteSliceCodecOptions {
- bs := ByteSliceCodec()
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- if opt.EncodeNilAsEmpty != nil {
- bs.EncodeNilAsEmpty = opt.EncodeNilAsEmpty
- }
- }
-
- return bs
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/empty_interface_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/empty_interface_codec_options.go
deleted file mode 100644
index 6caaa000..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/empty_interface_codec_options.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-// EmptyInterfaceCodecOptions represents all possible options for interface{} encoding and decoding.
-type EmptyInterfaceCodecOptions struct {
- DecodeBinaryAsSlice *bool // Specifies if Old and Generic type binarys should default to []slice instead of primitive.Binary. Defaults to false.
-}
-
-// EmptyInterfaceCodec creates a new *EmptyInterfaceCodecOptions
-func EmptyInterfaceCodec() *EmptyInterfaceCodecOptions {
- return &EmptyInterfaceCodecOptions{}
-}
-
-// SetDecodeBinaryAsSlice specifies if Old and Generic type binarys should default to []slice instead of primitive.Binary. Defaults to false.
-func (e *EmptyInterfaceCodecOptions) SetDecodeBinaryAsSlice(b bool) *EmptyInterfaceCodecOptions {
- e.DecodeBinaryAsSlice = &b
- return e
-}
-
-// MergeEmptyInterfaceCodecOptions combines the given *EmptyInterfaceCodecOptions into a single *EmptyInterfaceCodecOptions in a last one wins fashion.
-func MergeEmptyInterfaceCodecOptions(opts ...*EmptyInterfaceCodecOptions) *EmptyInterfaceCodecOptions {
- e := EmptyInterfaceCodec()
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- if opt.DecodeBinaryAsSlice != nil {
- e.DecodeBinaryAsSlice = opt.DecodeBinaryAsSlice
- }
- }
-
- return e
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/map_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/map_codec_options.go
deleted file mode 100644
index 1ac3e200..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/map_codec_options.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-// MapCodecOptions represents all possible options for map encoding and decoding.
-type MapCodecOptions struct {
- DecodeZerosMap *bool // Specifies if the map should be zeroed before decoding into it. Defaults to false.
- EncodeNilAsEmpty *bool // Specifies if a nil map should encode as an empty document instead of null. Defaults to false.
-}
-
-// MapCodec creates a new *MapCodecOptions
-func MapCodec() *MapCodecOptions {
- return &MapCodecOptions{}
-}
-
-// SetDecodeZerosMap specifies if the map should be zeroed before decoding into it. Defaults to false.
-func (t *MapCodecOptions) SetDecodeZerosMap(b bool) *MapCodecOptions {
- t.DecodeZerosMap = &b
- return t
-}
-
-// SetEncodeNilAsEmpty specifies if a nil map should encode as an empty document instead of null. Defaults to false.
-func (t *MapCodecOptions) SetEncodeNilAsEmpty(b bool) *MapCodecOptions {
- t.EncodeNilAsEmpty = &b
- return t
-}
-
-// MergeMapCodecOptions combines the given *MapCodecOptions into a single *MapCodecOptions in a last one wins fashion.
-func MergeMapCodecOptions(opts ...*MapCodecOptions) *MapCodecOptions {
- s := MapCodec()
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- if opt.DecodeZerosMap != nil {
- s.DecodeZerosMap = opt.DecodeZerosMap
- }
- if opt.EncodeNilAsEmpty != nil {
- s.EncodeNilAsEmpty = opt.EncodeNilAsEmpty
- }
- }
-
- return s
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/slice_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/slice_codec_options.go
deleted file mode 100644
index ef965e4b..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/slice_codec_options.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-// SliceCodecOptions represents all possible options for slice encoding and decoding.
-type SliceCodecOptions struct {
- EncodeNilAsEmpty *bool // Specifies if a nil slice should encode as an empty array instead of null. Defaults to false.
-}
-
-// SliceCodec creates a new *SliceCodecOptions
-func SliceCodec() *SliceCodecOptions {
- return &SliceCodecOptions{}
-}
-
-// SetEncodeNilAsEmpty specifies if a nil slice should encode as an empty array instead of null. Defaults to false.
-func (s *SliceCodecOptions) SetEncodeNilAsEmpty(b bool) *SliceCodecOptions {
- s.EncodeNilAsEmpty = &b
- return s
-}
-
-// MergeSliceCodecOptions combines the given *SliceCodecOptions into a single *SliceCodecOptions in a last one wins fashion.
-func MergeSliceCodecOptions(opts ...*SliceCodecOptions) *SliceCodecOptions {
- s := SliceCodec()
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- if opt.EncodeNilAsEmpty != nil {
- s.EncodeNilAsEmpty = opt.EncodeNilAsEmpty
- }
- }
-
- return s
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/string_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/string_codec_options.go
deleted file mode 100644
index 65964f42..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/string_codec_options.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-var defaultDecodeOIDAsHex = true
-
-// StringCodecOptions represents all possible options for string encoding and decoding.
-type StringCodecOptions struct {
- DecodeObjectIDAsHex *bool // Specifies if we should decode ObjectID as the hex value. Defaults to true.
-}
-
-// StringCodec creates a new *StringCodecOptions
-func StringCodec() *StringCodecOptions {
- return &StringCodecOptions{}
-}
-
-// SetDecodeObjectIDAsHex specifies if object IDs should be decoded as their hex representation. If false, a string made
-// from the raw object ID bytes will be used. Defaults to true.
-func (t *StringCodecOptions) SetDecodeObjectIDAsHex(b bool) *StringCodecOptions {
- t.DecodeObjectIDAsHex = &b
- return t
-}
-
-// MergeStringCodecOptions combines the given *StringCodecOptions into a single *StringCodecOptions in a last one wins fashion.
-func MergeStringCodecOptions(opts ...*StringCodecOptions) *StringCodecOptions {
- s := &StringCodecOptions{&defaultDecodeOIDAsHex}
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- if opt.DecodeObjectIDAsHex != nil {
- s.DecodeObjectIDAsHex = opt.DecodeObjectIDAsHex
- }
- }
-
- return s
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/struct_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/struct_codec_options.go
deleted file mode 100644
index ad32c7c3..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/struct_codec_options.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-// StructCodecOptions represents all possible options for struct encoding and decoding.
-type StructCodecOptions struct {
- DecodeZeroStruct *bool // Specifies if structs should be zeroed before decoding into them. Defaults to false.
- DecodeDeepZeroInline *bool // Specifies if structs should be recursively zeroed when a inline value is decoded. Defaults to false.
- EncodeOmitDefaultStruct *bool // Specifies if default structs should be considered empty by omitempty. Defaults to false.
- AllowUnexportedFields *bool // Specifies if unexported fields should be marshaled/unmarshaled. Defaults to false.
-}
-
-// StructCodec creates a new *StructCodecOptions
-func StructCodec() *StructCodecOptions {
- return &StructCodecOptions{}
-}
-
-// SetDecodeZeroStruct specifies if structs should be zeroed before decoding into them. Defaults to false.
-func (t *StructCodecOptions) SetDecodeZeroStruct(b bool) *StructCodecOptions {
- t.DecodeZeroStruct = &b
- return t
-}
-
-// SetDecodeDeepZeroInline specifies if structs should be zeroed before decoding into them. Defaults to false.
-func (t *StructCodecOptions) SetDecodeDeepZeroInline(b bool) *StructCodecOptions {
- t.DecodeDeepZeroInline = &b
- return t
-}
-
-// SetEncodeOmitDefaultStruct specifies if default structs should be considered empty by omitempty. A default struct has all
-// its values set to their default value. Defaults to false.
-func (t *StructCodecOptions) SetEncodeOmitDefaultStruct(b bool) *StructCodecOptions {
- t.EncodeOmitDefaultStruct = &b
- return t
-}
-
-// SetAllowUnexportedFields specifies if unexported fields should be marshaled/unmarshaled. Defaults to false.
-func (t *StructCodecOptions) SetAllowUnexportedFields(b bool) *StructCodecOptions {
- t.AllowUnexportedFields = &b
- return t
-}
-
-// MergeStructCodecOptions combines the given *StructCodecOptions into a single *StructCodecOptions in a last one wins fashion.
-func MergeStructCodecOptions(opts ...*StructCodecOptions) *StructCodecOptions {
- s := StructCodec()
- for _, opt := range opts {
- if opt == nil {
- continue
- }
-
- if opt.DecodeZeroStruct != nil {
- s.DecodeZeroStruct = opt.DecodeZeroStruct
- }
- if opt.DecodeDeepZeroInline != nil {
- s.DecodeDeepZeroInline = opt.DecodeDeepZeroInline
- }
- if opt.EncodeOmitDefaultStruct != nil {
- s.EncodeOmitDefaultStruct = opt.EncodeOmitDefaultStruct
- }
- if opt.AllowUnexportedFields != nil {
- s.AllowUnexportedFields = opt.AllowUnexportedFields
- }
- }
-
- return s
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/time_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/time_codec_options.go
deleted file mode 100644
index 13496d12..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/time_codec_options.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-// TimeCodecOptions represents all possible options for time.Time encoding and decoding.
-type TimeCodecOptions struct {
- UseLocalTimeZone *bool // Specifies if we should decode into the local time zone. Defaults to false.
-}
-
-// TimeCodec creates a new *TimeCodecOptions
-func TimeCodec() *TimeCodecOptions {
- return &TimeCodecOptions{}
-}
-
-// SetUseLocalTimeZone specifies if we should decode into the local time zone. Defaults to false.
-func (t *TimeCodecOptions) SetUseLocalTimeZone(b bool) *TimeCodecOptions {
- t.UseLocalTimeZone = &b
- return t
-}
-
-// MergeTimeCodecOptions combines the given *TimeCodecOptions into a single *TimeCodecOptions in a last one wins fashion.
-func MergeTimeCodecOptions(opts ...*TimeCodecOptions) *TimeCodecOptions {
- t := TimeCodec()
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- if opt.UseLocalTimeZone != nil {
- t.UseLocalTimeZone = opt.UseLocalTimeZone
- }
- }
-
- return t
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/uint_codec_options.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/uint_codec_options.go
deleted file mode 100644
index e08b7f19..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/uint_codec_options.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonoptions
-
-// UIntCodecOptions represents all possible options for uint encoding and decoding.
-type UIntCodecOptions struct {
- EncodeToMinSize *bool // Specifies if all uints except uint64 should be decoded to minimum size bsontype. Defaults to false.
-}
-
-// UIntCodec creates a new *UIntCodecOptions
-func UIntCodec() *UIntCodecOptions {
- return &UIntCodecOptions{}
-}
-
-// SetEncodeToMinSize specifies if all uints except uint64 should be decoded to minimum size bsontype. Defaults to false.
-func (u *UIntCodecOptions) SetEncodeToMinSize(b bool) *UIntCodecOptions {
- u.EncodeToMinSize = &b
- return u
-}
-
-// MergeUIntCodecOptions combines the given *UIntCodecOptions into a single *UIntCodecOptions in a last one wins fashion.
-func MergeUIntCodecOptions(opts ...*UIntCodecOptions) *UIntCodecOptions {
- u := UIntCodec()
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- if opt.EncodeToMinSize != nil {
- u.EncodeToMinSize = opt.EncodeToMinSize
- }
- }
-
- return u
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/copier.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/copier.go
deleted file mode 100644
index 02e3a7e3..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/copier.go
+++ /dev/null
@@ -1,389 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonrw
-
-import (
- "fmt"
- "io"
-
- "go.mongodb.org/mongo-driver/bson/bsontype"
- "go.mongodb.org/mongo-driver/bson/primitive"
- "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
-)
-
-// Copier is a type that allows copying between ValueReaders, ValueWriters, and
-// []byte values.
-type Copier struct{}
-
-// NewCopier creates a new copier with the given registry. If a nil registry is provided
-// a default registry is used.
-func NewCopier() Copier {
- return Copier{}
-}
-
-// CopyDocument handles copying a document from src to dst.
-func CopyDocument(dst ValueWriter, src ValueReader) error {
- return Copier{}.CopyDocument(dst, src)
-}
-
-// CopyDocument handles copying one document from the src to the dst.
-func (c Copier) CopyDocument(dst ValueWriter, src ValueReader) error {
- dr, err := src.ReadDocument()
- if err != nil {
- return err
- }
-
- dw, err := dst.WriteDocument()
- if err != nil {
- return err
- }
-
- return c.copyDocumentCore(dw, dr)
-}
-
-// CopyDocumentFromBytes copies the values from a BSON document represented as a
-// []byte to a ValueWriter.
-func (c Copier) CopyDocumentFromBytes(dst ValueWriter, src []byte) error {
- dw, err := dst.WriteDocument()
- if err != nil {
- return err
- }
-
- err = c.CopyBytesToDocumentWriter(dw, src)
- if err != nil {
- return err
- }
-
- return dw.WriteDocumentEnd()
-}
-
-// CopyBytesToDocumentWriter copies the values from a BSON document represented as a []byte to a
-// DocumentWriter.
-func (c Copier) CopyBytesToDocumentWriter(dst DocumentWriter, src []byte) error {
- // TODO(skriptble): Create errors types here. Anything thats a tag should be a property.
- length, rem, ok := bsoncore.ReadLength(src)
- if !ok {
- return fmt.Errorf("couldn't read length from src, not enough bytes. length=%d", len(src))
- }
- if len(src) < int(length) {
- return fmt.Errorf("length read exceeds number of bytes available. length=%d bytes=%d", len(src), length)
- }
- rem = rem[:length-4]
-
- var t bsontype.Type
- var key string
- var val bsoncore.Value
- for {
- t, rem, ok = bsoncore.ReadType(rem)
- if !ok {
- return io.EOF
- }
- if t == bsontype.Type(0) {
- if len(rem) != 0 {
- return fmt.Errorf("document end byte found before end of document. remaining bytes=%v", rem)
- }
- break
- }
-
- key, rem, ok = bsoncore.ReadKey(rem)
- if !ok {
- return fmt.Errorf("invalid key found. remaining bytes=%v", rem)
- }
- dvw, err := dst.WriteDocumentElement(key)
- if err != nil {
- return err
- }
- val, rem, ok = bsoncore.ReadValue(rem, t)
- if !ok {
- return fmt.Errorf("not enough bytes available to read type. bytes=%d type=%s", len(rem), t)
- }
- err = c.CopyValueFromBytes(dvw, t, val.Data)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// CopyDocumentToBytes copies an entire document from the ValueReader and
-// returns it as bytes.
-func (c Copier) CopyDocumentToBytes(src ValueReader) ([]byte, error) {
- return c.AppendDocumentBytes(nil, src)
-}
-
-// AppendDocumentBytes functions the same as CopyDocumentToBytes, but will
-// append the result to dst.
-func (c Copier) AppendDocumentBytes(dst []byte, src ValueReader) ([]byte, error) {
- if br, ok := src.(BytesReader); ok {
- _, dst, err := br.ReadValueBytes(dst)
- return dst, err
- }
-
- vw := vwPool.Get().(*valueWriter)
- defer vwPool.Put(vw)
-
- vw.reset(dst)
-
- err := c.CopyDocument(vw, src)
- dst = vw.buf
- return dst, err
-}
-
-// CopyValueFromBytes will write the value represtend by t and src to dst.
-func (c Copier) CopyValueFromBytes(dst ValueWriter, t bsontype.Type, src []byte) error {
- if wvb, ok := dst.(BytesWriter); ok {
- return wvb.WriteValueBytes(t, src)
- }
-
- vr := vrPool.Get().(*valueReader)
- defer vrPool.Put(vr)
-
- vr.reset(src)
- vr.pushElement(t)
-
- return c.CopyValue(dst, vr)
-}
-
-// CopyValueToBytes copies a value from src and returns it as a bsontype.Type and a
-// []byte.
-func (c Copier) CopyValueToBytes(src ValueReader) (bsontype.Type, []byte, error) {
- return c.AppendValueBytes(nil, src)
-}
-
-// AppendValueBytes functions the same as CopyValueToBytes, but will append the
-// result to dst.
-func (c Copier) AppendValueBytes(dst []byte, src ValueReader) (bsontype.Type, []byte, error) {
- if br, ok := src.(BytesReader); ok {
- return br.ReadValueBytes(dst)
- }
-
- vw := vwPool.Get().(*valueWriter)
- defer vwPool.Put(vw)
-
- start := len(dst)
-
- vw.reset(dst)
- vw.push(mElement)
-
- err := c.CopyValue(vw, src)
- if err != nil {
- return 0, dst, err
- }
-
- return bsontype.Type(vw.buf[start]), vw.buf[start+2:], nil
-}
-
-// CopyValue will copy a single value from src to dst.
-func (c Copier) CopyValue(dst ValueWriter, src ValueReader) error {
- var err error
- switch src.Type() {
- case bsontype.Double:
- var f64 float64
- f64, err = src.ReadDouble()
- if err != nil {
- break
- }
- err = dst.WriteDouble(f64)
- case bsontype.String:
- var str string
- str, err = src.ReadString()
- if err != nil {
- return err
- }
- err = dst.WriteString(str)
- case bsontype.EmbeddedDocument:
- err = c.CopyDocument(dst, src)
- case bsontype.Array:
- err = c.copyArray(dst, src)
- case bsontype.Binary:
- var data []byte
- var subtype byte
- data, subtype, err = src.ReadBinary()
- if err != nil {
- break
- }
- err = dst.WriteBinaryWithSubtype(data, subtype)
- case bsontype.Undefined:
- err = src.ReadUndefined()
- if err != nil {
- break
- }
- err = dst.WriteUndefined()
- case bsontype.ObjectID:
- var oid primitive.ObjectID
- oid, err = src.ReadObjectID()
- if err != nil {
- break
- }
- err = dst.WriteObjectID(oid)
- case bsontype.Boolean:
- var b bool
- b, err = src.ReadBoolean()
- if err != nil {
- break
- }
- err = dst.WriteBoolean(b)
- case bsontype.DateTime:
- var dt int64
- dt, err = src.ReadDateTime()
- if err != nil {
- break
- }
- err = dst.WriteDateTime(dt)
- case bsontype.Null:
- err = src.ReadNull()
- if err != nil {
- break
- }
- err = dst.WriteNull()
- case bsontype.Regex:
- var pattern, options string
- pattern, options, err = src.ReadRegex()
- if err != nil {
- break
- }
- err = dst.WriteRegex(pattern, options)
- case bsontype.DBPointer:
- var ns string
- var pointer primitive.ObjectID
- ns, pointer, err = src.ReadDBPointer()
- if err != nil {
- break
- }
- err = dst.WriteDBPointer(ns, pointer)
- case bsontype.JavaScript:
- var js string
- js, err = src.ReadJavascript()
- if err != nil {
- break
- }
- err = dst.WriteJavascript(js)
- case bsontype.Symbol:
- var symbol string
- symbol, err = src.ReadSymbol()
- if err != nil {
- break
- }
- err = dst.WriteSymbol(symbol)
- case bsontype.CodeWithScope:
- var code string
- var srcScope DocumentReader
- code, srcScope, err = src.ReadCodeWithScope()
- if err != nil {
- break
- }
-
- var dstScope DocumentWriter
- dstScope, err = dst.WriteCodeWithScope(code)
- if err != nil {
- break
- }
- err = c.copyDocumentCore(dstScope, srcScope)
- case bsontype.Int32:
- var i32 int32
- i32, err = src.ReadInt32()
- if err != nil {
- break
- }
- err = dst.WriteInt32(i32)
- case bsontype.Timestamp:
- var t, i uint32
- t, i, err = src.ReadTimestamp()
- if err != nil {
- break
- }
- err = dst.WriteTimestamp(t, i)
- case bsontype.Int64:
- var i64 int64
- i64, err = src.ReadInt64()
- if err != nil {
- break
- }
- err = dst.WriteInt64(i64)
- case bsontype.Decimal128:
- var d128 primitive.Decimal128
- d128, err = src.ReadDecimal128()
- if err != nil {
- break
- }
- err = dst.WriteDecimal128(d128)
- case bsontype.MinKey:
- err = src.ReadMinKey()
- if err != nil {
- break
- }
- err = dst.WriteMinKey()
- case bsontype.MaxKey:
- err = src.ReadMaxKey()
- if err != nil {
- break
- }
- err = dst.WriteMaxKey()
- default:
- err = fmt.Errorf("Cannot copy unknown BSON type %s", src.Type())
- }
-
- return err
-}
-
-func (c Copier) copyArray(dst ValueWriter, src ValueReader) error {
- ar, err := src.ReadArray()
- if err != nil {
- return err
- }
-
- aw, err := dst.WriteArray()
- if err != nil {
- return err
- }
-
- for {
- vr, err := ar.ReadValue()
- if err == ErrEOA {
- break
- }
- if err != nil {
- return err
- }
-
- vw, err := aw.WriteArrayElement()
- if err != nil {
- return err
- }
-
- err = c.CopyValue(vw, vr)
- if err != nil {
- return err
- }
- }
-
- return aw.WriteArrayEnd()
-}
-
-func (c Copier) copyDocumentCore(dw DocumentWriter, dr DocumentReader) error {
- for {
- key, vr, err := dr.ReadElement()
- if err == ErrEOD {
- break
- }
- if err != nil {
- return err
- }
-
- vw, err := dw.WriteDocumentElement(key)
- if err != nil {
- return err
- }
-
- err = c.CopyValue(vw, vr)
- if err != nil {
- return err
- }
- }
-
- return dw.WriteDocumentEnd()
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/doc.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/doc.go
deleted file mode 100644
index 750b0d2a..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/doc.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-// Package bsonrw contains abstractions for reading and writing
-// BSON and BSON like types from sources.
-package bsonrw // import "go.mongodb.org/mongo-driver/bson/bsonrw"
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_parser.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_parser.go
deleted file mode 100644
index 3ff17c19..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_parser.go
+++ /dev/null
@@ -1,738 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonrw
-
-import (
- "errors"
- "fmt"
- "io"
-
- "go.mongodb.org/mongo-driver/bson/bsontype"
-)
-
-const maxNestingDepth = 200
-
-// ErrInvalidJSON indicates the JSON input is invalid
-var ErrInvalidJSON = errors.New("invalid JSON input")
-
-type jsonParseState byte
-
-const (
- jpsStartState jsonParseState = iota
- jpsSawBeginObject
- jpsSawEndObject
- jpsSawBeginArray
- jpsSawEndArray
- jpsSawColon
- jpsSawComma
- jpsSawKey
- jpsSawValue
- jpsDoneState
- jpsInvalidState
-)
-
-type jsonParseMode byte
-
-const (
- jpmInvalidMode jsonParseMode = iota
- jpmObjectMode
- jpmArrayMode
-)
-
-type extJSONValue struct {
- t bsontype.Type
- v interface{}
-}
-
-type extJSONObject struct {
- keys []string
- values []*extJSONValue
-}
-
-type extJSONParser struct {
- js *jsonScanner
- s jsonParseState
- m []jsonParseMode
- k string
- v *extJSONValue
-
- err error
- canonical bool
- depth int
- maxDepth int
-
- emptyObject bool
-}
-
-// newExtJSONParser returns a new extended JSON parser, ready to to begin
-// parsing from the first character of the argued json input. It will not
-// perform any read-ahead and will therefore not report any errors about
-// malformed JSON at this point.
-func newExtJSONParser(r io.Reader, canonical bool) *extJSONParser {
- return &extJSONParser{
- js: &jsonScanner{r: r},
- s: jpsStartState,
- m: []jsonParseMode{},
- canonical: canonical,
- maxDepth: maxNestingDepth,
- }
-}
-
-// peekType examines the next value and returns its BSON Type
-func (ejp *extJSONParser) peekType() (bsontype.Type, error) {
- var t bsontype.Type
- var err error
- initialState := ejp.s
-
- ejp.advanceState()
- switch ejp.s {
- case jpsSawValue:
- t = ejp.v.t
- case jpsSawBeginArray:
- t = bsontype.Array
- case jpsInvalidState:
- err = ejp.err
- case jpsSawComma:
- // in array mode, seeing a comma means we need to progress again to actually observe a type
- if ejp.peekMode() == jpmArrayMode {
- return ejp.peekType()
- }
- case jpsSawEndArray:
- // this would only be a valid state if we were in array mode, so return end-of-array error
- err = ErrEOA
- case jpsSawBeginObject:
- // peek key to determine type
- ejp.advanceState()
- switch ejp.s {
- case jpsSawEndObject: // empty embedded document
- t = bsontype.EmbeddedDocument
- ejp.emptyObject = true
- case jpsInvalidState:
- err = ejp.err
- case jpsSawKey:
- if initialState == jpsStartState {
- return bsontype.EmbeddedDocument, nil
- }
- t = wrapperKeyBSONType(ejp.k)
-
- switch t {
- case bsontype.JavaScript:
- // just saw $code, need to check for $scope at same level
- _, err = ejp.readValue(bsontype.JavaScript)
- if err != nil {
- break
- }
-
- switch ejp.s {
- case jpsSawEndObject: // type is TypeJavaScript
- case jpsSawComma:
- ejp.advanceState()
-
- if ejp.s == jpsSawKey && ejp.k == "$scope" {
- t = bsontype.CodeWithScope
- } else {
- err = fmt.Errorf("invalid extended JSON: unexpected key %s in CodeWithScope object", ejp.k)
- }
- case jpsInvalidState:
- err = ejp.err
- default:
- err = ErrInvalidJSON
- }
- case bsontype.CodeWithScope:
- err = errors.New("invalid extended JSON: code with $scope must contain $code before $scope")
- }
- }
- }
-
- return t, err
-}
-
-// readKey parses the next key and its type and returns them
-func (ejp *extJSONParser) readKey() (string, bsontype.Type, error) {
- if ejp.emptyObject {
- ejp.emptyObject = false
- return "", 0, ErrEOD
- }
-
- // advance to key (or return with error)
- switch ejp.s {
- case jpsStartState:
- ejp.advanceState()
- if ejp.s == jpsSawBeginObject {
- ejp.advanceState()
- }
- case jpsSawBeginObject:
- ejp.advanceState()
- case jpsSawValue, jpsSawEndObject, jpsSawEndArray:
- ejp.advanceState()
- switch ejp.s {
- case jpsSawBeginObject, jpsSawComma:
- ejp.advanceState()
- case jpsSawEndObject:
- return "", 0, ErrEOD
- case jpsDoneState:
- return "", 0, io.EOF
- case jpsInvalidState:
- return "", 0, ejp.err
- default:
- return "", 0, ErrInvalidJSON
- }
- case jpsSawKey: // do nothing (key was peeked before)
- default:
- return "", 0, invalidRequestError("key")
- }
-
- // read key
- var key string
-
- switch ejp.s {
- case jpsSawKey:
- key = ejp.k
- case jpsSawEndObject:
- return "", 0, ErrEOD
- case jpsInvalidState:
- return "", 0, ejp.err
- default:
- return "", 0, invalidRequestError("key")
- }
-
- // check for colon
- ejp.advanceState()
- if err := ensureColon(ejp.s, key); err != nil {
- return "", 0, err
- }
-
- // peek at the value to determine type
- t, err := ejp.peekType()
- if err != nil {
- return "", 0, err
- }
-
- return key, t, nil
-}
-
-// readValue returns the value corresponding to the Type returned by peekType
-func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) {
- if ejp.s == jpsInvalidState {
- return nil, ejp.err
- }
-
- var v *extJSONValue
-
- switch t {
- case bsontype.Null, bsontype.Boolean, bsontype.String:
- if ejp.s != jpsSawValue {
- return nil, invalidRequestError(t.String())
- }
- v = ejp.v
- case bsontype.Int32, bsontype.Int64, bsontype.Double:
- // relaxed version allows these to be literal number values
- if ejp.s == jpsSawValue {
- v = ejp.v
- break
- }
- fallthrough
- case bsontype.Decimal128, bsontype.Symbol, bsontype.ObjectID, bsontype.MinKey, bsontype.MaxKey, bsontype.Undefined:
- switch ejp.s {
- case jpsSawKey:
- // read colon
- ejp.advanceState()
- if err := ensureColon(ejp.s, ejp.k); err != nil {
- return nil, err
- }
-
- // read value
- ejp.advanceState()
- if ejp.s != jpsSawValue || !ejp.ensureExtValueType(t) {
- return nil, invalidJSONErrorForType("value", t)
- }
-
- v = ejp.v
-
- // read end object
- ejp.advanceState()
- if ejp.s != jpsSawEndObject {
- return nil, invalidJSONErrorForType("} after value", t)
- }
- default:
- return nil, invalidRequestError(t.String())
- }
- case bsontype.Binary, bsontype.Regex, bsontype.Timestamp, bsontype.DBPointer:
- if ejp.s != jpsSawKey {
- return nil, invalidRequestError(t.String())
- }
- // read colon
- ejp.advanceState()
- if err := ensureColon(ejp.s, ejp.k); err != nil {
- return nil, err
- }
-
- ejp.advanceState()
- if t == bsontype.Binary && ejp.s == jpsSawValue {
- // convert legacy $binary format
- base64 := ejp.v
-
- ejp.advanceState()
- if ejp.s != jpsSawComma {
- return nil, invalidJSONErrorForType(",", bsontype.Binary)
- }
-
- ejp.advanceState()
- key, t, err := ejp.readKey()
- if err != nil {
- return nil, err
- }
- if key != "$type" {
- return nil, invalidJSONErrorForType("$type", bsontype.Binary)
- }
-
- subType, err := ejp.readValue(t)
- if err != nil {
- return nil, err
- }
-
- ejp.advanceState()
- if ejp.s != jpsSawEndObject {
- return nil, invalidJSONErrorForType("2 key-value pairs and then }", bsontype.Binary)
- }
-
- v = &extJSONValue{
- t: bsontype.EmbeddedDocument,
- v: &extJSONObject{
- keys: []string{"base64", "subType"},
- values: []*extJSONValue{base64, subType},
- },
- }
- break
- }
-
- // read KV pairs
- if ejp.s != jpsSawBeginObject {
- return nil, invalidJSONErrorForType("{", t)
- }
-
- keys, vals, err := ejp.readObject(2, true)
- if err != nil {
- return nil, err
- }
-
- ejp.advanceState()
- if ejp.s != jpsSawEndObject {
- return nil, invalidJSONErrorForType("2 key-value pairs and then }", t)
- }
-
- v = &extJSONValue{t: bsontype.EmbeddedDocument, v: &extJSONObject{keys: keys, values: vals}}
-
- case bsontype.DateTime:
- switch ejp.s {
- case jpsSawValue:
- v = ejp.v
- case jpsSawKey:
- // read colon
- ejp.advanceState()
- if err := ensureColon(ejp.s, ejp.k); err != nil {
- return nil, err
- }
-
- ejp.advanceState()
- switch ejp.s {
- case jpsSawBeginObject:
- keys, vals, err := ejp.readObject(1, true)
- if err != nil {
- return nil, err
- }
- v = &extJSONValue{t: bsontype.EmbeddedDocument, v: &extJSONObject{keys: keys, values: vals}}
- case jpsSawValue:
- if ejp.canonical {
- return nil, invalidJSONError("{")
- }
- v = ejp.v
- default:
- if ejp.canonical {
- return nil, invalidJSONErrorForType("object", t)
- }
- return nil, invalidJSONErrorForType("ISO-8601 Internet Date/Time Format as decribed in RFC-3339", t)
- }
-
- ejp.advanceState()
- if ejp.s != jpsSawEndObject {
- return nil, invalidJSONErrorForType("value and then }", t)
- }
- default:
- return nil, invalidRequestError(t.String())
- }
- case bsontype.JavaScript:
- switch ejp.s {
- case jpsSawKey:
- // read colon
- ejp.advanceState()
- if err := ensureColon(ejp.s, ejp.k); err != nil {
- return nil, err
- }
-
- // read value
- ejp.advanceState()
- if ejp.s != jpsSawValue {
- return nil, invalidJSONErrorForType("value", t)
- }
- v = ejp.v
-
- // read end object or comma and just return
- ejp.advanceState()
- case jpsSawEndObject:
- v = ejp.v
- default:
- return nil, invalidRequestError(t.String())
- }
- case bsontype.CodeWithScope:
- if ejp.s == jpsSawKey && ejp.k == "$scope" {
- v = ejp.v // this is the $code string from earlier
-
- // read colon
- ejp.advanceState()
- if err := ensureColon(ejp.s, ejp.k); err != nil {
- return nil, err
- }
-
- // read {
- ejp.advanceState()
- if ejp.s != jpsSawBeginObject {
- return nil, invalidJSONError("$scope to be embedded document")
- }
- } else {
- return nil, invalidRequestError(t.String())
- }
- case bsontype.EmbeddedDocument, bsontype.Array:
- return nil, invalidRequestError(t.String())
- }
-
- return v, nil
-}
-
-// readObject is a utility method for reading full objects of known (or expected) size
-// it is useful for extended JSON types such as binary, datetime, regex, and timestamp
-func (ejp *extJSONParser) readObject(numKeys int, started bool) ([]string, []*extJSONValue, error) {
- keys := make([]string, numKeys)
- vals := make([]*extJSONValue, numKeys)
-
- if !started {
- ejp.advanceState()
- if ejp.s != jpsSawBeginObject {
- return nil, nil, invalidJSONError("{")
- }
- }
-
- for i := 0; i < numKeys; i++ {
- key, t, err := ejp.readKey()
- if err != nil {
- return nil, nil, err
- }
-
- switch ejp.s {
- case jpsSawKey:
- v, err := ejp.readValue(t)
- if err != nil {
- return nil, nil, err
- }
-
- keys[i] = key
- vals[i] = v
- case jpsSawValue:
- keys[i] = key
- vals[i] = ejp.v
- default:
- return nil, nil, invalidJSONError("value")
- }
- }
-
- ejp.advanceState()
- if ejp.s != jpsSawEndObject {
- return nil, nil, invalidJSONError("}")
- }
-
- return keys, vals, nil
-}
-
-// advanceState reads the next JSON token from the scanner and transitions
-// from the current state based on that token's type
-func (ejp *extJSONParser) advanceState() {
- if ejp.s == jpsDoneState || ejp.s == jpsInvalidState {
- return
- }
-
- jt, err := ejp.js.nextToken()
-
- if err != nil {
- ejp.err = err
- ejp.s = jpsInvalidState
- return
- }
-
- valid := ejp.validateToken(jt.t)
- if !valid {
- ejp.err = unexpectedTokenError(jt)
- ejp.s = jpsInvalidState
- return
- }
-
- switch jt.t {
- case jttBeginObject:
- ejp.s = jpsSawBeginObject
- ejp.pushMode(jpmObjectMode)
- ejp.depth++
-
- if ejp.depth > ejp.maxDepth {
- ejp.err = nestingDepthError(jt.p, ejp.depth)
- ejp.s = jpsInvalidState
- }
- case jttEndObject:
- ejp.s = jpsSawEndObject
- ejp.depth--
-
- if ejp.popMode() != jpmObjectMode {
- ejp.err = unexpectedTokenError(jt)
- ejp.s = jpsInvalidState
- }
- case jttBeginArray:
- ejp.s = jpsSawBeginArray
- ejp.pushMode(jpmArrayMode)
- case jttEndArray:
- ejp.s = jpsSawEndArray
-
- if ejp.popMode() != jpmArrayMode {
- ejp.err = unexpectedTokenError(jt)
- ejp.s = jpsInvalidState
- }
- case jttColon:
- ejp.s = jpsSawColon
- case jttComma:
- ejp.s = jpsSawComma
- case jttEOF:
- ejp.s = jpsDoneState
- if len(ejp.m) != 0 {
- ejp.err = unexpectedTokenError(jt)
- ejp.s = jpsInvalidState
- }
- case jttString:
- switch ejp.s {
- case jpsSawComma:
- if ejp.peekMode() == jpmArrayMode {
- ejp.s = jpsSawValue
- ejp.v = extendJSONToken(jt)
- return
- }
- fallthrough
- case jpsSawBeginObject:
- ejp.s = jpsSawKey
- ejp.k = jt.v.(string)
- return
- }
- fallthrough
- default:
- ejp.s = jpsSawValue
- ejp.v = extendJSONToken(jt)
- }
-}
-
-var jpsValidTransitionTokens = map[jsonParseState]map[jsonTokenType]bool{
- jpsStartState: {
- jttBeginObject: true,
- jttBeginArray: true,
- jttInt32: true,
- jttInt64: true,
- jttDouble: true,
- jttString: true,
- jttBool: true,
- jttNull: true,
- jttEOF: true,
- },
- jpsSawBeginObject: {
- jttEndObject: true,
- jttString: true,
- },
- jpsSawEndObject: {
- jttEndObject: true,
- jttEndArray: true,
- jttComma: true,
- jttEOF: true,
- },
- jpsSawBeginArray: {
- jttBeginObject: true,
- jttBeginArray: true,
- jttEndArray: true,
- jttInt32: true,
- jttInt64: true,
- jttDouble: true,
- jttString: true,
- jttBool: true,
- jttNull: true,
- },
- jpsSawEndArray: {
- jttEndObject: true,
- jttEndArray: true,
- jttComma: true,
- jttEOF: true,
- },
- jpsSawColon: {
- jttBeginObject: true,
- jttBeginArray: true,
- jttInt32: true,
- jttInt64: true,
- jttDouble: true,
- jttString: true,
- jttBool: true,
- jttNull: true,
- },
- jpsSawComma: {
- jttBeginObject: true,
- jttBeginArray: true,
- jttInt32: true,
- jttInt64: true,
- jttDouble: true,
- jttString: true,
- jttBool: true,
- jttNull: true,
- },
- jpsSawKey: {
- jttColon: true,
- },
- jpsSawValue: {
- jttEndObject: true,
- jttEndArray: true,
- jttComma: true,
- jttEOF: true,
- },
- jpsDoneState: {},
- jpsInvalidState: {},
-}
-
-func (ejp *extJSONParser) validateToken(jtt jsonTokenType) bool {
- switch ejp.s {
- case jpsSawEndObject:
- // if we are at depth zero and the next token is a '{',
- // we can consider it valid only if we are not in array mode.
- if jtt == jttBeginObject && ejp.depth == 0 {
- return ejp.peekMode() != jpmArrayMode
- }
- case jpsSawComma:
- switch ejp.peekMode() {
- // the only valid next token after a comma inside a document is a string (a key)
- case jpmObjectMode:
- return jtt == jttString
- case jpmInvalidMode:
- return false
- }
- }
-
- _, ok := jpsValidTransitionTokens[ejp.s][jtt]
- return ok
-}
-
-// ensureExtValueType returns true if the current value has the expected
-// value type for single-key extended JSON types. For example,
-// {"$numberInt": v} v must be TypeString
-func (ejp *extJSONParser) ensureExtValueType(t bsontype.Type) bool {
- switch t {
- case bsontype.MinKey, bsontype.MaxKey:
- return ejp.v.t == bsontype.Int32
- case bsontype.Undefined:
- return ejp.v.t == bsontype.Boolean
- case bsontype.Int32, bsontype.Int64, bsontype.Double, bsontype.Decimal128, bsontype.Symbol, bsontype.ObjectID:
- return ejp.v.t == bsontype.String
- default:
- return false
- }
-}
-
-func (ejp *extJSONParser) pushMode(m jsonParseMode) {
- ejp.m = append(ejp.m, m)
-}
-
-func (ejp *extJSONParser) popMode() jsonParseMode {
- l := len(ejp.m)
- if l == 0 {
- return jpmInvalidMode
- }
-
- m := ejp.m[l-1]
- ejp.m = ejp.m[:l-1]
-
- return m
-}
-
-func (ejp *extJSONParser) peekMode() jsonParseMode {
- l := len(ejp.m)
- if l == 0 {
- return jpmInvalidMode
- }
-
- return ejp.m[l-1]
-}
-
-func extendJSONToken(jt *jsonToken) *extJSONValue {
- var t bsontype.Type
-
- switch jt.t {
- case jttInt32:
- t = bsontype.Int32
- case jttInt64:
- t = bsontype.Int64
- case jttDouble:
- t = bsontype.Double
- case jttString:
- t = bsontype.String
- case jttBool:
- t = bsontype.Boolean
- case jttNull:
- t = bsontype.Null
- default:
- return nil
- }
-
- return &extJSONValue{t: t, v: jt.v}
-}
-
-func ensureColon(s jsonParseState, key string) error {
- if s != jpsSawColon {
- return fmt.Errorf("invalid JSON input: missing colon after key \"%s\"", key)
- }
-
- return nil
-}
-
-func invalidRequestError(s string) error {
- return fmt.Errorf("invalid request to read %s", s)
-}
-
-func invalidJSONError(expected string) error {
- return fmt.Errorf("invalid JSON input; expected %s", expected)
-}
-
-func invalidJSONErrorForType(expected string, t bsontype.Type) error {
- return fmt.Errorf("invalid JSON input; expected %s for %s", expected, t)
-}
-
-func unexpectedTokenError(jt *jsonToken) error {
- switch jt.t {
- case jttInt32, jttInt64, jttDouble:
- return fmt.Errorf("invalid JSON input; unexpected number (%v) at position %d", jt.v, jt.p)
- case jttString:
- return fmt.Errorf("invalid JSON input; unexpected string (\"%v\") at position %d", jt.v, jt.p)
- case jttBool:
- return fmt.Errorf("invalid JSON input; unexpected boolean literal (%v) at position %d", jt.v, jt.p)
- case jttNull:
- return fmt.Errorf("invalid JSON input; unexpected null literal at position %d", jt.p)
- case jttEOF:
- return fmt.Errorf("invalid JSON input; unexpected end of input at position %d", jt.p)
- default:
- return fmt.Errorf("invalid JSON input; unexpected %c at position %d", jt.v.(byte), jt.p)
- }
-}
-
-func nestingDepthError(p, depth int) error {
- return fmt.Errorf("invalid JSON input; nesting too deep (%d levels) at position %d", depth, p)
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_reader.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_reader.go
deleted file mode 100644
index dd560c96..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_reader.go
+++ /dev/null
@@ -1,659 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-
-package bsonrw
-
-import (
- "fmt"
- "io"
- "sync"
-
- "go.mongodb.org/mongo-driver/bson/bsontype"
- "go.mongodb.org/mongo-driver/bson/primitive"
-)
-
-// ExtJSONValueReaderPool is a pool for ValueReaders that read ExtJSON.
-type ExtJSONValueReaderPool struct {
- pool sync.Pool
-}
-
-// NewExtJSONValueReaderPool instantiates a new ExtJSONValueReaderPool.
-func NewExtJSONValueReaderPool() *ExtJSONValueReaderPool {
- return &ExtJSONValueReaderPool{
- pool: sync.Pool{
- New: func() interface{} {
- return new(extJSONValueReader)
- },
- },
- }
-}
-
-// Get retrieves a ValueReader from the pool and uses src as the underlying ExtJSON.
-func (bvrp *ExtJSONValueReaderPool) Get(r io.Reader, canonical bool) (ValueReader, error) {
- vr := bvrp.pool.Get().(*extJSONValueReader)
- return vr.reset(r, canonical)
-}
-
-// Put inserts a ValueReader into the pool. If the ValueReader is not a ExtJSON ValueReader nothing
-// is inserted into the pool and ok will be false.
-func (bvrp *ExtJSONValueReaderPool) Put(vr ValueReader) (ok bool) {
- bvr, ok := vr.(*extJSONValueReader)
- if !ok {
- return false
- }
-
- bvr, _ = bvr.reset(nil, false)
- bvrp.pool.Put(bvr)
- return true
-}
-
-type ejvrState struct {
- mode mode
- vType bsontype.Type
- depth int
-}
-
-// extJSONValueReader is for reading extended JSON.
-type extJSONValueReader struct {
- p *extJSONParser
-
- stack []ejvrState
- frame int
-}
-
-// NewExtJSONValueReader creates a new ValueReader from a given io.Reader
-// It will interpret the JSON of r as canonical or relaxed according to the
-// given canonical flag
-func NewExtJSONValueReader(r io.Reader, canonical bool) (ValueReader, error) {
- return newExtJSONValueReader(r, canonical)
-}
-
-func newExtJSONValueReader(r io.Reader, canonical bool) (*extJSONValueReader, error) {
- ejvr := new(extJSONValueReader)
- return ejvr.reset(r, canonical)
-}
-
-func (ejvr *extJSONValueReader) reset(r io.Reader, canonical bool) (*extJSONValueReader, error) {
- p := newExtJSONParser(r, canonical)
- typ, err := p.peekType()
-
- if err != nil {
- return nil, ErrInvalidJSON
- }
-
- var m mode
- switch typ {
- case bsontype.EmbeddedDocument:
- m = mTopLevel
- case bsontype.Array:
- m = mArray
- default:
- m = mValue
- }
-
- stack := make([]ejvrState, 1, 5)
- stack[0] = ejvrState{
- mode: m,
- vType: typ,
- }
- return &extJSONValueReader{
- p: p,
- stack: stack,
- }, nil
-}
-
-func (ejvr *extJSONValueReader) advanceFrame() {
- if ejvr.frame+1 >= len(ejvr.stack) { // We need to grow the stack
- length := len(ejvr.stack)
- if length+1 >= cap(ejvr.stack) {
- // double it
- buf := make([]ejvrState, 2*cap(ejvr.stack)+1)
- copy(buf, ejvr.stack)
- ejvr.stack = buf
- }
- ejvr.stack = ejvr.stack[:length+1]
- }
- ejvr.frame++
-
- // Clean the stack
- ejvr.stack[ejvr.frame].mode = 0
- ejvr.stack[ejvr.frame].vType = 0
- ejvr.stack[ejvr.frame].depth = 0
-}
-
-func (ejvr *extJSONValueReader) pushDocument() {
- ejvr.advanceFrame()
-
- ejvr.stack[ejvr.frame].mode = mDocument
- ejvr.stack[ejvr.frame].depth = ejvr.p.depth
-}
-
-func (ejvr *extJSONValueReader) pushCodeWithScope() {
- ejvr.advanceFrame()
-
- ejvr.stack[ejvr.frame].mode = mCodeWithScope
-}
-
-func (ejvr *extJSONValueReader) pushArray() {
- ejvr.advanceFrame()
-
- ejvr.stack[ejvr.frame].mode = mArray
-}
-
-func (ejvr *extJSONValueReader) push(m mode, t bsontype.Type) {
- ejvr.advanceFrame()
-
- ejvr.stack[ejvr.frame].mode = m
- ejvr.stack[ejvr.frame].vType = t
-}
-
-func (ejvr *extJSONValueReader) pop() {
- switch ejvr.stack[ejvr.frame].mode {
- case mElement, mValue:
- ejvr.frame--
- case mDocument, mArray, mCodeWithScope:
- ejvr.frame -= 2 // we pop twice to jump over the vrElement: vrDocument -> vrElement -> vrDocument/TopLevel/etc...
- }
-}
-
-func (ejvr *extJSONValueReader) skipDocument() error {
- // read entire document until ErrEOD (using readKey and readValue)
- _, typ, err := ejvr.p.readKey()
- for err == nil {
- _, err = ejvr.p.readValue(typ)
- if err != nil {
- break
- }
-
- _, typ, err = ejvr.p.readKey()
- }
-
- return err
-}
-
-func (ejvr *extJSONValueReader) skipArray() error {
- // read entire array until ErrEOA (using peekType)
- _, err := ejvr.p.peekType()
- for err == nil {
- _, err = ejvr.p.peekType()
- }
-
- return err
-}
-
-func (ejvr *extJSONValueReader) invalidTransitionErr(destination mode, name string, modes []mode) error {
- te := TransitionError{
- name: name,
- current: ejvr.stack[ejvr.frame].mode,
- destination: destination,
- modes: modes,
- action: "read",
- }
- if ejvr.frame != 0 {
- te.parent = ejvr.stack[ejvr.frame-1].mode
- }
- return te
-}
-
-func (ejvr *extJSONValueReader) typeError(t bsontype.Type) error {
- return fmt.Errorf("positioned on %s, but attempted to read %s", ejvr.stack[ejvr.frame].vType, t)
-}
-
-func (ejvr *extJSONValueReader) ensureElementValue(t bsontype.Type, destination mode, callerName string, addModes ...mode) error {
- switch ejvr.stack[ejvr.frame].mode {
- case mElement, mValue:
- if ejvr.stack[ejvr.frame].vType != t {
- return ejvr.typeError(t)
- }
- default:
- modes := []mode{mElement, mValue}
- if addModes != nil {
- modes = append(modes, addModes...)
- }
- return ejvr.invalidTransitionErr(destination, callerName, modes)
- }
-
- return nil
-}
-
-func (ejvr *extJSONValueReader) Type() bsontype.Type {
- return ejvr.stack[ejvr.frame].vType
-}
-
-func (ejvr *extJSONValueReader) Skip() error {
- switch ejvr.stack[ejvr.frame].mode {
- case mElement, mValue:
- default:
- return ejvr.invalidTransitionErr(0, "Skip", []mode{mElement, mValue})
- }
-
- defer ejvr.pop()
-
- t := ejvr.stack[ejvr.frame].vType
- switch t {
- case bsontype.Array:
- // read entire array until ErrEOA
- err := ejvr.skipArray()
- if err != ErrEOA {
- return err
- }
- case bsontype.EmbeddedDocument:
- // read entire doc until ErrEOD
- err := ejvr.skipDocument()
- if err != ErrEOD {
- return err
- }
- case bsontype.CodeWithScope:
- // read the code portion and set up parser in document mode
- _, err := ejvr.p.readValue(t)
- if err != nil {
- return err
- }
-
- // read until ErrEOD
- err = ejvr.skipDocument()
- if err != ErrEOD {
- return err
- }
- default:
- _, err := ejvr.p.readValue(t)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (ejvr *extJSONValueReader) ReadArray() (ArrayReader, error) {
- switch ejvr.stack[ejvr.frame].mode {
- case mTopLevel: // allow reading array from top level
- case mArray:
- return ejvr, nil
- default:
- if err := ejvr.ensureElementValue(bsontype.Array, mArray, "ReadArray", mTopLevel, mArray); err != nil {
- return nil, err
- }
- }
-
- ejvr.pushArray()
-
- return ejvr, nil
-}
-
-func (ejvr *extJSONValueReader) ReadBinary() (b []byte, btype byte, err error) {
- if err := ejvr.ensureElementValue(bsontype.Binary, 0, "ReadBinary"); err != nil {
- return nil, 0, err
- }
-
- v, err := ejvr.p.readValue(bsontype.Binary)
- if err != nil {
- return nil, 0, err
- }
-
- b, btype, err = v.parseBinary()
-
- ejvr.pop()
- return b, btype, err
-}
-
-func (ejvr *extJSONValueReader) ReadBoolean() (bool, error) {
- if err := ejvr.ensureElementValue(bsontype.Boolean, 0, "ReadBoolean"); err != nil {
- return false, err
- }
-
- v, err := ejvr.p.readValue(bsontype.Boolean)
- if err != nil {
- return false, err
- }
-
- if v.t != bsontype.Boolean {
- return false, fmt.Errorf("expected type bool, but got type %s", v.t)
- }
-
- ejvr.pop()
- return v.v.(bool), nil
-}
-
-func (ejvr *extJSONValueReader) ReadDocument() (DocumentReader, error) {
- switch ejvr.stack[ejvr.frame].mode {
- case mTopLevel:
- return ejvr, nil
- case mElement, mValue:
- if ejvr.stack[ejvr.frame].vType != bsontype.EmbeddedDocument {
- return nil, ejvr.typeError(bsontype.EmbeddedDocument)
- }
-
- ejvr.pushDocument()
- return ejvr, nil
- default:
- return nil, ejvr.invalidTransitionErr(mDocument, "ReadDocument", []mode{mTopLevel, mElement, mValue})
- }
-}
-
-func (ejvr *extJSONValueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) {
- if err = ejvr.ensureElementValue(bsontype.CodeWithScope, 0, "ReadCodeWithScope"); err != nil {
- return "", nil, err
- }
-
- v, err := ejvr.p.readValue(bsontype.CodeWithScope)
- if err != nil {
- return "", nil, err
- }
-
- code, err = v.parseJavascript()
-
- ejvr.pushCodeWithScope()
- return code, ejvr, err
-}
-
-func (ejvr *extJSONValueReader) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) {
- if err = ejvr.ensureElementValue(bsontype.DBPointer, 0, "ReadDBPointer"); err != nil {
- return "", primitive.NilObjectID, err
- }
-
- v, err := ejvr.p.readValue(bsontype.DBPointer)
- if err != nil {
- return "", primitive.NilObjectID, err
- }
-
- ns, oid, err = v.parseDBPointer()
-
- ejvr.pop()
- return ns, oid, err
-}
-
-func (ejvr *extJSONValueReader) ReadDateTime() (int64, error) {
- if err := ejvr.ensureElementValue(bsontype.DateTime, 0, "ReadDateTime"); err != nil {
- return 0, err
- }
-
- v, err := ejvr.p.readValue(bsontype.DateTime)
- if err != nil {
- return 0, err
- }
-
- d, err := v.parseDateTime()
-
- ejvr.pop()
- return d, err
-}
-
-func (ejvr *extJSONValueReader) ReadDecimal128() (primitive.Decimal128, error) {
- if err := ejvr.ensureElementValue(bsontype.Decimal128, 0, "ReadDecimal128"); err != nil {
- return primitive.Decimal128{}, err
- }
-
- v, err := ejvr.p.readValue(bsontype.Decimal128)
- if err != nil {
- return primitive.Decimal128{}, err
- }
-
- d, err := v.parseDecimal128()
-
- ejvr.pop()
- return d, err
-}
-
-func (ejvr *extJSONValueReader) ReadDouble() (float64, error) {
- if err := ejvr.ensureElementValue(bsontype.Double, 0, "ReadDouble"); err != nil {
- return 0, err
- }
-
- v, err := ejvr.p.readValue(bsontype.Double)
- if err != nil {
- return 0, err
- }
-
- d, err := v.parseDouble()
-
- ejvr.pop()
- return d, err
-}
-
-func (ejvr *extJSONValueReader) ReadInt32() (int32, error) {
- if err := ejvr.ensureElementValue(bsontype.Int32, 0, "ReadInt32"); err != nil {
- return 0, err
- }
-
- v, err := ejvr.p.readValue(bsontype.Int32)
- if err != nil {
- return 0, err
- }
-
- i, err := v.parseInt32()
-
- ejvr.pop()
- return i, err
-}
-
-func (ejvr *extJSONValueReader) ReadInt64() (int64, error) {
- if err := ejvr.ensureElementValue(bsontype.Int64, 0, "ReadInt64"); err != nil {
- return 0, err
- }
-
- v, err := ejvr.p.readValue(bsontype.Int64)
- if err != nil {
- return 0, err
- }
-
- i, err := v.parseInt64()
-
- ejvr.pop()
- return i, err
-}
-
-func (ejvr *extJSONValueReader) ReadJavascript() (code string, err error) {
- if err = ejvr.ensureElementValue(bsontype.JavaScript, 0, "ReadJavascript"); err != nil {
- return "", err
- }
-
- v, err := ejvr.p.readValue(bsontype.JavaScript)
- if err != nil {
- return "", err
- }
-
- code, err = v.parseJavascript()
-
- ejvr.pop()
- return code, err
-}
-
-func (ejvr *extJSONValueReader) ReadMaxKey() error {
- if err := ejvr.ensureElementValue(bsontype.MaxKey, 0, "ReadMaxKey"); err != nil {
- return err
- }
-
- v, err := ejvr.p.readValue(bsontype.MaxKey)
- if err != nil {
- return err
- }
-
- err = v.parseMinMaxKey("max")
-
- ejvr.pop()
- return err
-}
-
-func (ejvr *extJSONValueReader) ReadMinKey() error {
- if err := ejvr.ensureElementValue(bsontype.MinKey, 0, "ReadMinKey"); err != nil {
- return err
- }
-
- v, err := ejvr.p.readValue(bsontype.MinKey)
- if err != nil {
- return err
- }
-
- err = v.parseMinMaxKey("min")
-
- ejvr.pop()
- return err
-}
-
-func (ejvr *extJSONValueReader) ReadNull() error {
- if err := ejvr.ensureElementValue(bsontype.Null, 0, "ReadNull"); err != nil {
- return err
- }
-
- v, err := ejvr.p.readValue(bsontype.Null)
- if err != nil {
- return err
- }
-
- if v.t != bsontype.Null {
- return fmt.Errorf("expected type null but got type %s", v.t)
- }
-
- ejvr.pop()
- return nil
-}
-
-func (ejvr *extJSONValueReader) ReadObjectID() (primitive.ObjectID, error) {
- if err := ejvr.ensureElementValue(bsontype.ObjectID, 0, "ReadObjectID"); err != nil {
- return primitive.ObjectID{}, err
- }
-
- v, err := ejvr.p.readValue(bsontype.ObjectID)
- if err != nil {
- return primitive.ObjectID{}, err
- }
-
- oid, err := v.parseObjectID()
-
- ejvr.pop()
- return oid, err
-}
-
-func (ejvr *extJSONValueReader) ReadRegex() (pattern string, options string, err error) {
- if err = ejvr.ensureElementValue(bsontype.Regex, 0, "ReadRegex"); err != nil {
- return "", "", err
- }
-
- v, err := ejvr.p.readValue(bsontype.Regex)
- if err != nil {
- return "", "", err
- }
-
- pattern, options, err = v.parseRegex()
-
- ejvr.pop()
- return pattern, options, err
-}
-
-func (ejvr *extJSONValueReader) ReadString() (string, error) {
- if err := ejvr.ensureElementValue(bsontype.String, 0, "ReadString"); err != nil {
- return "", err
- }
-
- v, err := ejvr.p.readValue(bsontype.String)
- if err != nil {
- return "", err
- }
-
- if v.t != bsontype.String {
- return "", fmt.Errorf("expected type string but got type %s", v.t)
- }
-
- ejvr.pop()
- return v.v.(string), nil
-}
-
-func (ejvr *extJSONValueReader) ReadSymbol() (symbol string, err error) {
- if err = ejvr.ensureElementValue(bsontype.Symbol, 0, "ReadSymbol"); err != nil {
- return "", err
- }
-
- v, err := ejvr.p.readValue(bsontype.Symbol)
- if err != nil {
- return "", err
- }
-
- symbol, err = v.parseSymbol()
-
- ejvr.pop()
- return symbol, err
-}
-
-func (ejvr *extJSONValueReader) ReadTimestamp() (t uint32, i uint32, err error) {
- if err = ejvr.ensureElementValue(bsontype.Timestamp, 0, "ReadTimestamp"); err != nil {
- return 0, 0, err
- }
-
- v, err := ejvr.p.readValue(bsontype.Timestamp)
- if err != nil {
- return 0, 0, err
- }
-
- t, i, err = v.parseTimestamp()
-
- ejvr.pop()
- return t, i, err
-}
-
-func (ejvr *extJSONValueReader) ReadUndefined() error {
- if err := ejvr.ensureElementValue(bsontype.Undefined, 0, "ReadUndefined"); err != nil {
- return err
- }
-
- v, err := ejvr.p.readValue(bsontype.Undefined)
- if err != nil {
- return err
- }
-
- err = v.parseUndefined()
-
- ejvr.pop()
- return err
-}
-
-func (ejvr *extJSONValueReader) ReadElement() (string, ValueReader, error) {
- switch ejvr.stack[ejvr.frame].mode {
- case mTopLevel, mDocument, mCodeWithScope:
- default:
- return "", nil, ejvr.invalidTransitionErr(mElement, "ReadElement", []mode{mTopLevel, mDocument, mCodeWithScope})
- }
-
- name, t, err := ejvr.p.readKey()
-
- if err != nil {
- if err == ErrEOD {
- if ejvr.stack[ejvr.frame].mode == mCodeWithScope {
- _, err := ejvr.p.peekType()
- if err != nil {
- return "", nil, err
- }
- }
-
- ejvr.pop()
- }
-
- return "", nil, err
- }
-
- ejvr.push(mElement, t)
- return name, ejvr, nil
-}
-
-func (ejvr *extJSONValueReader) ReadValue() (ValueReader, error) {
- switch ejvr.stack[ejvr.frame].mode {
- case mArray:
- default:
- return nil, ejvr.invalidTransitionErr(mValue, "ReadValue", []mode{mArray})
- }
-
- t, err := ejvr.p.peekType()
- if err != nil {
- if err == ErrEOA {
- ejvr.pop()
- }
-
- return nil, err
- }
-
- ejvr.push(mValue, t)
- return ejvr, nil
-}
diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_tables.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_tables.go
deleted file mode 100644
index ba39c960..00000000
--- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_tables.go
+++ /dev/null
@@ -1,223 +0,0 @@
-// Copyright (C) MongoDB, Inc. 2017-present.
-//
-// 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
-//
-// Based on github.com/golang/go by The Go Authors
-// See THIRD-PARTY-NOTICES for original license terms.
-
-package bsonrw
-
-import "unicode/utf8"
-
-// safeSet holds the value true if the ASCII character with the given array
-// position can be represented inside a JSON string without any further
-// escaping.
-//
-// All values are true except for the ASCII control characters (0-31), the
-// double quote ("), and the backslash character ("\").
-var safeSet = [utf8.RuneSelf]bool{
- ' ': true,
- '!': true,
- '"': false,
- '#': true,
- '$': true,
- '%': true,
- '&': true,
- '\'': true,
- '(': true,
- ')': true,
- '*': true,
- '+': true,
- ',': true,
- '-': true,
- '.': true,
- '/': true,
- '0': true,
- '1': true,
- '2': true,
- '3': true,
- '4': true,
- '5': true,
- '6': true,
- '7': true,
- '8': true,
- '9': true,
- ':': true,
- ';': true,
- '<': true,
- '=': true,
- '>': true,
- '?': true,
- '@': true,
- 'A': true,
- 'B': true,
- 'C': true,
- 'D': true,
- 'E': true,
- 'F': true,
- 'G': true,
- 'H': true,
- 'I': true,
- 'J': true,
- 'K': true,
- 'L': true,
- 'M': true,
- 'N': true,
- 'O': true,
- 'P': true,
- 'Q': true,
- 'R': true,
- 'S': true,
- 'T': true,
- 'U': true,
- 'V': true,
- 'W': true,
- 'X': true,
- 'Y': true,
- 'Z': true,
- '[': true,
- '\\': false,
- ']': true,
- '^': true,
- '_': true,
- '`': true,
- 'a': true,
- 'b': true,
- 'c': true,
- 'd': true,
- 'e': true,
- 'f': true,
- 'g': true,
- 'h': true,
- 'i': true,
- 'j': true,
- 'k': true,
- 'l': true,
- 'm': true,
- 'n': true,
- 'o': true,
- 'p': true,
- 'q': true,
- 'r': true,
- 's': true,
- 't': true,
- 'u': true,
- 'v': true,
- 'w': true,
- 'x': true,
- 'y': true,
- 'z': true,
- '{': true,
- '|': true,
- '}': true,
- '~': true,
- '\u007f': true,
-}
-
-// htmlSafeSet holds the value true if the ASCII character with the given
-// array position can be safely represented inside a JSON string, embedded
-// inside of HTML