diff --git a/go.mod b/go.mod index 3f821004..5da38352 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.25.8 require ( github.com/google/go-containerregistry v0.20.7 github.com/sigstore/cosign/v3 v3.0.5 - github.com/sigstore/rekor v1.5.0 + github.com/sigstore/rekor v1.5.1 github.com/sigstore/sigstore v1.10.4 github.com/sirupsen/logrus v1.9.4 github.com/theupdateframework/go-tuf v0.7.0 @@ -30,32 +30,32 @@ require ( github.com/dustin/go-humanize v1.0.1 // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect - github.com/go-chi/chi/v5 v5.2.4 // indirect + github.com/go-chi/chi/v5 v5.2.5 // indirect github.com/go-jose/go-jose/v4 v4.1.3 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/analysis v0.24.1 // indirect - github.com/go-openapi/errors v0.22.6 // indirect - github.com/go-openapi/jsonpointer v0.22.4 // indirect - github.com/go-openapi/jsonreference v0.21.4 // indirect - github.com/go-openapi/loads v0.23.2 // indirect - github.com/go-openapi/runtime v0.29.2 // indirect - github.com/go-openapi/spec v0.22.3 // indirect - github.com/go-openapi/strfmt v0.25.0 // indirect - github.com/go-openapi/swag v0.25.4 // indirect - github.com/go-openapi/swag/cmdutils v0.25.4 // indirect - github.com/go-openapi/swag/conv v0.25.4 // indirect - github.com/go-openapi/swag/fileutils v0.25.4 // indirect - github.com/go-openapi/swag/jsonname v0.25.4 // indirect - github.com/go-openapi/swag/jsonutils v0.25.4 // indirect - github.com/go-openapi/swag/loading v0.25.4 // indirect - github.com/go-openapi/swag/mangling v0.25.4 // indirect - github.com/go-openapi/swag/netutils v0.25.4 // indirect - github.com/go-openapi/swag/stringutils v0.25.4 // indirect - github.com/go-openapi/swag/typeutils v0.25.4 // indirect - github.com/go-openapi/swag/yamlutils v0.25.4 // indirect - github.com/go-openapi/validate v0.25.1 // indirect - github.com/go-viper/mapstructure/v2 v2.4.0 // indirect + github.com/go-openapi/analysis v0.24.3 // indirect + github.com/go-openapi/errors v0.22.7 // indirect + github.com/go-openapi/jsonpointer v0.22.5 // indirect + github.com/go-openapi/jsonreference v0.21.5 // indirect + github.com/go-openapi/loads v0.23.3 // indirect + github.com/go-openapi/runtime v0.29.3 // indirect + github.com/go-openapi/spec v0.22.4 // indirect + github.com/go-openapi/strfmt v0.26.0 // indirect + github.com/go-openapi/swag v0.25.5 // indirect + github.com/go-openapi/swag/cmdutils v0.25.5 // indirect + github.com/go-openapi/swag/conv v0.25.5 // indirect + github.com/go-openapi/swag/fileutils v0.25.5 // indirect + github.com/go-openapi/swag/jsonname v0.25.5 // indirect + github.com/go-openapi/swag/jsonutils v0.25.5 // indirect + github.com/go-openapi/swag/loading v0.25.5 // indirect + github.com/go-openapi/swag/mangling v0.25.5 // indirect + github.com/go-openapi/swag/netutils v0.25.5 // indirect + github.com/go-openapi/swag/stringutils v0.25.5 // indirect + github.com/go-openapi/swag/typeutils v0.25.5 // indirect + github.com/go-openapi/swag/yamlutils v0.25.5 // indirect + github.com/go-openapi/validate v0.25.2 // indirect + github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/certificate-transparency-go v1.3.2 // indirect github.com/google/gnostic-models v0.7.0 // indirect @@ -79,7 +79,7 @@ require ( github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/nozzle/throttler v0.0.0-20180817012639-2ea982251481 // indirect - github.com/oklog/ulid v1.3.1 // indirect + github.com/oklog/ulid/v2 v2.1.1 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect @@ -102,27 +102,26 @@ require ( github.com/vbatts/tar-split v0.12.2 // indirect github.com/x448/float16 v0.8.4 // indirect gitlab.com/gitlab-org/api/client-go v1.25.0 // indirect - go.mongodb.org/mongo-driver v1.17.6 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/otel v1.39.0 // indirect - go.opentelemetry.io/otel/metric v1.39.0 // indirect - go.opentelemetry.io/otel/trace v1.39.0 // indirect + go.opentelemetry.io/otel v1.41.0 // indirect + go.opentelemetry.io/otel/metric v1.41.0 // indirect + go.opentelemetry.io/otel/trace v1.41.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.1 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.47.0 // indirect - golang.org/x/mod v0.32.0 // indirect - golang.org/x/net v0.49.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/mod v0.33.0 // indirect + golang.org/x/net v0.50.0 // indirect golang.org/x/oauth2 v0.35.0 // indirect golang.org/x/sync v0.19.0 // indirect - golang.org/x/sys v0.40.0 // indirect - golang.org/x/term v0.39.0 // indirect - golang.org/x/text v0.33.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/term v0.40.0 // indirect + golang.org/x/text v0.34.0 // indirect golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 // indirect - google.golang.org/grpc v1.78.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260217215200-42d3e9bedb6d // indirect + google.golang.org/grpc v1.79.2 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect diff --git a/go.sum b/go.sum index 7c01e463..46fe3477 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,8 @@ al.essio.dev/pkg/shellescape v1.6.0 h1:NxFcEqzFSEVCGN2yq7Huv/9hyCEGVa/TncnOOBBeX al.essio.dev/pkg/shellescape v1.6.0/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -cloud.google.com/go/auth v0.18.1 h1:IwTEx92GFUo2pJ6Qea0EU3zYvKnTAeRCODxfA/G5UWs= -cloud.google.com/go/auth v0.18.1/go.mod h1:GfTYoS9G3CWpRA3Va9doKN9mjPGRS+v41jmZAhBzbrA= +cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= +cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= @@ -127,8 +127,8 @@ github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/go-chi/chi/v5 v5.2.4 h1:WtFKPHwlywe8Srng8j2BhOD9312j9cGUxG1SP4V2cR4= -github.com/go-chi/chi/v5 v5.2.4/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= +github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= +github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -136,54 +136,54 @@ github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/analysis v0.24.1 h1:Xp+7Yn/KOnVWYG8d+hPksOYnCYImE3TieBa7rBOesYM= -github.com/go-openapi/analysis v0.24.1/go.mod h1:dU+qxX7QGU1rl7IYhBC8bIfmWQdX4Buoea4TGtxXY84= -github.com/go-openapi/errors v0.22.6 h1:eDxcf89O8odEnohIXwEjY1IB4ph5vmbUsBMsFNwXWPo= -github.com/go-openapi/errors v0.22.6/go.mod h1:z9S8ASTUqx7+CP1Q8dD8ewGH/1JWFFLX/2PmAYNQLgk= -github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4= -github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80= -github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8= -github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4= -github.com/go-openapi/loads v0.23.2 h1:rJXAcP7g1+lWyBHC7iTY+WAF0rprtM+pm8Jxv1uQJp4= -github.com/go-openapi/loads v0.23.2/go.mod h1:IEVw1GfRt/P2Pplkelxzj9BYFajiWOtY2nHZNj4UnWY= -github.com/go-openapi/runtime v0.29.2 h1:UmwSGWNmWQqKm1c2MGgXVpC2FTGwPDQeUsBMufc5Yj0= -github.com/go-openapi/runtime v0.29.2/go.mod h1:biq5kJXRJKBJxTDJXAa00DOTa/anflQPhT0/wmjuy+0= -github.com/go-openapi/spec v0.22.3 h1:qRSmj6Smz2rEBxMnLRBMeBWxbbOvuOoElvSvObIgwQc= -github.com/go-openapi/spec v0.22.3/go.mod h1:iIImLODL2loCh3Vnox8TY2YWYJZjMAKYyLH2Mu8lOZs= -github.com/go-openapi/strfmt v0.25.0 h1:7R0RX7mbKLa9EYCTHRcCuIPcaqlyQiWNPTXwClK0saQ= -github.com/go-openapi/strfmt v0.25.0/go.mod h1:nNXct7OzbwrMY9+5tLX4I21pzcmE6ccMGXl3jFdPfn8= -github.com/go-openapi/swag v0.25.4 h1:OyUPUFYDPDBMkqyxOTkqDYFnrhuhi9NR6QVUvIochMU= -github.com/go-openapi/swag v0.25.4/go.mod h1:zNfJ9WZABGHCFg2RnY0S4IOkAcVTzJ6z2Bi+Q4i6qFQ= -github.com/go-openapi/swag/cmdutils v0.25.4 h1:8rYhB5n6WawR192/BfUu2iVlxqVR9aRgGJP6WaBoW+4= -github.com/go-openapi/swag/cmdutils v0.25.4/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0= -github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4= -github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU= -github.com/go-openapi/swag/fileutils v0.25.4 h1:2oI0XNW5y6UWZTC7vAxC8hmsK/tOkWXHJQH4lKjqw+Y= -github.com/go-openapi/swag/fileutils v0.25.4/go.mod h1:cdOT/PKbwcysVQ9Tpr0q20lQKH7MGhOEb6EwmHOirUk= -github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI= -github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag= -github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA= -github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4/go.mod h1:Mt0Ost9l3cUzVv4OEZG+WSeoHwjWLnarzMePNDAOBiM= -github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s= -github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE= -github.com/go-openapi/swag/mangling v0.25.4 h1:2b9kBJk9JvPgxr36V23FxJLdwBrpijI26Bx5JH4Hp48= -github.com/go-openapi/swag/mangling v0.25.4/go.mod h1:6dxwu6QyORHpIIApsdZgb6wBk/DPU15MdyYj/ikn0Hg= -github.com/go-openapi/swag/netutils v0.25.4 h1:Gqe6K71bGRb3ZQLusdI8p/y1KLgV4M/k+/HzVSqT8H0= -github.com/go-openapi/swag/netutils v0.25.4/go.mod h1:m2W8dtdaoX7oj9rEttLyTeEFFEBvnAx9qHd5nJEBzYg= -github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8= -github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0= -github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw= -github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE= -github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw= -github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc= -github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4= -github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg= -github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= -github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= -github.com/go-openapi/validate v0.25.1 h1:sSACUI6Jcnbo5IWqbYHgjibrhhmt3vR6lCzKZnmAgBw= -github.com/go-openapi/validate v0.25.1/go.mod h1:RMVyVFYte0gbSTaZ0N4KmTn6u/kClvAFp+mAVfS/DQc= +github.com/go-openapi/analysis v0.24.3 h1:a1hrvMr8X0Xt69KP5uVTu5jH62DscmDifrLzNglAayk= +github.com/go-openapi/analysis v0.24.3/go.mod h1:Nc+dWJ/FxZbhSow5Yh3ozg5CLJioB+XXT6MdLvJUsUw= +github.com/go-openapi/errors v0.22.7 h1:JLFBGC0Apwdzw3484MmBqspjPbwa2SHvpDm0u5aGhUA= +github.com/go-openapi/errors v0.22.7/go.mod h1://QW6SD9OsWtH6gHllUCddOXDL0tk0ZGNYHwsw4sW3w= +github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA= +github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0= +github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE= +github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw= +github.com/go-openapi/loads v0.23.3 h1:g5Xap1JfwKkUnZdn+S0L3SzBDpcTIYzZ5Qaag0YDkKQ= +github.com/go-openapi/loads v0.23.3/go.mod h1:NOH07zLajXo8y55hom0omlHWDVVvCwBM/S+csCK8LqA= +github.com/go-openapi/runtime v0.29.3 h1:h5twGaEqxtQg40ePiYm9vFFH1q06Czd7Ot6ufdK0w/Y= +github.com/go-openapi/runtime v0.29.3/go.mod h1:8A1W0/L5eyNJvKciqZtvIVQvYO66NlB7INMSZ9bw/oI= +github.com/go-openapi/spec v0.22.4 h1:4pxGjipMKu0FzFiu/DPwN3CTBRlVM2yLf/YTWorYfDQ= +github.com/go-openapi/spec v0.22.4/go.mod h1:WQ6Ai0VPWMZgMT4XySjlRIE6GP1bGQOtEThn3gcWLtQ= +github.com/go-openapi/strfmt v0.26.0 h1:SDdQLyOEqu8W96rO1FRG1fuCtVyzmukky0zcD6gMGLU= +github.com/go-openapi/strfmt v0.26.0/go.mod h1:Zslk5VZPOISLwmWTMBIS7oiVFem1o1EI6zULY8Uer7Y= +github.com/go-openapi/swag v0.25.5 h1:pNkwbUEeGwMtcgxDr+2GBPAk4kT+kJ+AaB+TMKAg+TU= +github.com/go-openapi/swag v0.25.5/go.mod h1:B3RT6l8q7X803JRxa2e59tHOiZlX1t8viplOcs9CwTA= +github.com/go-openapi/swag/cmdutils v0.25.5 h1:yh5hHrpgsw4NwM9KAEtaDTXILYzdXh/I8Whhx9hKj7c= +github.com/go-openapi/swag/cmdutils v0.25.5/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0= +github.com/go-openapi/swag/conv v0.25.5 h1:wAXBYEXJjoKwE5+vc9YHhpQOFj2JYBMF2DUi+tGu97g= +github.com/go-openapi/swag/conv v0.25.5/go.mod h1:CuJ1eWvh1c4ORKx7unQnFGyvBbNlRKbnRyAvDvzWA4k= +github.com/go-openapi/swag/fileutils v0.25.5 h1:B6JTdOcs2c0dBIs9HnkyTW+5gC+8NIhVBUwERkFhMWk= +github.com/go-openapi/swag/fileutils v0.25.5/go.mod h1:V3cT9UdMQIaH4WiTrUc9EPtVA4txS0TOmRURmhGF4kc= +github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo= +github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU= +github.com/go-openapi/swag/jsonutils v0.25.5 h1:XUZF8awQr75MXeC+/iaw5usY/iM7nXPDwdG3Jbl9vYo= +github.com/go-openapi/swag/jsonutils v0.25.5/go.mod h1:48FXUaz8YsDAA9s5AnaUvAmry1UcLcNVWUjY42XkrN4= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.5 h1:SX6sE4FrGb4sEnnxbFL/25yZBb5Hcg1inLeErd86Y1U= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.5/go.mod h1:/2KvOTrKWjVA5Xli3DZWdMCZDzz3uV/T7bXwrKWPquo= +github.com/go-openapi/swag/loading v0.25.5 h1:odQ/umlIZ1ZVRteI6ckSrvP6e2w9UTF5qgNdemJHjuU= +github.com/go-openapi/swag/loading v0.25.5/go.mod h1:I8A8RaaQ4DApxhPSWLNYWh9NvmX2YKMoB9nwvv6oW6g= +github.com/go-openapi/swag/mangling v0.25.5 h1:hyrnvbQRS7vKePQPHHDso+k6CGn5ZBs5232UqWZmJZw= +github.com/go-openapi/swag/mangling v0.25.5/go.mod h1:6hadXM/o312N/h98RwByLg088U61TPGiltQn71Iw0NY= +github.com/go-openapi/swag/netutils v0.25.5 h1:LZq2Xc2QI8+7838elRAaPCeqJnHODfSyOa7ZGfxDKlU= +github.com/go-openapi/swag/netutils v0.25.5/go.mod h1:lHbtmj4m57APG/8H7ZcMMSWzNqIQcu0RFiXrPUara14= +github.com/go-openapi/swag/stringutils v0.25.5 h1:NVkoDOA8YBgtAR/zvCx5rhJKtZF3IzXcDdwOsYzrB6M= +github.com/go-openapi/swag/stringutils v0.25.5/go.mod h1:PKK8EZdu4QJq8iezt17HM8RXnLAzY7gW0O1KKarrZII= +github.com/go-openapi/swag/typeutils v0.25.5 h1:EFJ+PCga2HfHGdo8s8VJXEVbeXRCYwzzr9u4rJk7L7E= +github.com/go-openapi/swag/typeutils v0.25.5/go.mod h1:itmFmScAYE1bSD8C4rS0W+0InZUBrB2xSPbWt6DLGuc= +github.com/go-openapi/swag/yamlutils v0.25.5 h1:kASCIS+oIeoc55j28T4o8KwlV2S4ZLPT6G0iq2SSbVQ= +github.com/go-openapi/swag/yamlutils v0.25.5/go.mod h1:Gek1/SjjfbYvM+Iq4QGwa/2lEXde9n2j4a3wI3pNuOQ= +github.com/go-openapi/testify/enable/yaml/v2 v2.4.1 h1:NZOrZmIb6PTv5LTFxr5/mKV/FjbUzGE7E6gLz7vFoOQ= +github.com/go-openapi/testify/enable/yaml/v2 v2.4.1/go.mod h1:r7dwsujEHawapMsxA69i+XMGZrQ5tRauhLAjV/sxg3Q= +github.com/go-openapi/testify/v2 v2.4.1 h1:zB34HDKj4tHwyUQHrUkpV0Q0iXQ6dUCOQtIqn8hE6Iw= +github.com/go-openapi/testify/v2 v2.4.1/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +github.com/go-openapi/validate v0.25.2 h1:12NsfLAwGegqbGWr2CnvT65X/Q2USJipmJ9b7xDJZz0= +github.com/go-openapi/validate v0.25.2/go.mod h1:Pgl1LpPPGFnZ+ys4/hTlDiRYQdI1ocKypgE+8Q8BLfY= github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA= github.com/go-rod/rod v0.116.2/go.mod h1:H+CMO9SCNc2TJ2WfrG+pKhITz57uGNYU43qYHh438Mg= github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= @@ -192,8 +192,8 @@ github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8Wd github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= -github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= +github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= @@ -240,8 +240,8 @@ github.com/google/trillian v1.7.2 h1:EPBxc4YWY4Ak8tcuhyFleY+zYlbCDCa4Sn24e1Ka8Js github.com/google/trillian v1.7.2/go.mod h1:mfQJW4qRH6/ilABtPYNBerVJAJ/upxHLX81zxNQw05s= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= -github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= +github.com/googleapis/enterprise-certificate-proxy v0.3.12 h1:Fg+zsqzYEs1ZnvmcztTYxhgCBsx3eEhEwQ1W/lHq/sQ= +github.com/googleapis/enterprise-certificate-proxy v0.3.12/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc= github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= @@ -339,8 +339,8 @@ github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY= github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc= -github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s= +github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= @@ -359,6 +359,7 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -394,8 +395,8 @@ github.com/sigstore/cosign/v3 v3.0.5 h1:c1zPqjU+H4wmirgysC+AkWMg7a7fykyOYF/m+F11 github.com/sigstore/cosign/v3 v3.0.5/go.mod h1:ble1vMvJagCFyTIDkibCq6MIHiWDw00JNYl0f9rB4T4= github.com/sigstore/protobuf-specs v0.5.0 h1:F8YTI65xOHw70NrvPwJ5PhAzsvTnuJMGLkA4FIkofAY= github.com/sigstore/protobuf-specs v0.5.0/go.mod h1:+gXR+38nIa2oEupqDdzg4qSBT0Os+sP7oYv6alWewWc= -github.com/sigstore/rekor v1.5.0 h1:rL7SghHd5HLCtsCrxw0yQg+NczGvM75EjSPPWuGjaiQ= -github.com/sigstore/rekor v1.5.0/go.mod h1:D7JoVCUkxwQOpPDNYeu+CE8zeBC18Y5uDo6tF8s2rcQ= +github.com/sigstore/rekor v1.5.1 h1:Ca1egHRWRuDvXV4tZu9aXEXc3Gej9FG+HKeapV9OAMQ= +github.com/sigstore/rekor v1.5.1/go.mod h1:gTLDuZuo3SyQCuZvKqwRPA79Qo/2rw39/WtLP/rZjUQ= github.com/sigstore/rekor-tiles/v2 v2.2.0 h1:QwJNwxT+k5A3id+Hrg+8vYcNsTaB0Sj51xjfW2rKyAs= github.com/sigstore/rekor-tiles/v2 v2.2.0/go.mod h1:/WNRYctHKdxcjgXydYwO5OclW72Zqh6fNHSyGE8zQOE= github.com/sigstore/sigstore v1.10.4 h1:ytOmxMgLdcUed3w1SbbZOgcxqwMG61lh1TmZLN+WeZE= @@ -468,26 +469,24 @@ github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8u github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= gitlab.com/gitlab-org/api/client-go v1.25.0 h1:9YVk2o1CjZWKh2/KGOsNbOReBSxFIdBv6LrdOnBfEQY= gitlab.com/gitlab-org/api/client-go v1.25.0/go.mod h1:r060AandE8Md/L5oKdUVjljL8YQprOAxKzUnpqWqP3A= -go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss= -go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 h1:YH4g8lQroajqUwWbq/tr2QX1JFmEXaDLgG+ew9bLMWo= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0/go.mod h1:fvPi2qXDqFs8M4B4fmJhE92TyQs9Ydjlg3RvfUp+NbQ= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= -go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48= -go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8= -go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0= -go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs= -go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18= -go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE= -go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8= -go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew= -go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI= -go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= -go.step.sm/crypto v0.76.0 h1:K23BSaeoiY7Y5dvvijTeYC9EduDBetNwQYMBwMhi1aA= -go.step.sm/crypto v0.76.0/go.mod h1:PXYJdKkK8s+GHLwLguFaLxHNAFsFL3tL1vSBrYfey5k= +go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c= +go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE= +go.opentelemetry.io/otel/metric v1.41.0 h1:rFnDcs4gRzBcsO9tS8LCpgR0dxg4aaxWlJxCno7JlTQ= +go.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps= +go.opentelemetry.io/otel/sdk v1.41.0 h1:YPIEXKmiAwkGl3Gu1huk1aYWwtpRLeskpV+wPisxBp8= +go.opentelemetry.io/otel/sdk v1.41.0/go.mod h1:ahFdU0G5y8IxglBf0QBJXgSe7agzjE4GiTJ6HT9ud90= +go.opentelemetry.io/otel/sdk/metric v1.41.0 h1:siZQIYBAUd1rlIWQT2uCxWJxcCO7q3TriaMlf08rXw8= +go.opentelemetry.io/otel/sdk/metric v1.41.0/go.mod h1:HNBuSvT7ROaGtGI50ArdRLUnvRTRGniSUZbxiWxSO8Y= +go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0= +go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis= +go.step.sm/crypto v0.76.2 h1:JJ/yMcs/rmcCAwlo+afrHjq74XBFRTJw5B2y4Q4Z4c4= +go.step.sm/crypto v0.76.2/go.mod h1:m6KlB/HzIuGFep0UWI5e0SYi38UxpoKeCg6qUaHV6/Q= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -501,11 +500,11 @@ go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= -golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= -golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= +golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= +golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -514,8 +513,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= -golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= +golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= +golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM= golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -541,25 +540,25 @@ golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= -golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY= -golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww= +golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= +golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= -golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= -golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -567,16 +566,16 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/api v0.267.0 h1:w+vfWPMPYeRs8qH1aYYsFX68jMls5acWl/jocfLomwE= -google.golang.org/api v0.267.0/go.mod h1:Jzc0+ZfLnyvXma3UtaTl023TdhZu6OMBP9tJ+0EmFD0= +google.golang.org/api v0.269.0 h1:qDrTOxKUQ/P0MveH6a7vZ+DNHxJQjtGm/uvdbdGXCQg= +google.golang.org/api v0.269.0/go.mod h1:N8Wpcu23Tlccl0zSHEkcAZQKDLdquxK+l9r2LkwAauE= google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM= google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 h1:merA0rdPeUV3YIIfHHcH4qBkiQAc1nfCKSI7lB4cV2M= google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409/go.mod h1:fl8J1IvUjCilwZzQowmw2b7HQB2eAuYBabMXzWurF+I= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 h1:Jr5R2J6F6qWyzINc+4AM8t5pfUz6beZpHp678GNrMbE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= -google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= -google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260217215200-42d3e9bedb6d h1:t/LOSXPJ9R0B6fnZNyALBRfZBH0Uy0gT+uR+SJ6syqQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260217215200-42d3e9bedb6d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU= +google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/vendor/github.com/go-chi/chi/v5/middleware/route_headers.go b/vendor/github.com/go-chi/chi/v5/middleware/route_headers.go index 88743769..1c3334d3 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/route_headers.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/route_headers.go @@ -79,6 +79,7 @@ func (hr HeaderRouter) Handler(next http.Handler) http.Handler { if len(hr) == 0 { // skip if no routes set next.ServeHTTP(w, r) + return } // find first matching header route, and continue diff --git a/vendor/github.com/go-openapi/analysis/.editorconfig b/vendor/github.com/go-openapi/analysis/.editorconfig new file mode 100644 index 00000000..3152da69 --- /dev/null +++ b/vendor/github.com/go-openapi/analysis/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/vendor/github.com/go-openapi/analysis/.gitignore b/vendor/github.com/go-openapi/analysis/.gitignore index 87c3bd3e..885dc27a 100644 --- a/vendor/github.com/go-openapi/analysis/.gitignore +++ b/vendor/github.com/go-openapi/analysis/.gitignore @@ -1,5 +1,6 @@ -secrets.yml -coverage.out -coverage.txt +*.out *.cov .idea +.env +.mcp.json +.claude/ diff --git a/vendor/github.com/go-openapi/analysis/.golangci.yml b/vendor/github.com/go-openapi/analysis/.golangci.yml index 06190ac0..02edc1b9 100644 --- a/vendor/github.com/go-openapi/analysis/.golangci.yml +++ b/vendor/github.com/go-openapi/analysis/.golangci.yml @@ -2,34 +2,19 @@ version: "2" linters: default: all disable: - - cyclop - depguard - - errchkjson - - errorlint - - exhaustruct - - forcetypeassert - funlen - - gochecknoglobals - - gochecknoinits - - gocognit - - godot - godox - - gosmopolitan - - inamedparam - - intrange - - ireturn - - lll - - musttag - - nestif + - gomoddirectives + - exhaustruct - nlreturn - - noinlineerr - nonamedreturns + - noinlineerr - paralleltest - recvcheck - testpackage - thelper - tparallel - - unparam - varnamelen - whitespace - wrapcheck @@ -41,8 +26,17 @@ linters: goconst: min-len: 2 min-occurrences: 3 + cyclop: + max-complexity: 25 gocyclo: - min-complexity: 45 + min-complexity: 25 + gocognit: + min-complexity: 35 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 exclusions: generated: lax presets: @@ -58,6 +52,7 @@ formatters: enable: - gofmt - goimports + - gofumpt exclusions: generated: lax paths: diff --git a/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/analysis/CONTRIBUTORS.md b/vendor/github.com/go-openapi/analysis/CONTRIBUTORS.md new file mode 100644 index 00000000..cf8fcaa7 --- /dev/null +++ b/vendor/github.com/go-openapi/analysis/CONTRIBUTORS.md @@ -0,0 +1,27 @@ +# Contributors + +- Repository: ['go-openapi/analysis'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 15 | 202 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 99 | | +| @casualjim | 70 | | +| @keramix | 9 | | +| @youyuanwu | 8 | | +| @msample | 3 | | +| @kul-amr | 3 | | +| @mbohlool | 2 | | +| @Copilot | 1 | | +| @danielfbm | 1 | | +| @gregmarr | 1 | | +| @guillemj | 1 | | +| @knweiss | 1 | | +| @tklauser | 1 | | +| @cuishuang | 1 | | +| @ujjwalsh | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/analysis/README.md b/vendor/github.com/go-openapi/analysis/README.md index e005d4b3..96821d3e 100644 --- a/vendor/github.com/go-openapi/analysis/README.md +++ b/vendor/github.com/go-openapi/analysis/README.md @@ -1,22 +1,46 @@ -# OpenAPI analysis [![Build Status](https://github.com/go-openapi/analysis/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/analysis/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/analysis/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/analysis) +# analysis -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/analysis/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/analysis.svg)](https://pkg.go.dev/github.com/go-openapi/analysis) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/analysis)](https://goreportcard.com/report/github.com/go-openapi/analysis) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] +--- A foundational library to analyze an OAI specification document for easier reasoning about the content. -## What's inside? +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + +## Status + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/analysis +``` + +## What's inside * An analyzer providing methods to walk the functional content of a specification * A spec flattener producing a self-contained document bundle, while preserving `$ref`s * A spec merger ("mixin") to merge several spec documents into a primary spec * A spec "fixer" ensuring that response descriptions are non empty -[Documentation](https://pkg.go.dev/github.com/go-openapi/analysis) - ## FAQ * Does this library support OpenAPI 3? @@ -25,3 +49,79 @@ A foundational library to analyze an OAI specification document for easier reaso > This package currently only supports OpenAPI 2.0 (aka Swagger 2.0). > There is no plan to make it evolve toward supporting OpenAPI 3.x. > This [discussion thread](https://github.com/go-openapi/spec/issues/21) relates the full story. + +## Change log + +See + + + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + + + + + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/analysis/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/analysis/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/analysis/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/analysis/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/analysis +[vuln-scan-badge]: https://github.com/go-openapi/analysis/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/analysis/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/analysis/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/analysis/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fanalysis.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fanalysis + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/analysis +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/analysis +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/analysis +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/analysis + +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/analysis +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/analysis +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/analysis/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/analysis +[goversion-url]: https://github.com/go-openapi/analysis/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/analysis +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/analysis/latest diff --git a/vendor/github.com/go-openapi/analysis/SECURITY.md b/vendor/github.com/go-openapi/analysis/SECURITY.md new file mode 100644 index 00000000..6ceb159c --- /dev/null +++ b/vendor/github.com/go-openapi/analysis/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/analysis/analyzer.go b/vendor/github.com/go-openapi/analysis/analyzer.go index 4870ad07..1c91b8c5 100644 --- a/vendor/github.com/go-openapi/analysis/analyzer.go +++ b/vendor/github.com/go-openapi/analysis/analyzer.go @@ -164,13 +164,13 @@ func New(doc *spec.Swagger) *Spec { return a } -// SecurityRequirement is a representation of a security requirement for an operation +// SecurityRequirement is a representation of a security requirement for an operation. type SecurityRequirement struct { Name string Scopes []string } -// SecurityRequirementsFor gets the security requirements for the operation +// SecurityRequirementsFor gets the security requirements for the operation. func (s *Spec) SecurityRequirementsFor(operation *spec.Operation) [][]SecurityRequirement { if s.spec.Security == nil && operation.Security == nil { return nil @@ -204,7 +204,7 @@ func (s *Spec) SecurityRequirementsFor(operation *spec.Operation) [][]SecurityRe return result } -// SecurityDefinitionsForRequirements gets the matching security definitions for a set of requirements +// SecurityDefinitionsForRequirements gets the matching security definitions for a set of requirements. func (s *Spec) SecurityDefinitionsForRequirements(requirements []SecurityRequirement) map[string]spec.SecurityScheme { result := make(map[string]spec.SecurityScheme) @@ -219,7 +219,7 @@ func (s *Spec) SecurityDefinitionsForRequirements(requirements []SecurityRequire return result } -// SecurityDefinitionsFor gets the matching security definitions for a set of requirements +// SecurityDefinitionsFor gets the matching security definitions for a set of requirements. func (s *Spec) SecurityDefinitionsFor(operation *spec.Operation) map[string]spec.SecurityScheme { requirements := s.SecurityRequirementsFor(operation) if len(requirements) == 0 { @@ -250,7 +250,7 @@ func (s *Spec) SecurityDefinitionsFor(operation *spec.Operation) map[string]spec return result } -// ConsumesFor gets the mediatypes for the operation +// ConsumesFor gets the mediatypes for the operation. func (s *Spec) ConsumesFor(operation *spec.Operation) []string { if len(operation.Consumes) == 0 { cons := make(map[string]struct{}, len(s.spec.Consumes)) @@ -269,7 +269,7 @@ func (s *Spec) ConsumesFor(operation *spec.Operation) []string { return s.structMapKeys(cons) } -// ProducesFor gets the mediatypes for the operation +// ProducesFor gets the mediatypes for the operation. func (s *Spec) ProducesFor(operation *spec.Operation) []string { if len(operation.Produces) == 0 { prod := make(map[string]struct{}, len(s.spec.Produces)) @@ -306,7 +306,7 @@ func fieldNameFromParam(param *spec.Parameter) string { // whenever an error is encountered while resolving references // on parameters. // -// This function takes as input the spec.Parameter which triggered the +// This function takes as input the [spec.Parameter] which triggered the // error and the error itself. // // If the callback function returns false, the calling function should bail. @@ -329,7 +329,7 @@ func (s *Spec) ParametersFor(operationID string) []spec.Parameter { // Does not assume parameters properly resolve references or that // such references actually resolve to a parameter object. // -// Upon error, invoke a ErrorOnParamFunc callback with the erroneous +// Upon error, invoke a [ErrorOnParamFunc] callback with the erroneous // parameters. If the callback is set to nil, panics upon errors. func (s *Spec) SafeParametersFor(operationID string, callmeOnError ErrorOnParamFunc) []spec.Parameter { gatherParams := func(pi *spec.PathItem, op *spec.Operation) []spec.Parameter { @@ -337,7 +337,7 @@ func (s *Spec) SafeParametersFor(operationID string, callmeOnError ErrorOnParamF s.paramsAsMap(pi.Parameters, bag, callmeOnError) s.paramsAsMap(op.Parameters, bag, callmeOnError) - var res []spec.Parameter + res := make([]spec.Parameter, 0, len(bag)) for _, v := range bag { res = append(res, v) } @@ -388,7 +388,7 @@ func (s *Spec) ParamsFor(method, path string) map[string]spec.Parameter { // Does not assume parameters properly resolve references or that // such references actually resolve to a parameter object. // -// Upon error, invoke a ErrorOnParamFunc callback with the erroneous +// Upon error, invoke a [ErrorOnParamFunc] callback with the erroneous // parameters. If the callback is set to nil, panics upon errors. func (s *Spec) SafeParamsFor(method, path string, callmeOnError ErrorOnParamFunc) map[string]spec.Parameter { res := make(map[string]spec.Parameter) @@ -400,7 +400,7 @@ func (s *Spec) SafeParamsFor(method, path string, callmeOnError ErrorOnParamFunc return res } -// OperationForName gets the operation for the given id +// OperationForName gets the operation for the given id. func (s *Spec) OperationForName(operationID string) (string, string, *spec.Operation, bool) { for method, pathItem := range s.operations { for path, op := range pathItem { @@ -413,7 +413,7 @@ func (s *Spec) OperationForName(operationID string) (string, string, *spec.Opera return "", "", nil, false } -// OperationFor the given method and path +// OperationFor the given method and path. func (s *Spec) OperationFor(method, path string) (*spec.Operation, bool) { if mp, ok := s.operations[strings.ToUpper(method)]; ok { op, fn := mp[path] @@ -424,12 +424,12 @@ func (s *Spec) OperationFor(method, path string) (*spec.Operation, bool) { return nil, false } -// Operations gathers all the operations specified in the spec document +// Operations gathers all the operations specified in the spec document. func (s *Spec) Operations() map[string]map[string]*spec.Operation { return s.operations } -// AllPaths returns all the paths in the swagger spec +// AllPaths returns all the paths in the swagger spec. func (s *Spec) AllPaths() map[string]spec.PathItem { if s.spec == nil || s.spec.Paths == nil { return nil @@ -438,7 +438,7 @@ func (s *Spec) AllPaths() map[string]spec.PathItem { return s.spec.Paths.Paths } -// OperationIDs gets all the operation ids based on method an dpath +// OperationIDs gets all the operation ids based on method an dpath. func (s *Spec) OperationIDs() []string { if len(s.operations) == 0 { return nil @@ -458,7 +458,7 @@ func (s *Spec) OperationIDs() []string { return result } -// OperationMethodPaths gets all the operation ids based on method an dpath +// OperationMethodPaths gets all the operation ids based on method an dpath. func (s *Spec) OperationMethodPaths() []string { if len(s.operations) == 0 { return nil @@ -474,22 +474,22 @@ func (s *Spec) OperationMethodPaths() []string { return result } -// RequiredConsumes gets all the distinct consumes that are specified in the specification document +// RequiredConsumes gets all the distinct consumes that are specified in the specification document. func (s *Spec) RequiredConsumes() []string { return s.structMapKeys(s.consumes) } -// RequiredProduces gets all the distinct produces that are specified in the specification document +// RequiredProduces gets all the distinct produces that are specified in the specification document. func (s *Spec) RequiredProduces() []string { return s.structMapKeys(s.produces) } -// RequiredSecuritySchemes gets all the distinct security schemes that are specified in the swagger spec +// RequiredSecuritySchemes gets all the distinct security schemes that are specified in the swagger spec. func (s *Spec) RequiredSecuritySchemes() []string { return s.structMapKeys(s.authSchemes) } -// SchemaRef is a reference to a schema +// SchemaRef is a reference to a schema. type SchemaRef struct { Name string Ref spec.Ref @@ -498,7 +498,7 @@ type SchemaRef struct { } // SchemasWithAllOf returns schema references to all schemas that are defined -// with an allOf key +// with an allOf key. func (s *Spec) SchemasWithAllOf() (result []SchemaRef) { for _, v := range s.allOfs { result = append(result, v) @@ -507,7 +507,7 @@ func (s *Spec) SchemasWithAllOf() (result []SchemaRef) { return } -// AllDefinitions returns schema references for all the definitions that were discovered +// AllDefinitions returns schema references for all the definitions that were discovered. func (s *Spec) AllDefinitions() (result []SchemaRef) { for _, v := range s.allSchemas { result = append(result, v) @@ -516,7 +516,7 @@ func (s *Spec) AllDefinitions() (result []SchemaRef) { return } -// AllDefinitionReferences returns json refs for all the discovered schemas +// AllDefinitionReferences returns JSON references for all the discovered schemas. func (s *Spec) AllDefinitionReferences() (result []string) { for _, v := range s.references.schemas { result = append(result, v.String()) @@ -525,7 +525,7 @@ func (s *Spec) AllDefinitionReferences() (result []string) { return } -// AllParameterReferences returns json refs for all the discovered parameters +// AllParameterReferences returns JSON references for all the discovered parameters. func (s *Spec) AllParameterReferences() (result []string) { for _, v := range s.references.parameters { result = append(result, v.String()) @@ -534,7 +534,7 @@ func (s *Spec) AllParameterReferences() (result []string) { return } -// AllResponseReferences returns json refs for all the discovered responses +// AllResponseReferences returns JSON references for all the discovered responses. func (s *Spec) AllResponseReferences() (result []string) { for _, v := range s.references.responses { result = append(result, v.String()) @@ -543,7 +543,7 @@ func (s *Spec) AllResponseReferences() (result []string) { return } -// AllPathItemReferences returns the references for all the items +// AllPathItemReferences returns the references for all the items. func (s *Spec) AllPathItemReferences() (result []string) { for _, v := range s.references.pathItems { result = append(result, v.String()) @@ -564,7 +564,7 @@ func (s *Spec) AllItemsReferences() (result []string) { return } -// AllReferences returns all the references found in the document, with possible duplicates +// AllReferences returns all the references found in the document, with possible duplicates. func (s *Spec) AllReferences() (result []string) { for _, v := range s.references.allRefs { result = append(result, v.String()) @@ -573,7 +573,7 @@ func (s *Spec) AllReferences() (result []string) { return } -// AllRefs returns all the unique references found in the document +// AllRefs returns all the unique references found in the document. func (s *Spec) AllRefs() (result []spec.Ref) { set := make(map[string]struct{}) for _, v := range s.references.allRefs { @@ -592,61 +592,61 @@ func (s *Spec) AllRefs() (result []spec.Ref) { } // ParameterPatterns returns all the patterns found in parameters -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) ParameterPatterns() map[string]string { return cloneStringMap(s.patterns.parameters) } // HeaderPatterns returns all the patterns found in response headers -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) HeaderPatterns() map[string]string { return cloneStringMap(s.patterns.headers) } // ItemsPatterns returns all the patterns found in simple array items -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) ItemsPatterns() map[string]string { return cloneStringMap(s.patterns.items) } // SchemaPatterns returns all the patterns found in schemas -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) SchemaPatterns() map[string]string { return cloneStringMap(s.patterns.schemas) } // AllPatterns returns all the patterns found in the spec -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) AllPatterns() map[string]string { return cloneStringMap(s.patterns.allPatterns) } // ParameterEnums returns all the enums found in parameters -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) ParameterEnums() map[string][]any { return cloneEnumMap(s.enums.parameters) } // HeaderEnums returns all the enums found in response headers -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) HeaderEnums() map[string][]any { return cloneEnumMap(s.enums.headers) } // ItemsEnums returns all the enums found in simple array items -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) ItemsEnums() map[string][]any { return cloneEnumMap(s.enums.items) } // SchemaEnums returns all the enums found in schemas -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) SchemaEnums() map[string][]any { return cloneEnumMap(s.enums.schemas) } // AllEnums returns all the enums found in the spec -// the map is cloned to avoid accidental changes +// the map is cloned to avoid accidental changes. func (s *Spec) AllEnums() map[string][]any { return cloneEnumMap(s.enums.allEnums) } diff --git a/vendor/github.com/go-openapi/analysis/debug.go b/vendor/github.com/go-openapi/analysis/debug.go index d490eab6..8e777c43 100644 --- a/vendor/github.com/go-openapi/analysis/debug.go +++ b/vendor/github.com/go-openapi/analysis/debug.go @@ -9,4 +9,4 @@ import ( "github.com/go-openapi/analysis/internal/debug" ) -var debugLog = debug.GetLogger("analysis", os.Getenv("SWAGGER_DEBUG") != "") +var debugLog = debug.GetLogger("analysis", os.Getenv("SWAGGER_DEBUG") != "") //nolint:gochecknoglobals // it's okay to use a private global for logging diff --git a/vendor/github.com/go-openapi/analysis/doc.go b/vendor/github.com/go-openapi/analysis/doc.go index 9d41371a..9c4b165c 100644 --- a/vendor/github.com/go-openapi/analysis/doc.go +++ b/vendor/github.com/go-openapi/analysis/doc.go @@ -1,32 +1,31 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 -/* -Package analysis provides methods to work with a Swagger specification document from -package go-openapi/spec. - -## Analyzing a specification - -An analysed specification object (type Spec) provides methods to work with swagger definition. - -## Flattening or expanding a specification - -Flattening a specification bundles all remote $ref in the main spec document. -Depending on flattening options, additional preprocessing may take place: - - full flattening: replacing all inline complex constructs by a named entry in #/definitions - - expand: replace all $ref's in the document by their expanded content - -## Merging several specifications - -Mixin several specifications merges all Swagger constructs, and warns about found conflicts. - -## Fixing a specification - -Unmarshalling a specification with golang json unmarshalling may lead to -some unwanted result on present but empty fields. - -## Analyzing a Swagger schema - -Swagger schemas are analyzed to determine their complexity and qualify their content. -*/ +// Package analysis provides methods to work with a Swagger specification document from +// package go-openapi/spec. +// +// # Analyzing a specification +// +// An analysed specification object (type Spec) provides methods to work with swagger definition. +// +// # Flattening or expanding a specification +// +// Flattening a specification bundles all remote $ref in the main spec document. +// Depending on flattening options, additional preprocessing may take place: +// +// - full flattening: replacing all inline complex constructs by a named entry in #/definitions +// - expand: replace all $ref's in the document by their expanded content +// +// # Merging several specifications +// +// [Mixin] several specifications merges all Swagger constructs, and warns about found conflicts. +// +// # Fixing a specification +// +// Unmarshalling a specification with golang [json] unmarshalling may lead to +// some unwanted result on present but empty fields. +// +// # Analyzing a Swagger schema +// +// Swagger schemas are analyzed to determine their complexity and qualify their content. package analysis diff --git a/vendor/github.com/go-openapi/analysis/flatten.go b/vendor/github.com/go-openapi/analysis/flatten.go index 1c7a49c0..d7ee0064 100644 --- a/vendor/github.com/go-openapi/analysis/flatten.go +++ b/vendor/github.com/go-openapi/analysis/flatten.go @@ -21,7 +21,7 @@ import ( const definitionsPath = "#/definitions" -// newRef stores information about refs created during the flattening process +// newRef stores information about refs created during the flattening process. type newRef struct { key string newName string @@ -32,7 +32,7 @@ type newRef struct { parents []string } -// context stores intermediary results from flatten +// context stores intermediary results from flatten. type context struct { newRefs map[string]*newRef warnings []string @@ -52,13 +52,15 @@ func newContext() *context { // There is a minimal and a full flattening mode. // // Minimally flattening a spec means: +// // - Expanding parameters, responses, path items, parameter items and header items (references to schemas are left // unscathed) -// - Importing external (http, file) references so they become internal to the document +// - Importing external ([http], file) references so they become internal to the document // - Moving every JSON pointer to a $ref to a named definition (i.e. the reworked spec does not contain pointers // like "$ref": "#/definitions/myObject/allOfs/1") // // A minimally flattened spec thus guarantees the following properties: +// // - all $refs point to a local definition (i.e. '#/definitions/...') // - definitions are unique // @@ -70,6 +72,7 @@ func newContext() *context { // Minimal flattening is necessary and sufficient for codegen rendering using go-swagger. // // Fully flattening a spec means: +// // - Moving every complex inline schema to be a definition with an auto-generated name in a depth-first fashion. // // By complex, we mean every JSON object with some properties. @@ -80,6 +83,7 @@ func newContext() *context { // have been created. // // Available flattening options: +// // - Minimal: stops flattening after minimal $ref processing, leaving schema constructs untouched // - Expand: expand all $ref's in the document (inoperant if Minimal set to true) // - Verbose: croaks about name conflicts detected @@ -87,8 +91,9 @@ func newContext() *context { // // NOTE: expansion removes all $ref save circular $ref, which remain in place // -// TODO: additional options -// - ProgagateNameExtensions: ensure that created entries properly follow naming rules when their parent have set a +// Desirable future additions: additional options. +// +// - PropagateNameExtensions: ensure that created entries properly follow naming rules when their parent have set a // x-go-name extension // - LiftAllOfs: // - limit the flattening of allOf members when simple objects @@ -169,7 +174,7 @@ func expand(opts *FlattenOpts) error { } // normalizeRef strips the current file from any absolute file $ref. This works around issue go-openapi/spec#76: -// leading absolute file in $ref is stripped +// leading absolute file in $ref is stripped. func normalizeRef(opts *FlattenOpts) error { debugLog("normalizeRef") @@ -491,14 +496,25 @@ func stripPointersAndOAIGen(opts *FlattenOpts) error { // pointer and name resolution again. func stripOAIGen(opts *FlattenOpts) (bool, error) { debugLog("stripOAIGen") + // Ensure the spec analysis is fresh, as previous steps (namePointers, etc.) might have modified refs. + opts.Spec.reload() + replacedWithComplex := false // figure out referers of OAIGen definitions (doing it before the ref start mutating) - for _, r := range opts.flattenContext.newRefs { + // Sort keys to ensure deterministic processing order + sortedKeys := make([]string, 0, len(opts.flattenContext.newRefs)) + for k := range opts.flattenContext.newRefs { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + + for _, k := range sortedKeys { + r := opts.flattenContext.newRefs[k] updateRefParents(opts.Spec.references.allRefs, r) } - for k := range opts.flattenContext.newRefs { + for _, k := range sortedKeys { r := opts.flattenContext.newRefs[k] debugLog("newRefs[%s]: isOAIGen: %t, resolved: %t, name: %s, path:%s, #parents: %d, parents: %v, ref: %s", k, r.isOAIGen, r.resolved, r.newName, r.path, len(r.parents), r.parents, r.schema.Ref.String()) @@ -521,7 +537,7 @@ func stripOAIGen(opts *FlattenOpts) (bool, error) { return replacedWithComplex, nil } -// updateRefParents updates all parents of an updated $ref +// updateRefParents updates all parents of an updated $ref. func updateRefParents(allRefs map[string]spec.Ref, r *newRef) { if !r.isOAIGen || r.resolved { // bail on already resolved entries (avoid looping) return @@ -580,6 +596,19 @@ func stripOAIGenForRef(opts *FlattenOpts, k string, r *newRef) (bool, error) { replacedWithComplex = true } } + + // update parents of the target ref (pr[0]) if it is also a newRef (OAIGen) + // This ensures that if the target is later deleted/merged, it knows about these new referers. + for _, nr := range opts.flattenContext.newRefs { + if nr.path == pr[0] && nr.isOAIGen && !nr.resolved { + for _, p := range pr[1:] { + if !slices.Contains(nr.parents, p) { + nr.parents = append(nr.parents, p) + } + } + break + } + } } // remove OAIGen definition @@ -587,7 +616,15 @@ func stripOAIGenForRef(opts *FlattenOpts, k string, r *newRef) (bool, error) { delete(opts.Swagger().Definitions, path.Base(r.path)) // propagate changes in ref index for keys which have this one as a parent - for kk, value := range opts.flattenContext.newRefs { + // Sort keys to ensure deterministic update order + propagateKeys := make([]string, 0, len(opts.flattenContext.newRefs)) + for k := range opts.flattenContext.newRefs { + propagateKeys = append(propagateKeys, k) + } + sort.Strings(propagateKeys) + + for _, kk := range propagateKeys { + value := opts.flattenContext.newRefs[kk] if kk == k || !value.isOAIGen || value.resolved { continue } diff --git a/vendor/github.com/go-openapi/analysis/flatten_name.go b/vendor/github.com/go-openapi/analysis/flatten_name.go index 475b33c4..922cae55 100644 --- a/vendor/github.com/go-openapi/analysis/flatten_name.go +++ b/vendor/github.com/go-openapi/analysis/flatten_name.go @@ -17,7 +17,7 @@ import ( "github.com/go-openapi/swag/mangling" ) -// InlineSchemaNamer finds a new name for an inlined type +// InlineSchemaNamer finds a new name for an inlined type. type InlineSchemaNamer struct { Spec *spec.Swagger Operations map[string]operations.OpRef @@ -25,7 +25,7 @@ type InlineSchemaNamer struct { opts *FlattenOpts } -// Name yields a new name for the inline schema +// Name yields a new name for the inline schema. func (isn *InlineSchemaNamer) Name(key string, schema *spec.Schema, aschema *AnalyzedSchema) error { debugLog("naming inlined schema at %s", key) @@ -108,7 +108,7 @@ func (isn *InlineSchemaNamer) Name(key string, schema *spec.Schema, aschema *Ana return nil } -// uniqifyName yields a unique name for a definition +// uniqifyName yields a unique name for a definition. func uniqifyName(definitions spec.Definitions, name string) (string, bool) { isOAIGen := false if name == "" { @@ -244,7 +244,7 @@ func namesForDefinition(parts sortref.SplitKey) ([][]string, int) { return [][]string{}, 0 } -// partAdder knows how to interpret a schema when it comes to build a name from parts +// partAdder knows how to interpret a schema when it comes to build a name from parts. func partAdder(aschema *AnalyzedSchema) sortref.PartAdder { return func(part string) []string { segments := make([]string, 0, minSegments) diff --git a/vendor/github.com/go-openapi/analysis/flatten_options.go b/vendor/github.com/go-openapi/analysis/flatten_options.go index d8fc25cf..23a57ea1 100644 --- a/vendor/github.com/go-openapi/analysis/flatten_options.go +++ b/vendor/github.com/go-openapi/analysis/flatten_options.go @@ -35,7 +35,7 @@ type FlattenOpts struct { _ struct{} // require keys } -// ExpandOpts creates a spec.ExpandOptions to configure expanding a specification document. +// ExpandOpts creates a spec.[spec.ExpandOptions] to configure expanding a specification document. func (f *FlattenOpts) ExpandOpts(skipSchemas bool) *spec.ExpandOptions { return &spec.ExpandOptions{ RelativeBase: f.BasePath, @@ -44,13 +44,13 @@ func (f *FlattenOpts) ExpandOpts(skipSchemas bool) *spec.ExpandOptions { } } -// Swagger gets the swagger specification for this flatten operation +// Swagger gets the swagger specification for this flatten operation. func (f *FlattenOpts) Swagger() *spec.Swagger { return f.Spec.spec } // croak logs notifications and warnings about valid, but possibly unwanted constructs resulting -// from flattening a spec +// from flattening a spec. func (f *FlattenOpts) croak() { if !f.Verbose { return diff --git a/vendor/github.com/go-openapi/analysis/go.work b/vendor/github.com/go-openapi/analysis/go.work new file mode 100644 index 00000000..1794cfc9 --- /dev/null +++ b/vendor/github.com/go-openapi/analysis/go.work @@ -0,0 +1,6 @@ +go 1.24.0 + +use ( + . + ./internal/testintegration +) diff --git a/vendor/github.com/go-openapi/analysis/go.work.sum b/vendor/github.com/go-openapi/analysis/go.work.sum new file mode 100644 index 00000000..b767fb61 --- /dev/null +++ b/vendor/github.com/go-openapi/analysis/go.work.sum @@ -0,0 +1,29 @@ +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30 h1:BHT1/DKsYDGkUgQ2jmMaozVcdk+sVfz0+1ZJq4zkWgw= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= +go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss= +go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= +golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= +golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= +golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= +golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= diff --git a/vendor/github.com/go-openapi/analysis/internal/debug/debug.go b/vendor/github.com/go-openapi/analysis/internal/debug/debug.go index 03e0d32e..d3fa08d3 100644 --- a/vendor/github.com/go-openapi/analysis/internal/debug/debug.go +++ b/vendor/github.com/go-openapi/analysis/internal/debug/debug.go @@ -11,11 +11,9 @@ import ( "runtime" ) -var ( - output = os.Stdout -) +var output = os.Stdout //nolint:gochecknoglobals // this is on purpose to be overridable during tests -// GetLogger provides a prefix debug logger +// GetLogger provides a prefix debug logger. func GetLogger(prefix string, debug bool) func(string, ...any) { if debug { logger := log.New(output, prefix+":", log.LstdFlags) diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go b/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go index 320a50bf..afeef20e 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go @@ -17,8 +17,9 @@ import ( // NOTE: does not support JSONschema ID for $ref (we assume we are working with swagger specs here). // // NOTE(windows): -// * refs are assumed to have been normalized with drive letter lower cased (from go-openapi/spec) -// * "/ in paths may appear as escape sequences +// +// - refs are assumed to have been normalized with drive letter lower cased (from go-openapi/spec) +// - "/ in paths may appear as escape sequences. func RebaseRef(baseRef string, ref string) string { baseRef, _ = url.PathUnescape(baseRef) ref, _ = url.PathUnescape(ref) @@ -69,8 +70,9 @@ func RebaseRef(baseRef string, ref string) string { // Path renders absolute path on remote file refs // // NOTE(windows): -// * refs are assumed to have been normalized with drive letter lower cased (from go-openapi/spec) -// * "/ in paths may appear as escape sequences +// +// - refs are assumed to have been normalized with drive letter lower cased (from go-openapi/spec) +// - "/ in paths may appear as escape sequences. func Path(ref spec.Ref, basePath string) string { uri, _ := url.PathUnescape(ref.String()) if ref.HasFragmentOnly || filepath.IsAbs(uri) { diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go b/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go index 940c46a9..325e2751 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go @@ -14,12 +14,12 @@ import ( "github.com/go-openapi/swag/mangling" ) -// AllOpRefsByRef returns an index of sortable operations +// AllOpRefsByRef returns an index of sortable operations. func AllOpRefsByRef(specDoc Provider, operationIDs []string) map[string]OpRef { return OpRefsByRef(GatherOperations(specDoc, operationIDs)) } -// OpRefsByRef indexes a map of sortable operations +// OpRefsByRef indexes a map of sortable operations. func OpRefsByRef(oprefs map[string]OpRef) map[string]OpRef { result := make(map[string]OpRef, len(oprefs)) for _, v := range oprefs { @@ -29,7 +29,7 @@ func OpRefsByRef(oprefs map[string]OpRef) map[string]OpRef { return result } -// OpRef is an indexable, sortable operation +// OpRef is an indexable, sortable operation. type OpRef struct { Method string Path string @@ -39,19 +39,19 @@ type OpRef struct { Ref spec.Ref } -// OpRefs is a sortable collection of operations +// OpRefs is a sortable collection of operations. type OpRefs []OpRef func (o OpRefs) Len() int { return len(o) } func (o OpRefs) Swap(i, j int) { o[i], o[j] = o[j], o[i] } func (o OpRefs) Less(i, j int) bool { return o[i].Key < o[j].Key } -// Provider knows how to collect operations from a spec +// Provider knows how to collect operations from a spec. type Provider interface { Operations() map[string]map[string]*spec.Operation } -// GatherOperations builds a map of sorted operations from a spec +// GatherOperations builds a map of sorted operations from a spec. func GatherOperations(specDoc Provider, operationIDs []string) map[string]OpRef { var oprefs OpRefs mangler := mangling.NewNameMangler() diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go index d7c28b88..b2a8a93b 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go @@ -58,7 +58,7 @@ func ErrCyclicChain(key string) error { } func ErrInvalidPointerType(key string, value any, err error) error { - return fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T (%v): %w", + return fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T (%w): %w", key, value, err, ErrReplace, ) } diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go index 61c13f7e..b4c0fdd4 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go @@ -22,9 +22,10 @@ const ( allocMediumMap = 64 ) +//nolint:gochecknoglobals // it's okay to use a private global for logging var debugLog = debug.GetLogger("analysis/flatten/replace", os.Getenv("SWAGGER_DEBUG") != "") -// RewriteSchemaToRef replaces a schema with a Ref +// RewriteSchemaToRef replaces a schema with a Ref. func RewriteSchemaToRef(sp *spec.Swagger, key string, ref spec.Ref) error { debugLog("rewriting schema to ref for %s with %s", key, ref.String()) _, value, err := getPointerFromKey(sp, key) @@ -142,7 +143,7 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error { return nil } -// getPointerFromKey retrieves the content of the JSON pointer "key" +// getPointerFromKey retrieves the content of the JSON pointer "key". func getPointerFromKey(sp any, key string) (string, any, error) { switch sp.(type) { case *spec.Schema: @@ -154,7 +155,10 @@ func getPointerFromKey(sp any, key string) (string, any, error) { return "", sp, nil } // unescape chars in key, e.g. "{}" from path params - pth, _ := url.PathUnescape(key[1:]) + pth, err := url.PathUnescape(key[1:]) + if err != nil { + return "", nil, errors.Join(err, ErrReplace) + } ptr, err := jsonpointer.New(pth) if err != nil { return "", nil, errors.Join(err, ErrReplace) @@ -170,7 +174,7 @@ func getPointerFromKey(sp any, key string) (string, any, error) { return pth, value, nil } -// getParentFromKey retrieves the container of the JSON pointer "key" +// getParentFromKey retrieves the container of the JSON pointer "key". func getParentFromKey(sp any, key string) (string, string, any, error) { switch sp.(type) { case *spec.Schema: @@ -196,7 +200,7 @@ func getParentFromKey(sp any, key string) (string, string, any, error) { return parent, entry, pvalue, nil } -// UpdateRef replaces a ref by another one +// UpdateRef replaces a ref by another one. func UpdateRef(sp any, key string, ref spec.Ref) error { switch sp.(type) { case *spec.Schema: @@ -265,7 +269,7 @@ func UpdateRef(sp any, key string, ref spec.Ref) error { return nil } -// UpdateRefWithSchema replaces a ref with a schema (i.e. re-inline schema) +// UpdateRefWithSchema replaces a ref with a schema (i.e. re-inline schema). func UpdateRefWithSchema(sp *spec.Swagger, key string, sch *spec.Schema) error { debugLog("updating ref for %s with schema", key) pth, value, err := getPointerFromKey(sp, key) @@ -324,7 +328,7 @@ func UpdateRefWithSchema(sp *spec.Swagger, key string, sch *spec.Schema) error { return nil } -// DeepestRefResult holds the results from DeepestRef analysis +// DeepestRefResult holds the results from [DeepestRef] analysis. type DeepestRefResult struct { Ref spec.Ref Schema *spec.Schema @@ -332,10 +336,13 @@ type DeepestRefResult struct { } // DeepestRef finds the first definition ref, from a cascade of nested refs which are not definitions. +// // - if no definition is found, returns the deepest ref. // - pointers to external files are expanded // // NOTE: all external $ref's are assumed to be already expanded at this stage. +// +//nolint:gocognit,gocyclo,cyclop // definitely needs a refactoring, in a follow-up PR func DeepestRef(sp *spec.Swagger, opts *spec.ExpandOptions, ref spec.Ref) (*DeepestRefResult, error) { if !ref.HasFragmentOnly { // we found an external $ref, which is odd at this stage: @@ -392,11 +399,13 @@ DOWNREF: case spec.Response: // a pointer points to a schema initially marshalled in responses section... // Attempt to convert this to a schema. If this fails, the spec is invalid - asJSON, _ := refable.MarshalJSON() + asJSON, err := refable.MarshalJSON() + if err != nil { + return nil, ErrInvalidPointerType(currentRef.String(), value, err) + } var asSchema spec.Schema - err := asSchema.UnmarshalJSON(asJSON) - if err != nil { + if err = asSchema.UnmarshalJSON(asJSON); err != nil { return nil, ErrInvalidPointerType(currentRef.String(), value, err) } warnings = append(warnings, fmt.Sprintf("found $ref %q (response) interpreted as schema", currentRef.String())) @@ -409,9 +418,12 @@ DOWNREF: case spec.Parameter: // a pointer points to a schema initially marshalled in parameters section... // Attempt to convert this to a schema. If this fails, the spec is invalid - asJSON, _ := refable.MarshalJSON() + asJSON, err := refable.MarshalJSON() + if err != nil { + return nil, ErrInvalidPointerType(currentRef.String(), value, err) + } var asSchema spec.Schema - if err := asSchema.UnmarshalJSON(asJSON); err != nil { + if err = asSchema.UnmarshalJSON(asJSON); err != nil { return nil, ErrInvalidPointerType(currentRef.String(), value, err) } @@ -428,9 +440,12 @@ DOWNREF: break DOWNREF } - asJSON, _ := json.Marshal(refable) + asJSON, err := json.Marshal(refable) + if err != nil { + return nil, ErrInvalidPointerType(currentRef.String(), value, err) + } var asSchema spec.Schema - if err := asSchema.UnmarshalJSON(asJSON); err != nil { + if err = asSchema.UnmarshalJSON(asJSON); err != nil { return nil, ErrInvalidPointerType(currentRef.String(), value, err) } warnings = append(warnings, fmt.Sprintf("found $ref %q (%T) interpreted as schema", currentRef.String(), refable)) diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go b/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go index 7e9fb9f0..59855ef0 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go @@ -12,7 +12,7 @@ import ( const allocLargeMap = 150 -// Save registers a schema as an entry in spec #/definitions +// Save registers a schema as an entry in spec #/definitions. func Save(sp *spec.Swagger, name string, schema *spec.Schema) { if schema == nil { return @@ -25,7 +25,7 @@ func Save(sp *spec.Swagger, name string, schema *spec.Schema) { sp.Definitions[name] = *schema } -// Clone deep-clones a schema +// Clone deep-clones a schema. func Clone(schema *spec.Schema) *spec.Schema { var sch spec.Schema _ = jsonutils.FromDynamicJSON(schema, &sch) diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go index a5db0249..363bb19e 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go @@ -20,12 +20,8 @@ const ( definitions = "definitions" ) +//nolint:gochecknoglobals // it's okay to store small indexes like this as private globals var ( - ignoredKeys map[string]struct{} - validMethods map[string]struct{} -) - -func init() { ignoredKeys = map[string]struct{}{ "schema": {}, "properties": {}, @@ -43,15 +39,15 @@ func init() { "PUT": {}, "DELETE": {}, } -} +) -// Key represent a key item constructed from /-separated segments +// Key represent a key item constructed from /-separated segments. type Key struct { Segments int Key string } -// Keys is a sortable collable collection of Keys +// Keys is a sortable collable collection of Keys. type Keys []Key func (k Keys) Len() int { return len(k) } @@ -60,7 +56,7 @@ func (k Keys) Less(i, j int) bool { return k[i].Segments > k[j].Segments || (k[i].Segments == k[j].Segments && k[i].Key < k[j].Key) } -// KeyParts construct a SplitKey with all its /-separated segments decomposed. It is sortable. +// KeyParts construct a [SplitKey] with all its /-separated segments decomposed. It is sortable. func KeyParts(key string) SplitKey { var res []string for part := range strings.SplitSeq(key[1:], "/") { @@ -75,12 +71,12 @@ func KeyParts(key string) SplitKey { // SplitKey holds of the parts of a /-separated key, so that their location may be determined. type SplitKey []string -// IsDefinition is true when the split key is in the #/definitions section of a spec +// IsDefinition is true when the split key is in the #/definitions section of a spec. func (s SplitKey) IsDefinition() bool { return len(s) > 1 && s[0] == definitions } -// DefinitionName yields the name of the definition +// DefinitionName yields the name of the definition. func (s SplitKey) DefinitionName() string { if !s.IsDefinition() { return "" @@ -89,10 +85,10 @@ func (s SplitKey) DefinitionName() string { return s[1] } -// PartAdder know how to construct the components of a new name +// PartAdder know how to construct the components of a new name. type PartAdder func(string) []string -// BuildName builds a name from segments +// BuildName builds a name from segments. func (s SplitKey) BuildName(segments []string, startIndex int, adder PartAdder) string { for i, part := range s[startIndex:] { if _, ignored := ignoredKeys[part]; !ignored || s.isKeyName(startIndex+i) { @@ -103,42 +99,42 @@ func (s SplitKey) BuildName(segments []string, startIndex int, adder PartAdder) return strings.Join(segments, " ") } -// IsOperation is true when the split key is in the operations section +// IsOperation is true when the split key is in the operations section. func (s SplitKey) IsOperation() bool { return len(s) > 1 && s[0] == paths } -// IsSharedOperationParam is true when the split key is in the parameters section of a path +// IsSharedOperationParam is true when the split key is in the parameters section of a path. func (s SplitKey) IsSharedOperationParam() bool { return len(s) > 2 && s[0] == paths && s[2] == parameters } -// IsSharedParam is true when the split key is in the #/parameters section of a spec +// IsSharedParam is true when the split key is in the #/parameters section of a spec. func (s SplitKey) IsSharedParam() bool { return len(s) > 1 && s[0] == parameters } -// IsOperationParam is true when the split key is in the parameters section of an operation +// IsOperationParam is true when the split key is in the parameters section of an operation. func (s SplitKey) IsOperationParam() bool { return len(s) > 3 && s[0] == paths && s[3] == parameters } -// IsOperationResponse is true when the split key is in the responses section of an operation +// IsOperationResponse is true when the split key is in the responses section of an operation. func (s SplitKey) IsOperationResponse() bool { return len(s) > 3 && s[0] == paths && s[3] == responses } -// IsSharedResponse is true when the split key is in the #/responses section of a spec +// IsSharedResponse is true when the split key is in the #/responses section of a spec. func (s SplitKey) IsSharedResponse() bool { return len(s) > 1 && s[0] == responses } -// IsDefaultResponse is true when the split key is the default response for an operation +// IsDefaultResponse is true when the split key is the default response for an operation. func (s SplitKey) IsDefaultResponse() bool { return len(s) > 4 && s[0] == paths && s[3] == responses && s[4] == "default" } -// IsStatusCodeResponse is true when the split key is an operation response with a status code +// IsStatusCodeResponse is true when the split key is an operation response with a status code. func (s SplitKey) IsStatusCodeResponse() bool { isInt := func() bool { _, err := strconv.Atoi(s[4]) @@ -149,7 +145,7 @@ func (s SplitKey) IsStatusCodeResponse() bool { return len(s) > 4 && s[0] == paths && s[3] == responses && isInt() } -// ResponseName yields either the status code or "Default" for a response +// ResponseName yields either the status code or "Default" for a response. func (s SplitKey) ResponseName() string { if s.IsStatusCodeResponse() { code, _ := strconv.Atoi(s[4]) @@ -164,7 +160,7 @@ func (s SplitKey) ResponseName() string { return "" } -// PathItemRef constructs a $ref object from a split key of the form /{path}/{method} +// PathItemRef constructs a $ref object from a split key of the form /{path}/{method}. func (s SplitKey) PathItemRef() spec.Ref { const minValidPathItems = 3 if len(s) < minValidPathItems { @@ -179,7 +175,7 @@ func (s SplitKey) PathItemRef() spec.Ref { return spec.MustCreateRef("#" + path.Join("/", paths, jsonpointer.Escape(pth), strings.ToUpper(method))) } -// PathRef constructs a $ref object from a split key of the form /paths/{reference} +// PathRef constructs a $ref object from a split key of the form /paths/{reference}. func (s SplitKey) PathRef() spec.Ref { if !s.IsOperation() { return spec.Ref{} diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go index ceac7137..e4ad07b0 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go @@ -4,7 +4,9 @@ package sortref import ( + "iter" "reflect" + "slices" "sort" "strings" @@ -12,10 +14,6 @@ import ( "github.com/go-openapi/spec" ) -var depthGroupOrder = []string{ - "sharedParam", "sharedResponse", "sharedOpParam", "opParam", "codeResponse", "defaultResponse", "definition", -} - type mapIterator struct { len int mapIter *reflect.MapIter @@ -42,7 +40,7 @@ func mustMapIterator(anyMap any) *mapIterator { // DepthFirst sorts a map of anything. It groups keys by category // (shared params, op param, statuscode response, default response, definitions) // sort groups internally by number of parts in the key and lexical names -// flatten groups into a single list of keys +// flatten groups into a single list of keys. func DepthFirst(in any) []string { iterator := mustMapIterator(in) sorted := make([]string, 0, iterator.Len()) @@ -77,7 +75,7 @@ func DepthFirst(in any) []string { grouped[pk] = append(grouped[pk], Key{Segments: len(split), Key: k}) } - for _, pk := range depthGroupOrder { + for pk := range depthGroupOrder() { res := grouped[pk] sort.Sort(res) @@ -89,6 +87,12 @@ func DepthFirst(in any) []string { return sorted } +func depthGroupOrder() iter.Seq[string] { + return slices.Values([]string{ + "sharedParam", "sharedResponse", "sharedOpParam", "opParam", "codeResponse", "defaultResponse", "definition", + }) +} + // topMostRefs is able to sort refs by hierarchical then lexicographic order, // yielding refs ordered breadth-first. type topmostRefs []string @@ -104,7 +108,7 @@ func (k topmostRefs) Less(i, j int) bool { return li < lj } -// TopmostFirst sorts references by depth +// TopmostFirst sorts references by depth. func TopmostFirst(refs []string) []string { res := topmostRefs(refs) sort.Sort(res) @@ -112,13 +116,13 @@ func TopmostFirst(refs []string) []string { return res } -// RefRevIdx is a reverse index for references +// RefRevIdx is a reverse index for references. type RefRevIdx struct { Ref spec.Ref Keys []string } -// ReverseIndex builds a reverse index for references in schemas +// ReverseIndex builds a reverse index for references in schemas. func ReverseIndex(schemas map[string]spec.Ref, basePath string) map[string]RefRevIdx { collected := make(map[string]RefRevIdx) for key, schRef := range schemas { diff --git a/vendor/github.com/go-openapi/analysis/mixin.go b/vendor/github.com/go-openapi/analysis/mixin.go index cc5c3923..a7a9306c 100644 --- a/vendor/github.com/go-openapi/analysis/mixin.go +++ b/vendor/github.com/go-openapi/analysis/mixin.go @@ -18,12 +18,13 @@ import ( // needed. // // The following parts of primary are subject to merge, filling empty details +// // - Info // - BasePath // - Host // - ExternalDocs // -// Consider calling FixEmptyResponseDescriptions() on the modified primary +// Consider calling [FixEmptyResponseDescriptions]() on the modified primary // if you read them from storage and they are valid to start with. // // Entries in "paths", "definitions", "parameters" and "responses" are @@ -39,7 +40,7 @@ import ( // etc). Ensure they are canonical if your downstream tools do // key normalization of any form. // -// Merging schemes (http, https), and consumers/producers do not account for +// Merging schemes ([http], https), and consumers/producers do not account for // collisions. func Mixin(primary *spec.Swagger, mixins ...*spec.Swagger) []string { skipped := make([]string, 0, len(mixins)) diff --git a/vendor/github.com/go-openapi/analysis/schema.go b/vendor/github.com/go-openapi/analysis/schema.go index 039dac15..bedea652 100644 --- a/vendor/github.com/go-openapi/analysis/schema.go +++ b/vendor/github.com/go-openapi/analysis/schema.go @@ -8,7 +8,7 @@ import ( "github.com/go-openapi/strfmt" ) -// SchemaOpts configures the schema analyzer +// SchemaOpts configures the schema analyzer. type SchemaOpts struct { Schema *spec.Schema Root any @@ -52,7 +52,7 @@ func Schema(opts SchemaOpts) (*AnalyzedSchema, error) { return a, nil } -// AnalyzedSchema indicates what the schema represents +// AnalyzedSchema indicates what the schema represents. type AnalyzedSchema struct { schema *spec.Schema root any @@ -78,7 +78,7 @@ type AnalyzedSchema struct { IsEnum bool } -// Inherits copies value fields from other onto this schema +// Inherits copies value fields from other onto this schema. func (a *AnalyzedSchema) inherits(other *AnalyzedSchema) { if other == nil { return diff --git a/vendor/github.com/go-openapi/errors/.gitignore b/vendor/github.com/go-openapi/errors/.gitignore index 9a8da7e5..9364443a 100644 --- a/vendor/github.com/go-openapi/errors/.gitignore +++ b/vendor/github.com/go-openapi/errors/.gitignore @@ -1,3 +1,7 @@ -secrets.yml *.out +*.cov +.idea +.env +.mcp.json +.claude/ settings.local.json diff --git a/vendor/github.com/go-openapi/errors/.golangci.yml b/vendor/github.com/go-openapi/errors/.golangci.yml index fdae591b..e2c14be8 100644 --- a/vendor/github.com/go-openapi/errors/.golangci.yml +++ b/vendor/github.com/go-openapi/errors/.golangci.yml @@ -12,6 +12,7 @@ linters: - paralleltest - recvcheck - testpackage + - thelper - tparallel - varnamelen - whitespace @@ -40,6 +41,10 @@ linters: - common-false-positives - legacy - std-error-handling + rules: + - linters: + - revive + text: "avoid package names that conflict with Go standard library package names" paths: - third_party$ - builtin$ diff --git a/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/errors/CONTRIBUTORS.md b/vendor/github.com/go-openapi/errors/CONTRIBUTORS.md index eb018f8a..d49e377a 100644 --- a/vendor/github.com/go-openapi/errors/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/errors/CONTRIBUTORS.md @@ -4,21 +4,22 @@ | Total Contributors | Total Contributions | | --- | --- | -| 12 | 105 | +| 13 | 110 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | -| @casualjim | 58 | https://github.com/go-openapi/errors/commits?author=casualjim | -| @fredbi | 32 | https://github.com/go-openapi/errors/commits?author=fredbi | -| @youyuanwu | 5 | https://github.com/go-openapi/errors/commits?author=youyuanwu | -| @alexandear | 2 | https://github.com/go-openapi/errors/commits?author=alexandear | -| @fiorix | 1 | https://github.com/go-openapi/errors/commits?author=fiorix | -| @ligustah | 1 | https://github.com/go-openapi/errors/commits?author=ligustah | -| @artemseleznev | 1 | https://github.com/go-openapi/errors/commits?author=artemseleznev | -| @gautierdelorme | 1 | https://github.com/go-openapi/errors/commits?author=gautierdelorme | -| @guillemj | 1 | https://github.com/go-openapi/errors/commits?author=guillemj | -| @maxatome | 1 | https://github.com/go-openapi/errors/commits?author=maxatome | -| @Simon-Li | 1 | https://github.com/go-openapi/errors/commits?author=Simon-Li | -| @ujjwalsh | 1 | https://github.com/go-openapi/errors/commits?author=ujjwalsh | +| @casualjim | 58 | | +| @fredbi | 36 | | +| @youyuanwu | 5 | | +| @alexandear | 2 | | +| @fiorix | 1 | | +| @ligustah | 1 | | +| @artemseleznev | 1 | | +| @gautierdelorme | 1 | | +| @guillemj | 1 | | +| @maxatome | 1 | | +| @Simon-Li | 1 | | +| @aokumasan | 1 | | +| @ujjwalsh | 1 | | _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/errors/README.md b/vendor/github.com/go-openapi/errors/README.md index 6102c6b5..d9f4a3f1 100644 --- a/vendor/github.com/go-openapi/errors/README.md +++ b/vendor/github.com/go-openapi/errors/README.md @@ -51,7 +51,9 @@ errNotImplemented := NotImplemented("method: %s", url) See ## Licensing @@ -59,12 +61,9 @@ See This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). - ## Other documentation @@ -95,23 +94,19 @@ Maintainers can cut a new release by either: [release-badge]: https://badge.fury.io/gh/go-openapi%2Ferrors.svg [release-url]: https://badge.fury.io/gh/go-openapi%2Ferrors -[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Ferrors.svg -[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Ferrors [gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/errors [gocard-url]: https://goreportcard.com/report/github.com/go-openapi/errors [codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/errors [codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/errors -[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F -[doc-url]: https://goswagger.io/go-openapi [godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/errors [godoc-url]: http://pkg.go.dev/github.com/go-openapi/errors [slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png [slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM [slack-url]: https://goswagger.slack.com/archives/C04R30YMU [discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue -[discord-url]: https://discord.gg/DrafRmZx +[discord-url]: https://discord.gg/twZ9BwT3 [license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg diff --git a/vendor/github.com/go-openapi/errors/SECURITY.md b/vendor/github.com/go-openapi/errors/SECURITY.md index 2a7b6f09..6ceb159c 100644 --- a/vendor/github.com/go-openapi/errors/SECURITY.md +++ b/vendor/github.com/go-openapi/errors/SECURITY.md @@ -6,14 +6,32 @@ This policy outlines the commitment and practices of the go-openapi maintainers | Version | Supported | | ------- | ------------------ | -| 0.22.x | :white_check_mark: | +| 0.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. ## Reporting a vulnerability If you become aware of a security vulnerability that affects the current repository, -please report it privately to the maintainers. +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. -Please follow the instructions provided by github to -[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". -TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/errors/api.go b/vendor/github.com/go-openapi/errors/api.go index cb139416..d2b4427a 100644 --- a/vendor/github.com/go-openapi/errors/api.go +++ b/vendor/github.com/go-openapi/errors/api.go @@ -146,7 +146,7 @@ func MethodNotAllowed(requested string, allow []string) Error { } } -// ServeError implements the http error handler interface. +// ServeError implements the [http] error handler interface. func ServeError(rw http.ResponseWriter, r *http.Request, err error) { rw.Header().Set("Content-Type", "application/json") diff --git a/vendor/github.com/go-openapi/errors/doc.go b/vendor/github.com/go-openapi/errors/doc.go index b4627f30..208c7405 100644 --- a/vendor/github.com/go-openapi/errors/doc.go +++ b/vendor/github.com/go-openapi/errors/doc.go @@ -1,15 +1,13 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 -/* -Package errors provides an Error interface and several concrete types -implementing this interface to manage API errors and JSON-schema validation -errors. - -A middleware handler ServeError() is provided to serve the errors types -it defines. - -It is used throughout the various go-openapi toolkit libraries -(https://github.com/go-openapi). -*/ +// Package errors provides an Error interface and several concrete types +// implementing this interface to manage API errors and JSON-schema validation +// errors. +// +// A middleware handler [ServeError]() is provided to serve the errors types +// it defines. +// +// It is used throughout the various go-openapi toolkit libraries. +// (https://github.com/go-openapi). package errors diff --git a/vendor/github.com/go-openapi/jsonpointer/.gitignore b/vendor/github.com/go-openapi/jsonpointer/.gitignore index 59cd2948..885dc27a 100644 --- a/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ b/vendor/github.com/go-openapi/jsonpointer/.gitignore @@ -2,3 +2,5 @@ *.cov .idea .env +.mcp.json +.claude/ diff --git a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml index fdae591b..dc7c9605 100644 --- a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml +++ b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml @@ -12,6 +12,7 @@ linters: - paralleltest - recvcheck - testpackage + - thelper - tparallel - varnamelen - whitespace diff --git a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md index 03c09831..2ebebedc 100644 --- a/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md @@ -4,21 +4,21 @@ | Total Contributors | Total Contributions | | --- | --- | -| 12 | 95 | +| 12 | 101 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | -| @fredbi | 48 | https://github.com/go-openapi/jsonpointer/commits?author=fredbi | -| @casualjim | 33 | https://github.com/go-openapi/jsonpointer/commits?author=casualjim | -| @magodo | 3 | https://github.com/go-openapi/jsonpointer/commits?author=magodo | -| @youyuanwu | 3 | https://github.com/go-openapi/jsonpointer/commits?author=youyuanwu | -| @gaiaz-iusipov | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gaiaz-iusipov | -| @gbjk | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gbjk | -| @gordallott | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gordallott | -| @ianlancetaylor | 1 | https://github.com/go-openapi/jsonpointer/commits?author=ianlancetaylor | -| @mfleader | 1 | https://github.com/go-openapi/jsonpointer/commits?author=mfleader | -| @Neo2308 | 1 | https://github.com/go-openapi/jsonpointer/commits?author=Neo2308 | -| @olivierlemasle | 1 | https://github.com/go-openapi/jsonpointer/commits?author=olivierlemasle | -| @testwill | 1 | https://github.com/go-openapi/jsonpointer/commits?author=testwill | +| @fredbi | 54 | | +| @casualjim | 33 | | +| @magodo | 3 | | +| @youyuanwu | 3 | | +| @gaiaz-iusipov | 1 | | +| @gbjk | 1 | | +| @gordallott | 1 | | +| @ianlancetaylor | 1 | | +| @mfleader | 1 | | +| @Neo2308 | 1 | | +| @olivierlemasle | 1 | | +| @testwill | 1 | | _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md index b61b63fd..c52803e2 100644 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ b/vendor/github.com/go-openapi/jsonpointer/README.md @@ -8,12 +8,22 @@ [![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] -[![GoDoc][godoc-badge]][godoc-url] [![Slack Channel][slack-logo]![slack-badge]][slack-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] --- An implementation of JSON Pointer for golang, which supports go `struct`. +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + ## Status API is stable. @@ -124,21 +134,20 @@ Maintainers can cut a new release by either: [release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer.svg [release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer -[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonpointer.svg -[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonpointer [gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonpointer [gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonpointer [codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonpointer [codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonpointer -[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F -[doc-url]: https://goswagger.io/go-openapi [godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer [godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonpointer [slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png [slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM [slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + [license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg [license-url]: https://github.com/go-openapi/jsonpointer/?tab=Apache-2.0-1-ov-file#readme diff --git a/vendor/github.com/go-openapi/jsonpointer/SECURITY.md b/vendor/github.com/go-openapi/jsonpointer/SECURITY.md index 2a7b6f09..1fea2c57 100644 --- a/vendor/github.com/go-openapi/jsonpointer/SECURITY.md +++ b/vendor/github.com/go-openapi/jsonpointer/SECURITY.md @@ -6,14 +6,32 @@ This policy outlines the commitment and practices of the go-openapi maintainers | Version | Supported | | ------- | ------------------ | -| 0.22.x | :white_check_mark: | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. ## Reporting a vulnerability If you become aware of a security vulnerability that affects the current repository, -please report it privately to the maintainers. +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. -Please follow the instructions provided by github to -[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". -TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/jsonreference/.cliff.toml b/vendor/github.com/go-openapi/jsonreference/.cliff.toml deleted file mode 100644 index 702629f5..00000000 --- a/vendor/github.com/go-openapi/jsonreference/.cliff.toml +++ /dev/null @@ -1,181 +0,0 @@ -# git-cliff ~ configuration file -# https://git-cliff.org/docs/configuration - -[changelog] -header = """ -""" - -footer = """ - ------ - -**[{{ remote.github.repo }}]({{ self::remote_url() }}) license terms** - -[![License][license-badge]][license-url] - -[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg -[license-url]: {{ self::remote_url() }}/?tab=Apache-2.0-1-ov-file#readme - -{%- macro remote_url() -%} - https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} -{%- endmacro -%} -""" - -body = """ -{%- if version %} -## [{{ version | trim_start_matches(pat="v") }}]({{ self::remote_url() }}/tree/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} -{%- else %} -## [unreleased] -{%- endif %} -{%- if message %} - {%- raw %}\n{% endraw %} -{{ message }} - {%- raw %}\n{% endraw %} -{%- endif %} -{%- if version %} - {%- if previous.version %} - -**Full Changelog**: <{{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}> - {%- endif %} -{%- else %} - {%- raw %}\n{% endraw %} -{%- endif %} - -{%- if statistics %}{% if statistics.commit_count %} - {%- raw %}\n{% endraw %} -{{ statistics.commit_count }} commits in this release. - {%- raw %}\n{% endraw %} -{%- endif %}{% endif %} ------ - -{%- for group, commits in commits | group_by(attribute="group") %} - {%- raw %}\n{% endraw %} -### {{ group | upper_first }} - {%- raw %}\n{% endraw %} - {%- for commit in commits %} - {%- if commit.remote.pr_title %} - {%- set commit_message = commit.remote.pr_title %} - {%- else %} - {%- set commit_message = commit.message %} - {%- endif %} -* {{ commit_message | split(pat="\n") | first | trim }} - {%- if commit.remote.username %} -{%- raw %} {% endraw %}by [@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) - {%- endif %} - {%- if commit.remote.pr_number %} -{%- raw %} {% endraw %}in [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) - {%- endif %} -{%- raw %} {% endraw %}[...]({{ self::remote_url() }}/commit/{{ commit.id }}) - {%- endfor %} -{%- endfor %} - -{%- if github %} -{%- raw %}\n{% endraw -%} - {%- set all_contributors = github.contributors | length %} - {%- if github.contributors | filter(attribute="username", value="dependabot[bot]") | length < all_contributors %} ------ - -### People who contributed to this release - {% endif %} - {%- for contributor in github.contributors | filter(attribute="username") | sort(attribute="username") %} - {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} -* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) - {%- endif %} - {%- endfor %} - - {% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} ------ - {%- raw %}\n{% endraw %} - -### New Contributors - {%- endif %} - - {%- for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} - {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} -* @{{ contributor.username }} made their first contribution - {%- if contributor.pr_number %} - in [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ - {%- endif %} - {%- endif %} - {%- endfor %} -{%- endif %} - -{%- raw %}\n{% endraw %} - -{%- macro remote_url() -%} - https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} -{%- endmacro -%} -""" -# Remove leading and trailing whitespaces from the changelog's body. -trim = true -# Render body even when there are no releases to process. -render_always = true -# An array of regex based postprocessors to modify the changelog. -postprocessors = [ - # Replace the placeholder with a URL. - #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, -] -# output file path -# output = "test.md" - -[git] -# Parse commits according to the conventional commits specification. -# See https://www.conventionalcommits.org -conventional_commits = false -# Exclude commits that do not match the conventional commits specification. -filter_unconventional = false -# Require all commits to be conventional. -# Takes precedence over filter_unconventional. -require_conventional = false -# Split commits on newlines, treating each line as an individual commit. -split_commits = false -# An array of regex based parsers to modify commit messages prior to further processing. -commit_preprocessors = [ - # Replace issue numbers with link templates to be updated in `changelog.postprocessors`. - #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, - # Check spelling of the commit message using https://github.com/crate-ci/typos. - # If the spelling is incorrect, it will be fixed automatically. - #{ pattern = '.*', replace_command = 'typos --write-changes -' } -] -# Prevent commits that are breaking from being excluded by commit parsers. -protect_breaking_commits = false -# An array of regex based parsers for extracting data from the commit message. -# Assigns commits to groups. -# Optionally sets the commit's scope and can decide to exclude commits from further processing. -commit_parsers = [ - { message = "^[Cc]hore\\([Rr]elease\\): prepare for", skip = true }, - { message = "(^[Mm]erge)|([Mm]erge conflict)", skip = true }, - { field = "author.name", pattern = "dependabot*", group = "Updates" }, - { message = "([Ss]ecurity)|([Vv]uln)", group = "Security" }, - { body = "(.*[Ss]ecurity)|([Vv]uln)", group = "Security" }, - { message = "([Cc]hore\\(lint\\))|(style)|(lint)|(codeql)|(golangci)", group = "Code quality" }, - { message = "(^[Dd]oc)|((?i)readme)|(badge)|(typo)|(documentation)", group = "Documentation" }, - { message = "(^[Ff]eat)|(^[Ee]nhancement)", group = "Implemented enhancements" }, - { message = "(^ci)|(\\(ci\\))|(fixup\\s+ci)|(fix\\s+ci)|(license)|(example)", group = "Miscellaneous tasks" }, - { message = "^test", group = "Testing" }, - { message = "(^fix)|(panic)", group = "Fixed bugs" }, - { message = "(^refact)|(rework)", group = "Refactor" }, - { message = "(^[Pp]erf)|(performance)", group = "Performance" }, - { message = "(^[Cc]hore)", group = "Miscellaneous tasks" }, - { message = "^[Rr]evert", group = "Reverted changes" }, - { message = "(upgrade.*?go)|(go\\s+version)", group = "Updates" }, - { message = ".*", group = "Other" }, -] -# Exclude commits that are not matched by any commit parser. -filter_commits = false -# An array of link parsers for extracting external references, and turning them into URLs, using regex. -link_parsers = [] -# Include only the tags that belong to the current branch. -use_branch_tags = false -# Order releases topologically instead of chronologically. -topo_order = false -# Order releases topologically instead of chronologically. -topo_order_commits = true -# Order of commits in each group/release within the changelog. -# Allowed values: newest, oldest -sort_commits = "newest" -# Process submodules commits -recurse_submodules = false - -#[remote.github] -#owner = "go-openapi" diff --git a/vendor/github.com/go-openapi/jsonreference/.gitignore b/vendor/github.com/go-openapi/jsonreference/.gitignore index 769c2440..885dc27a 100644 --- a/vendor/github.com/go-openapi/jsonreference/.gitignore +++ b/vendor/github.com/go-openapi/jsonreference/.gitignore @@ -1 +1,6 @@ -secrets.yml +*.out +*.cov +.idea +.env +.mcp.json +.claude/ diff --git a/vendor/github.com/go-openapi/jsonreference/.golangci.yml b/vendor/github.com/go-openapi/jsonreference/.golangci.yml index fdae591b..dc7c9605 100644 --- a/vendor/github.com/go-openapi/jsonreference/.golangci.yml +++ b/vendor/github.com/go-openapi/jsonreference/.golangci.yml @@ -12,6 +12,7 @@ linters: - paralleltest - recvcheck - testpackage + - thelper - tparallel - varnamelen - whitespace diff --git a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md b/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md index 9907d5d2..7faeb83a 100644 --- a/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md @@ -4,11 +4,11 @@ | Total Contributors | Total Contributions | | --- | --- | -| 9 | 68 | +| 9 | 73 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | -| @fredbi | 31 | https://github.com/go-openapi/jsonreference/commits?author=fredbi | +| @fredbi | 36 | https://github.com/go-openapi/jsonreference/commits?author=fredbi | | @casualjim | 25 | https://github.com/go-openapi/jsonreference/commits?author=casualjim | | @youyuanwu | 5 | https://github.com/go-openapi/jsonreference/commits?author=youyuanwu | | @olivierlemasle | 2 | https://github.com/go-openapi/jsonreference/commits?author=olivierlemasle | diff --git a/vendor/github.com/go-openapi/jsonreference/NOTICE b/vendor/github.com/go-openapi/jsonreference/NOTICE index f3b51939..814e87ef 100644 --- a/vendor/github.com/go-openapi/jsonreference/NOTICE +++ b/vendor/github.com/go-openapi/jsonreference/NOTICE @@ -3,7 +3,7 @@ Copyright 2015-2025 go-swagger maintainers // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 -This software library, github.com/go-openapi/jsonpointer, includes software developed +This software library, github.com/go-openapi/jsonreference, includes software developed by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,7 +18,7 @@ It ships with copies of other software which license terms are recalled below. The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). -github.com/sigh-399/jsonpointer +github.com/sigh-399/jsonreference =========================== // SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) diff --git a/vendor/github.com/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md index d479dbdc..adea1606 100644 --- a/vendor/github.com/go-openapi/jsonreference/README.md +++ b/vendor/github.com/go-openapi/jsonreference/README.md @@ -8,12 +8,22 @@ [![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] -[![GoDoc][godoc-badge]][godoc-url] [![Slack Channel][slack-logo]![slack-badge]][slack-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] --- An implementation of JSON Reference for golang. +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + ## Status API is stable. @@ -26,18 +36,33 @@ go get github.com/go-openapi/jsonreference ## Dependencies -* https://github.com/go-openapi/jsonpointer +* ## Basic usage +```go +// Creating a new reference +ref, err := jsonreference.New("http://example.com/doc.json#/definitions/Pet") + +// Fragment-only reference +fragRef := jsonreference.MustCreateRef("#/definitions/Pet") + +// Resolving references +parent, _ := jsonreference.New("http://example.com/base.json") +child, _ := jsonreference.New("#/definitions/Pet") +resolved, _ := parent.Inherits(child) +// Result: "http://example.com/base.json#/definitions/Pet" +``` + + ## Change log See ## References -* http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 -* http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 +* +* ## Licensing @@ -89,6 +114,9 @@ Maintainers can cut a new release by either: [slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png [slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM [slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + [license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg [license-url]: https://github.com/go-openapi/jsonreference/?tab=Apache-2.0-1-ov-file#readme diff --git a/vendor/github.com/go-openapi/jsonreference/SECURITY.md b/vendor/github.com/go-openapi/jsonreference/SECURITY.md index 2a7b6f09..1fea2c57 100644 --- a/vendor/github.com/go-openapi/jsonreference/SECURITY.md +++ b/vendor/github.com/go-openapi/jsonreference/SECURITY.md @@ -6,14 +6,32 @@ This policy outlines the commitment and practices of the go-openapi maintainers | Version | Supported | | ------- | ------------------ | -| 0.22.x | :white_check_mark: | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. ## Reporting a vulnerability If you become aware of a security vulnerability that affects the current repository, -please report it privately to the maintainers. +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. -Please follow the instructions provided by github to -[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". -TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/jsonreference/reference.go b/vendor/github.com/go-openapi/jsonreference/reference.go index 6e3ae499..003ba7a8 100644 --- a/vendor/github.com/go-openapi/jsonreference/reference.go +++ b/vendor/github.com/go-openapi/jsonreference/reference.go @@ -16,6 +16,7 @@ const ( fragmentRune = `#` ) +// ErrChildURL is raised when there is no child. var ErrChildURL = errors.New("child url is nil") // Ref represents a json reference object. diff --git a/vendor/github.com/go-openapi/loads/.gitignore b/vendor/github.com/go-openapi/loads/.gitignore index e4f15f17..d8f4186f 100644 --- a/vendor/github.com/go-openapi/loads/.gitignore +++ b/vendor/github.com/go-openapi/loads/.gitignore @@ -1,4 +1,5 @@ -secrets.yml -coverage.out -profile.cov -profile.out +*.out +*.cov +.idea +.env +.mcp.json diff --git a/vendor/github.com/go-openapi/loads/.golangci.yml b/vendor/github.com/go-openapi/loads/.golangci.yml index 1ad5adf4..83968f3f 100644 --- a/vendor/github.com/go-openapi/loads/.golangci.yml +++ b/vendor/github.com/go-openapi/loads/.golangci.yml @@ -2,25 +2,12 @@ version: "2" linters: default: all disable: - - cyclop - depguard - - errchkjson - - errorlint - - exhaustruct - - forcetypeassert - funlen - - gochecknoglobals + - gochecknoglobals # on this repo, it is hard to refactor without globals/inits and no breaking change - gochecknoinits - - gocognit - - godot - godox - - gosmopolitan - - inamedparam - - intrange - - ireturn - - lll - - musttag - - nestif + - exhaustruct - nlreturn - nonamedreturns - noinlineerr @@ -29,7 +16,6 @@ linters: - testpackage - thelper - tparallel - - unparam - varnamelen - whitespace - wrapcheck @@ -41,8 +27,15 @@ linters: goconst: min-len: 2 min-occurrences: 3 + cyclop: + max-complexity: 20 gocyclo: - min-complexity: 45 + min-complexity: 20 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 exclusions: generated: lax presets: @@ -58,6 +51,7 @@ formatters: enable: - gofmt - goimports + - gofumpt exclusions: generated: lax paths: diff --git a/vendor/github.com/go-openapi/loads/.travis.yml b/vendor/github.com/go-openapi/loads/.travis.yml deleted file mode 100644 index cd4a7c33..00000000 --- a/vendor/github.com/go-openapi/loads/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -after_success: -- bash <(curl -s https://codecov.io/bash) -go: -- 1.16.x -- 1.x -install: -- go get gotest.tools/gotestsum -language: go -arch: -- amd64 -- ppc64le -jobs: - include: - # include linting job, but only for latest go version and amd64 arch - - go: 1.x - arch: amd64 - install: - go get github.com/golangci/golangci-lint/cmd/golangci-lint - script: - - golangci-lint run --new-from-rev master -notifications: - slack: - secure: OxkPwVp35qBTUilgWC8xykSj+sGMcj0h8IIOKD+Rflx2schZVlFfdYdyVBM+s9OqeOfvtuvnR9v1Ye2rPKAvcjWdC4LpRGUsgmItZaI6Um8Aj6+K9udCw5qrtZVfOVmRu8LieH//XznWWKdOultUuniW0MLqw5+II87Gd00RWbCGi0hk0PykHe7uK+PDA2BEbqyZ2WKKYCvfB3j+0nrFOHScXqnh0V05l2E83J4+Sgy1fsPy+1WdX58ZlNBG333ibaC1FS79XvKSmTgKRkx3+YBo97u6ZtUmJa5WZjf2OdLG3KIckGWAv6R5xgxeU31N0Ng8L332w/Edpp2O/M2bZwdnKJ8hJQikXIAQbICbr+lTDzsoNzMdEIYcHpJ5hjPbiUl3Bmd+Jnsjf5McgAZDiWIfpCKZ29tPCEkVwRsOCqkyPRMNMzHHmoja495P5jR+ODS7+J8RFg5xgcnOgpP9D4Wlhztlf5WyZMpkLxTUD+bZq2SRf50HfHFXTkfq22zPl3d1eq0yrLwh/Z/fWKkfb6SyysROL8y6s8u3dpFX1YHSg0BR6i913h4aoZw9B2BG27cafLLTwKYsp2dFo1PWl4O6u9giFJIeqwloZHLKKrwh0cBFhB7RH0I58asxkZpCH6uWjJierahmHe7iS+E6i+9oCHkOZ59hmCYNimIs3hM= -script: -- gotestsum -f short-verbose -- -race -timeout=20m -coverprofile=coverage.txt -covermode=atomic ./... diff --git a/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/loads/CONTRIBUTORS.md b/vendor/github.com/go-openapi/loads/CONTRIBUTORS.md new file mode 100644 index 00000000..36b836a3 --- /dev/null +++ b/vendor/github.com/go-openapi/loads/CONTRIBUTORS.md @@ -0,0 +1,26 @@ +# Contributors + +- Repository: ['go-openapi/loads'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 14 | 123 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @casualjim | 48 | | +| @fredbi | 45 | | +| @youyuanwu | 6 | | +| @vburenin | 4 | | +| @keramix | 4 | | +| @orisano | 3 | | +| @GlenDC | 3 | | +| @pengsrc | 2 | | +| @a2800276 | 2 | | +| @tklauser | 2 | | +| @hypnoglow | 1 | | +| @koron | 1 | | +| @kreativka | 1 | | +| @petrkotas | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/loads/README.md b/vendor/github.com/go-openapi/loads/README.md index 1f0174f2..d92e62a0 100644 --- a/vendor/github.com/go-openapi/loads/README.md +++ b/vendor/github.com/go-openapi/loads/README.md @@ -1,11 +1,42 @@ -# Loads OAI specs [![Build Status](https://github.com/go-openapi/loads/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/loads/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/loads/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/loads) +# Loads OAI specs -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/loads/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/loads?status.svg)](http://godoc.org/github.com/go-openapi/loads) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/loads)](https://goreportcard.com/report/github.com/go-openapi/loads) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -Loading of OAI v2 API specification documents from local or remote locations. Supports JSON and YAML documents. +--- -Primary usage: +Loads OAI v2 API specification documents from local or remote locations. + +Supports JSON and YAML documents. + +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + +## Status + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/loads +``` + +## Basic usage ```go import ( @@ -27,6 +58,61 @@ Primary usage: See also the provided [examples](https://pkg.go.dev/github.com/go-openapi/loads#pkg-examples). +## Change log + +See + ## Licensing This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/loads/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/loads/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/loads/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/loads/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/loads +[vuln-scan-badge]: https://github.com/go-openapi/loads/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/loads/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/loads/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/loads/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Floads.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Floads + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/loads +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/loads +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/loads +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/loads + +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/loads +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/loads +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/loads/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/loads +[goversion-url]: https://github.com/go-openapi/loads/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/loads +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/loads/latest diff --git a/vendor/github.com/go-openapi/loads/SECURITY.md b/vendor/github.com/go-openapi/loads/SECURITY.md new file mode 100644 index 00000000..6ceb159c --- /dev/null +++ b/vendor/github.com/go-openapi/loads/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/loads/doc.go b/vendor/github.com/go-openapi/loads/doc.go index 7981e70e..67a5e2f8 100644 --- a/vendor/github.com/go-openapi/loads/doc.go +++ b/vendor/github.com/go-openapi/loads/doc.go @@ -4,4 +4,6 @@ // Package loads provides document loading methods for swagger (OAI v2) API specifications. // // It is used by other go-openapi packages to load and run analysis on local or remote spec documents. +// +// Loaders support JSON and YAML documents. package loads diff --git a/vendor/github.com/go-openapi/loads/errors.go b/vendor/github.com/go-openapi/loads/errors.go index 8f2d602f..14a8186b 100644 --- a/vendor/github.com/go-openapi/loads/errors.go +++ b/vendor/github.com/go-openapi/loads/errors.go @@ -10,9 +10,9 @@ func (e loaderError) Error() string { } const ( - // ErrLoads is an error returned by the loads package + // ErrLoads is an error returned by the loads package. ErrLoads loaderError = "loaderrs error" - // ErrNoLoader indicates that no configured loader matched the input + // ErrNoLoader indicates that no configured loader matched the input. ErrNoLoader loaderError = "no loader matched" ) diff --git a/vendor/github.com/go-openapi/loads/loaders.go b/vendor/github.com/go-openapi/loads/loaders.go index 25b15730..ac8adfe8 100644 --- a/vendor/github.com/go-openapi/loads/loaders.go +++ b/vendor/github.com/go-openapi/loads/loaders.go @@ -13,14 +13,12 @@ import ( "github.com/go-openapi/swag/loading" ) -var ( - // Default chain of loaders, defined at the package level. - // - // By default this matches json and yaml documents. - // - // May be altered with AddLoader(). - loaders *loader -) +// Default chain of loaders, defined at the package level. +// +// By default this matches json and yaml documents. +// +// May be altered with AddLoader(). +var loaders *loader func init() { jsonLoader := &loader{ @@ -43,10 +41,10 @@ func init() { spec.PathLoader = loaders.Load } -// DocLoader represents a doc loader type +// DocLoader represents a doc loader type. type DocLoader func(string, ...loading.Option) (json.RawMessage, error) -// DocMatcher represents a predicate to check if a loader matches +// DocMatcher represents a predicate to check if a loader matches. type DocMatcher func(string) bool // DocLoaderWithMatch describes a loading function for a given extension match. @@ -55,7 +53,7 @@ type DocLoaderWithMatch struct { Match DocMatcher } -// NewDocLoaderWithMatch builds a DocLoaderWithMatch to be used in load options +// NewDocLoaderWithMatch builds a [DocLoaderWithMatch] to be used in load options. func NewDocLoaderWithMatch(fn DocLoader, matcher DocMatcher) DocLoaderWithMatch { return DocLoaderWithMatch{ Fn: fn, @@ -71,7 +69,7 @@ type loader struct { Next *loader } -// WithHead adds a loader at the head of the current stack +// WithHead adds a loader at the head of the current stack. func (l *loader) WithHead(head *loader) *loader { if head == nil { return l @@ -80,13 +78,13 @@ func (l *loader) WithHead(head *loader) *loader { return head } -// WithNext adds a loader at the trail of the current stack +// WithNext adds a loader at the trail of the current stack. func (l *loader) WithNext(next *loader) *loader { l.Next = next return next } -// Load the raw document from path +// Load the raw document from path. func (l *loader) Load(path string) (json.RawMessage, error) { _, erp := url.Parse(path) if erp != nil { @@ -123,9 +121,9 @@ func (l *loader) clone() *loader { } } -// JSONDoc loads a json document from either a file or a remote url. +// JSONDoc loads a json document from either a file or a remote URL. // -// See [loading.Option] for available options (e.g. configuring authentifaction, +// See [loading.Option] for available options (e.g. configuring authentication, // headers or using embedded file system resources). func JSONDoc(path string, opts ...loading.Option) (json.RawMessage, error) { data, err := loading.LoadFromFileOrHTTP(path, opts...) @@ -139,9 +137,10 @@ func JSONDoc(path string, opts ...loading.Option) (json.RawMessage, error) { // // This sets the configuration at the package level. // -// NOTE: -// - this updates the default loader used by github.com/go-openapi/spec -// - since this sets package level globals, you shouln't call this concurrently +// # Concurrency +// +// This function updates the default loader used by [github.com/go-openapi/spec]. +// Since this sets package level globals, you shouldn't call this concurrently. func AddLoader(predicate DocMatcher, load DocLoader) { loaders = loaders.WithHead(&loader{ DocLoaderWithMatch: DocLoaderWithMatch{ diff --git a/vendor/github.com/go-openapi/loads/options.go b/vendor/github.com/go-openapi/loads/options.go index adb5e6d1..045ece5e 100644 --- a/vendor/github.com/go-openapi/loads/options.go +++ b/vendor/github.com/go-openapi/loads/options.go @@ -28,10 +28,10 @@ func loaderFromOptions(options []LoaderOption) *loader { return l } -// LoaderOption allows to fine-tune the spec loader behavior +// LoaderOption allows to fine-tune the spec loader behavior. type LoaderOption func(*options) -// WithDocLoader sets a custom loader for loading specs +// WithDocLoader sets a custom loader for loading specs. func WithDocLoader(l DocLoader) LoaderOption { return func(opt *options) { if l == nil { @@ -48,7 +48,7 @@ func WithDocLoader(l DocLoader) LoaderOption { // WithDocLoaderMatches sets a chain of custom loaders for loading specs // for different extension matches. // -// Loaders are executed in the order of provided DocLoaderWithMatch'es. +// Loaders are executed in the order of provided [DocLoaderWithMatch] 'es. func WithDocLoaderMatches(l ...DocLoaderWithMatch) LoaderOption { return func(opt *options) { var final, prev *loader diff --git a/vendor/github.com/go-openapi/loads/spec.go b/vendor/github.com/go-openapi/loads/spec.go index 213c40c6..606a01d8 100644 --- a/vendor/github.com/go-openapi/loads/spec.go +++ b/vendor/github.com/go-openapi/loads/spec.go @@ -21,7 +21,7 @@ func init() { gob.Register([]any{}) } -// Document represents a swagger spec document +// Document represents a swagger spec document. type Document struct { // specAnalyzer Analyzer *analysis.Spec @@ -33,7 +33,7 @@ type Document struct { raw json.RawMessage } -// JSONSpec loads a spec from a json document, using the [JSONDoc] loader. +// JSONSpec loads a spec from a JSON document, using the [JSONDoc] loader. // // A set of [loading.Option] may be passed to this loader using [WithLoadingOptions]. func JSONSpec(path string, opts ...LoaderOption) (*Document, error) { @@ -57,7 +57,7 @@ func JSONSpec(path string, opts ...LoaderOption) (*Document, error) { return doc, nil } -// Embedded returns a Document based on embedded specs (i.e. as a raw [json.RawMessage]). No analysis is required +// Embedded returns a Document based on embedded specs (i.e. as a [json.RawMessage]). No analysis is required. func Embedded(orig, flat json.RawMessage, opts ...LoaderOption) (*Document, error) { var origSpec, flatSpec spec.Swagger if err := json.Unmarshal(orig, &origSpec); err != nil { @@ -96,7 +96,7 @@ func Spec(path string, opts ...LoaderOption) (*Document, error) { return document, nil } -// Analyzed creates a new analyzed spec document for a root json.RawMessage. +// Analyzed creates a new analyzed spec document for a root [json.RawMessage]. func Analyzed(data json.RawMessage, version string, options ...LoaderOption) (*Document, error) { if version == "" { version = "2.0" @@ -145,18 +145,18 @@ func trimData(in json.RawMessage) (json.RawMessage, error) { // assume yaml doc: convert it to json yml, err := yamlutils.BytesToYAMLDoc(trimmed) if err != nil { - return nil, fmt.Errorf("analyzed: %v: %w", err, ErrLoads) + return nil, fmt.Errorf("analyzed: %w: %w", err, ErrLoads) } d, err := yamlutils.YAMLToJSON(yml) if err != nil { - return nil, fmt.Errorf("analyzed: %v: %w", err, ErrLoads) + return nil, fmt.Errorf("analyzed: %w: %w", err, ErrLoads) } return d, nil } -// Expanded expands the $ref fields in the spec [Document] and returns a new expanded [Document] +// Expanded expands the $ref fields in the spec [Document] and returns a new expanded [Document]. func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) { swspec := new(spec.Swagger) if err := json.Unmarshal(d.raw, swspec); err != nil { @@ -200,7 +200,7 @@ func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) { return dd, nil } -// BasePath the base path for the API specified by this spec +// BasePath the base path for the API specified by this spec. func (d *Document) BasePath() string { if d.spec == nil { return "" @@ -208,37 +208,37 @@ func (d *Document) BasePath() string { return d.spec.BasePath } -// Version returns the OpenAPI version of this spec (e.g. 2.0) +// Version returns the OpenAPI version of this spec (e.g. 2.0). func (d *Document) Version() string { return d.spec.Swagger } -// Schema returns the swagger 2.0 meta-schema +// Schema returns the swagger 2.0 meta-schema. func (d *Document) Schema() *spec.Schema { return d.schema } -// Spec returns the swagger object model for this API specification +// Spec returns the swagger object model for this API specification. func (d *Document) Spec() *spec.Swagger { return d.spec } -// Host returns the host for the API +// Host returns the host for the API. func (d *Document) Host() string { return d.spec.Host } -// Raw returns the raw swagger spec as json bytes +// Raw returns the raw swagger spec as json bytes. func (d *Document) Raw() json.RawMessage { return d.raw } -// OrigSpec yields the original spec +// OrigSpec yields the original spec. func (d *Document) OrigSpec() *spec.Swagger { return d.origSpec } -// ResetDefinitions yields a shallow copy with the models reset to the original spec +// ResetDefinitions yields a shallow copy with the models reset to the original spec. func (d *Document) ResetDefinitions() *Document { d.spec.Definitions = make(map[string]spec.Schema, len(d.origSpec.Definitions)) maps.Copy(d.spec.Definitions, d.origSpec.Definitions) @@ -246,9 +246,9 @@ func (d *Document) ResetDefinitions() *Document { return d } -// Pristine creates a new pristine document instance based on the input data +// Pristine creates a new pristine document instance based on the input data. func (d *Document) Pristine() *Document { - raw, _ := json.Marshal(d.Spec()) + raw, _ := json.Marshal(d.Spec()) //nolint:errchkjson // the spec always marshals to JSON dd, _ := Analyzed(raw, d.Version()) dd.pathLoader = d.pathLoader dd.specFilePath = d.specFilePath @@ -256,7 +256,7 @@ func (d *Document) Pristine() *Document { return dd } -// SpecFilePath returns the file path of the spec if one is defined +// SpecFilePath returns the file path of the spec if one is defined. func (d *Document) SpecFilePath() string { return d.specFilePath } diff --git a/vendor/github.com/go-openapi/runtime/.gitignore b/vendor/github.com/go-openapi/runtime/.gitignore index fea8b84e..d8f4186f 100644 --- a/vendor/github.com/go-openapi/runtime/.gitignore +++ b/vendor/github.com/go-openapi/runtime/.gitignore @@ -1,5 +1,5 @@ -secrets.yml -coverage.out -*.cov *.out -playground +*.cov +.idea +.env +.mcp.json diff --git a/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/runtime/NOTICE b/vendor/github.com/go-openapi/runtime/NOTICE new file mode 100644 index 00000000..b9153aae --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/NOTICE @@ -0,0 +1,45 @@ +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored in 2014 by Naoya Inada + +https://github.com/naoina/denco +=========================== + +// SPDX-FileCopyrightText: Copyright (c) 2014 Naoya Inada +// SPDX-License-Identifier: MIT + +Copyright (c) 2014 Naoya Inada + +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/go-openapi/runtime/README.md b/vendor/github.com/go-openapi/runtime/README.md index 9e15b1ad..dd7f5039 100644 --- a/vendor/github.com/go-openapi/runtime/README.md +++ b/vendor/github.com/go-openapi/runtime/README.md @@ -1,31 +1,46 @@ -# runtime [![Build Status](https://github.com/go-openapi/runtime/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/runtime/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/runtime/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/runtime) +# runtime -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/runtime/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/runtime.svg)](https://pkg.go.dev/github.com/go-openapi/runtime) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/runtime)](https://goreportcard.com/report/github.com/go-openapi/runtime) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -# go OpenAPI toolkit runtime +--- + +A runtime for go OpenAPI toolkit. The runtime component for use in code generation or as untyped usage. -## Release notes +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + +## Status + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/runtime +``` -### v0.29.0 +## Change log -**New with this release**: +See -* upgraded to `go1.24` and modernized the code base accordingly -* updated all dependencies, and removed an noticable indirect dependency (e.g. `mailru/easyjson`) -* **breaking change** no longer imports `opentracing-go` (#365). - * the `WithOpentracing()` method now returns an opentelemetry transport - * for users who can't transition to opentelemetry, the previous behavior - of `WithOpentracing` delivering an opentracing transport is provided by a separate - module `github.com/go-openapi/runtime/client-middleware/opentracing`. -* removed direct dependency to `gopkg.in/yaml.v3`, in favor of `go.yaml.in/yaml/v3` (an indirect - test dependency to the older package is still around) -* technically, the repo has evolved to a mono-repo, multiple modules structures (2 go modules - published), with CI adapted accordingly +For pre-v0.30.0 releases see [release notes](docs/NOTES.md). **What coming next?** @@ -41,3 +56,58 @@ Moving forward, we want to : ## Licensing This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +See the license [NOTICE](./NOTICE), which recalls the licensing terms of all the pieces of software +on top of which it has been built. + +## Other documentation + +* [FAQ](docs/FAQ.md) +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/runtime/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/runtime/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/runtime/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/runtime/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/runtime +[vuln-scan-badge]: https://github.com/go-openapi/runtime/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/runtime/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/runtime/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/runtime/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fruntime.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fruntime + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/runtime +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/runtime +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/runtime +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/runtime + +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/runtime +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/runtime +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/runtime/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/runtime +[goversion-url]: https://github.com/go-openapi/runtime/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/runtime +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/runtime/latest diff --git a/vendor/github.com/go-openapi/runtime/SECURITY.md b/vendor/github.com/go-openapi/runtime/SECURITY.md new file mode 100644 index 00000000..1fea2c57 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/runtime/bytestream.go b/vendor/github.com/go-openapi/runtime/bytestream.go index eb649742..8701c8e3 100644 --- a/vendor/github.com/go-openapi/runtime/bytestream.go +++ b/vendor/github.com/go-openapi/runtime/bytestream.go @@ -18,7 +18,7 @@ func defaultCloser() error { return nil } type byteStreamOpt func(opts *byteStreamOpts) -// ClosesStream when the bytestream consumer or producer is finished +// ClosesStream when the bytestream consumer or producer is finished. func ClosesStream(opts *byteStreamOpts) { opts.Close = true } @@ -32,11 +32,12 @@ type byteStreamOpts struct { // The consumer consumes from a provided reader into the data passed by reference. // // Supported output underlying types and interfaces, prioritized in this order: -// - io.ReaderFrom (for maximum control) -// - io.Writer (performs io.Copy) -// - encoding.BinaryUnmarshaler -// - *string -// - *[]byte +// +// - [io.ReaderFrom] (for maximum control) +// - [io.Writer] (performs [io.Copy]) +// - [encoding.BinaryUnmarshaler] +// - *string +// - *[]byte func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { var vals byteStreamOpts for _, opt := range opts { @@ -124,13 +125,14 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { // The producer takes input data then writes to an output writer (essentially as a pipe). // // Supported input underlying types and interfaces, prioritized in this order: -// - io.WriterTo (for maximum control) -// - io.Reader (performs io.Copy). A ReadCloser is closed before exiting. -// - encoding.BinaryMarshaler +// +// - [io.WriterTo] (for maximum control) +// - [io.Reader] (performs [io.Copy]). A ReadCloser is closed before exiting. +// - [encoding.BinaryMarshaler] // - error (writes as a string) // - []byte // - string -// - struct, other slices: writes as JSON +// - struct, other slices: writes as JSON. func ByteStreamProducer(opts ...byteStreamOpt) Producer { var vals byteStreamOpts for _, opt := range opts { diff --git a/vendor/github.com/go-openapi/runtime/client/auth_info.go b/vendor/github.com/go-openapi/runtime/client/auth_info.go index a98690c4..fdaa08f2 100644 --- a/vendor/github.com/go-openapi/runtime/client/auth_info.go +++ b/vendor/github.com/go-openapi/runtime/client/auth_info.go @@ -11,14 +11,14 @@ import ( "github.com/go-openapi/runtime" ) -// PassThroughAuth never manipulates the request +// PassThroughAuth never manipulates the request. var PassThroughAuth runtime.ClientAuthInfoWriter func init() { PassThroughAuth = runtime.ClientAuthInfoWriterFunc(func(_ runtime.ClientRequest, _ strfmt.Registry) error { return nil }) } -// BasicAuth provides a basic auth info writer +// BasicAuth provides a basic auth info writer. func BasicAuth(username, password string) runtime.ClientAuthInfoWriter { return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) @@ -26,7 +26,7 @@ func BasicAuth(username, password string) runtime.ClientAuthInfoWriter { }) } -// APIKeyAuth provides an API key auth info writer +// APIKeyAuth provides an API key auth info writer. func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter { if in == "query" { return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { @@ -42,7 +42,7 @@ func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter { return nil } -// BearerToken provides a header based oauth2 bearer access token auth info writer +// BearerToken provides a header based oauth2 bearer access token auth info writer. func BearerToken(token string) runtime.ClientAuthInfoWriter { return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { return r.SetHeaderParam(runtime.HeaderAuthorization, "Bearer "+token) diff --git a/vendor/github.com/go-openapi/runtime/client/keepalive.go b/vendor/github.com/go-openapi/runtime/client/keepalive.go index 831d23b5..3bac5e27 100644 --- a/vendor/github.com/go-openapi/runtime/client/keepalive.go +++ b/vendor/github.com/go-openapi/runtime/client/keepalive.go @@ -13,7 +13,7 @@ import ( // so that go will reuse the TCP connections. // This is not enabled by default because there are servers where // the response never gets closed and that would make the code hang forever. -// So instead it's provided as a http client middleware that can be used to override +// So instead it's provided as a [http] client [middleware] that can be used to override // any request. func KeepAliveTransport(rt http.RoundTripper) http.RoundTripper { return &keepAliveTransport{wrapped: rt} diff --git a/vendor/github.com/go-openapi/runtime/client/opentelemetry.go b/vendor/github.com/go-openapi/runtime/client/opentelemetry.go index e7794129..5054878c 100644 --- a/vendor/github.com/go-openapi/runtime/client/opentelemetry.go +++ b/vendor/github.com/go-openapi/runtime/client/opentelemetry.go @@ -98,12 +98,14 @@ func newOpenTelemetryTransport(transport runtime.ClientTransport, host string, o host: host, } - defaultOpts := []OpenTelemetryOpt{ + const baseOptions = 4 + defaultOpts := make([]OpenTelemetryOpt, 0, len(opts)+baseOptions) + defaultOpts = append(defaultOpts, WithSpanOptions(trace.WithSpanKind(trace.SpanKindClient)), WithSpanNameFormatter(defaultTransportFormatter), WithPropagators(otel.GetTextMapPropagator()), WithTracerProvider(otel.GetTracerProvider()), - } + ) c := newConfig(append(defaultOpts, opts...)...) tr.config = c diff --git a/vendor/github.com/go-openapi/runtime/client/request.go b/vendor/github.com/go-openapi/runtime/client/request.go index 6d9b2591..f16ee487 100644 --- a/vendor/github.com/go-openapi/runtime/client/request.go +++ b/vendor/github.com/go-openapi/runtime/client/request.go @@ -51,7 +51,7 @@ type request struct { getBody func(r *request) []byte } -// NewRequest creates a new swagger http client request +// NewRequest creates a new swagger http client request. func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) *request { return &request{ pathPattern: pathPattern, @@ -64,7 +64,7 @@ func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) } } -// BuildHTTP creates a new http request based on the data from the params +// BuildHTTP creates a new http request based on the data from the params. func (r *request) BuildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry) (*http.Request, error) { return r.buildHTTP(mediaType, basePath, producers, registry, nil) } @@ -87,7 +87,7 @@ func (r *request) GetBody() []byte { // SetHeaderParam adds a header param to the request // when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding) +// when there are several values provided for the varargs it will add it (no overriding). func (r *request) SetHeaderParam(name string, values ...string) error { if r.header == nil { r.header = make(http.Header) @@ -96,14 +96,14 @@ func (r *request) SetHeaderParam(name string, values ...string) error { return nil } -// GetHeaderParams returns the all headers currently set for the request +// GetHeaderParams returns the all headers currently set for the request. func (r *request) GetHeaderParams() http.Header { return r.header } // SetQueryParam adds a query param to the request // when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding) +// when there are several values provided for the varargs it will add it (no overriding). func (r *request) SetQueryParam(name string, values ...string) error { if r.query == nil { r.query = make(url.Values) @@ -112,7 +112,7 @@ func (r *request) SetQueryParam(name string, values ...string) error { return nil } -// GetQueryParams returns a copy of all query params currently set for the request +// GetQueryParams returns a copy of all query params currently set for the request. func (r *request) GetQueryParams() url.Values { var result = make(url.Values) for key, value := range r.query { @@ -123,7 +123,7 @@ func (r *request) GetQueryParams() url.Values { // SetFormParam adds a forn param to the request // when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding) +// when there are several values provided for the varargs it will add it (no overriding). func (r *request) SetFormParam(name string, values ...string) error { if r.formFields == nil { r.formFields = make(url.Values) @@ -132,7 +132,7 @@ func (r *request) SetFormParam(name string, values ...string) error { return nil } -// SetPathParam adds a path param to the request +// SetPathParam adds a path param to the request. func (r *request) SetPathParam(name string, value string) error { if r.pathParams == nil { r.pathParams = make(map[string]string) @@ -142,7 +142,7 @@ func (r *request) SetPathParam(name string, value string) error { return nil } -// SetFileParam adds a file param to the request +// SetFileParam adds a file param to the request. func (r *request) SetFileParam(name string, files ...runtime.NamedReadCloser) error { for _, file := range files { if actualFile, ok := file.(*os.File); ok { @@ -182,7 +182,7 @@ func (r *request) GetBodyParam() any { return r.payload } -// SetTimeout sets the timeout for a request +// SetTimeout sets the timeout for a request. func (r *request) SetTimeout(timeout time.Duration) error { r.timeout = timeout return nil @@ -298,8 +298,7 @@ func (r *request) buildHTTP(mediaType, basePath string, producers map[string]run // if there is payload, use the producer to write the payload, and then // set the header to the content-type appropriate for the payload produced if r.payload != nil { - // TODO: infer most appropriate content type based on the producer used, - // and the `consumers` section of the spec/operation + // Enhancement proposal: https://github.com/go-openapi/runtime/issues/387 r.header.Set(runtime.HeaderContentType, mediaType) if rdr, ok := r.payload.(io.ReadCloser); ok { body = rdr diff --git a/vendor/github.com/go-openapi/runtime/client/runtime.go b/vendor/github.com/go-openapi/runtime/client/runtime.go index 203c74e4..eeb17dfb 100644 --- a/vendor/github.com/go-openapi/runtime/client/runtime.go +++ b/vendor/github.com/go-openapi/runtime/client/runtime.go @@ -33,10 +33,10 @@ const ( schemeHTTPS = "https" ) -// DefaultTimeout the default request timeout +// DefaultTimeout the default request timeout. var DefaultTimeout = 30 * time.Second -// TLSClientOptions to configure client authentication with mutual TLS +// TLSClientOptions to configure client authentication with mutual TLS. type TLSClientOptions struct { // Certificate is the path to a PEM-encoded certificate to be used for // client authentication. If set then Key must also be set. @@ -92,6 +92,17 @@ type TLSClientOptions struct { // the verifiedChains argument will always be nil. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error + // VerifyConnection, if not nil, is called after normal certificate + // verification and after [TLSClientOptions.VerifyPeerCertificate] by either a TLS client or + // server. It receives the [tls.ConnectionState] which may be inspected. + // + // Unlike VerifyPeerCertificate, this callback is invoked on every + // connection, including resumed ones, making it suitable for checks + // that must always apply (e.g. certificate pinning). + // + // If it returns a non-nil error, the handshake is aborted and that error results. + VerifyConnection func(tls.ConnectionState) error + // SessionTicketsDisabled may be set to true to disable session ticket and // PSK (resumption) support. Note that on clients, session ticket support is // also disabled if ClientSessionCache is nil. @@ -105,7 +116,7 @@ type TLSClientOptions struct { _ struct{} } -// TLSClientAuth creates a tls.Config for mutual auth +// TLSClientAuth creates a [tls.Config] for mutual auth. func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { // create client tls config cfg := &tls.Config{ @@ -150,6 +161,7 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { cfg.InsecureSkipVerify = opts.InsecureSkipVerify cfg.VerifyPeerCertificate = opts.VerifyPeerCertificate + cfg.VerifyConnection = opts.VerifyConnection cfg.SessionTicketsDisabled = opts.SessionTicketsDisabled cfg.ClientSessionCache = opts.ClientSessionCache @@ -183,7 +195,7 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { return cfg, nil } -// TLSTransport creates a http client transport suitable for mutual tls auth +// TLSTransport creates a [http] client transport suitable for mutual [tls] auth. func TLSTransport(opts TLSClientOptions) (http.RoundTripper, error) { cfg, err := TLSClientAuth(opts) if err != nil { @@ -193,7 +205,7 @@ func TLSTransport(opts TLSClientOptions) (http.RoundTripper, error) { return &http.Transport{TLSClientConfig: cfg}, nil } -// TLSClient creates a http.Client for mutual auth +// TLSClient creates a [http.Client] for mutual auth. func TLSClient(opts TLSClientOptions) (*http.Client, error) { transport, err := TLSTransport(opts) if err != nil { @@ -203,7 +215,7 @@ func TLSClient(opts TLSClientOptions) (*http.Client, error) { } // Runtime represents an API client that uses the transport -// to make http requests based on a swagger specification. +// to make [http] requests based on a swagger specification. type Runtime struct { DefaultMediaType string DefaultAuthentication runtime.ClientAuthInfoWriter @@ -227,12 +239,12 @@ type Runtime struct { response ClientResponseFunc } -// New creates a new default runtime for a swagger api runtime.Client +// New creates a new default runtime for a swagger api runtime.Client. func New(host, basePath string, schemes []string) *Runtime { var rt Runtime rt.DefaultMediaType = runtime.JSONMime - // TODO: actually infer this stuff from the spec + // Enhancement proposal: https://github.com/go-openapi/runtime/issues/385 rt.Consumers = map[string]runtime.Consumer{ runtime.YAMLMime: yamlpc.YAMLConsumer(), runtime.JSONMime: runtime.JSONConsumer(), @@ -271,7 +283,7 @@ func New(host, basePath string, schemes []string) *Runtime { return &rt } -// NewWithClient allows you to create a new transport with a configured http.Client +// NewWithClient allows you to create a new transport with a configured [http.Client]. func NewWithClient(host, basePath string, schemes []string, client *http.Client) *Runtime { rt := New(host, basePath, schemes) if client != nil { @@ -297,8 +309,8 @@ func NewWithClient(host, basePath string, schemes []string, client *http.Client) // an opentelemetry transport. // // If you have a strict requirement on using opentracing, you may still do so by importing -// module [github.com/go-openapi/runtime/client-middleware/opentracing] and using -// [github.com/go-openapi/runtime/client-middleware/opentracing.WithOpenTracing] with your +// module [github.com/go-openapi/runtime/client-[middleware]/opentracing] and using +// [github.com/go-openapi/runtime/client-[middleware]/opentracing.WithOpenTracing] with your // usual opentracing options and opentracing-enabled transport. // // Passed options are ignored unless they are of type [OpenTelemetryOpt]. @@ -328,7 +340,7 @@ func (r *Runtime) WithOpenTelemetry(opts ...OpenTelemetryOpt) runtime.ClientTran // // This is not enabled by default because there are servers where // the response never gets closed and that would make the code hang forever. -// So instead it's provided as a http client middleware that can be used to override +// So instead it's provided as a [http] client [middleware] that can be used to override // any request. func (r *Runtime) EnableConnectionReuse() { if r.client == nil { @@ -351,7 +363,7 @@ func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *ht } // Submit a request and when there is a body on success it will turn that into the result -// all other things are turned into an api error for swagger which retains the status code +// all other things are turned into an api error for swagger which retains the status code. func (r *Runtime) Submit(operation *runtime.ClientOperation) (any, error) { _, readResponse, _ := operation.Params, operation.Reader, operation.AuthInfo @@ -506,13 +518,13 @@ func transportOrDefault(left, right http.RoundTripper) http.RoundTripper { return left } -// takes a client operation and creates equivalent http.Request +// takes a client operation and creates equivalent http.Request. func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*request, *http.Request, error) { //nolint:revive params, _, auth := operation.Params, operation.Reader, operation.AuthInfo request := newRequest(operation.Method, operation.PathPattern, params) - var accept []string + accept := make([]string, 0, len(operation.ProducesMediaTypes)) accept = append(accept, operation.ProducesMediaTypes...) if err := request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil { return nil, nil, err @@ -532,7 +544,7 @@ func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*reques // } //} - // TODO: pick appropriate media type + // Enhancement proposal: https://github.com/go-openapi/runtime/issues/386 cmt := r.DefaultMediaType for _, mediaType := range operation.ConsumesMediaTypes { // Pick first non-empty media type diff --git a/vendor/github.com/go-openapi/runtime/client_auth_info.go b/vendor/github.com/go-openapi/runtime/client_auth_info.go index 581e6445..5ef59c88 100644 --- a/vendor/github.com/go-openapi/runtime/client_auth_info.go +++ b/vendor/github.com/go-openapi/runtime/client_auth_info.go @@ -5,15 +5,15 @@ package runtime import "github.com/go-openapi/strfmt" -// A ClientAuthInfoWriterFunc converts a function to a request writer interface +// A ClientAuthInfoWriterFunc converts a function to a request writer interface. type ClientAuthInfoWriterFunc func(ClientRequest, strfmt.Registry) error -// AuthenticateRequest adds authentication data to the request +// AuthenticateRequest adds authentication data to the request. func (fn ClientAuthInfoWriterFunc) AuthenticateRequest(req ClientRequest, reg strfmt.Registry) error { return fn(req, reg) } -// A ClientAuthInfoWriter implementor knows how to write authentication info to a request +// A ClientAuthInfoWriter implementor knows how to write authentication info to a request. type ClientAuthInfoWriter interface { AuthenticateRequest(ClientRequest, strfmt.Registry) error } diff --git a/vendor/github.com/go-openapi/runtime/client_operation.go b/vendor/github.com/go-openapi/runtime/client_operation.go index b0bb0977..ad7277e0 100644 --- a/vendor/github.com/go-openapi/runtime/client_operation.go +++ b/vendor/github.com/go-openapi/runtime/client_operation.go @@ -8,7 +8,7 @@ import ( "net/http" ) -// ClientOperation represents the context for a swagger operation to be submitted to the transport +// ClientOperation represents the context for a swagger operation to be submitted to the transport. type ClientOperation struct { ID string Method string @@ -23,7 +23,7 @@ type ClientOperation struct { Client *http.Client } -// A ClientTransport implementor knows how to submit Request objects to some destination +// A ClientTransport implementor knows how to submit Request objects to some destination. type ClientTransport interface { // Submit(string, RequestWriter, ResponseReader, AuthInfoWriter) (interface{}, error) Submit(*ClientOperation) (any, error) diff --git a/vendor/github.com/go-openapi/runtime/client_request.go b/vendor/github.com/go-openapi/runtime/client_request.go index 6e335b36..844f57b3 100644 --- a/vendor/github.com/go-openapi/runtime/client_request.go +++ b/vendor/github.com/go-openapi/runtime/client_request.go @@ -12,15 +12,15 @@ import ( "github.com/go-openapi/strfmt" ) -// ClientRequestWriterFunc converts a function to a request writer interface +// ClientRequestWriterFunc converts a function to a request writer interface. type ClientRequestWriterFunc func(ClientRequest, strfmt.Registry) error -// WriteToRequest adds data to the request +// WriteToRequest adds data to the request. func (fn ClientRequestWriterFunc) WriteToRequest(req ClientRequest, reg strfmt.Registry) error { return fn(req, reg) } -// ClientRequestWriter is an interface for things that know how to write to a request +// ClientRequestWriter is an interface for things that know how to write to a request. type ClientRequestWriter interface { WriteToRequest(ClientRequest, strfmt.Registry) error } @@ -57,13 +57,13 @@ type ClientRequest interface { //nolint:interfacebloat // a swagger-capable requ GetFileParam() map[string][]NamedReadCloser } -// NamedReadCloser represents a named ReadCloser interface +// NamedReadCloser represents a named ReadCloser interface. type NamedReadCloser interface { io.ReadCloser Name() string } -// NamedReader creates a NamedReadCloser for use as file upload +// NamedReader creates a [NamedReadCloser] for use as file upload. func NamedReader(name string, rdr io.Reader) NamedReadCloser { rc, ok := rdr.(io.ReadCloser) if !ok { diff --git a/vendor/github.com/go-openapi/runtime/client_response.go b/vendor/github.com/go-openapi/runtime/client_response.go index f2cf942a..92668db4 100644 --- a/vendor/github.com/go-openapi/runtime/client_response.go +++ b/vendor/github.com/go-openapi/runtime/client_response.go @@ -12,7 +12,7 @@ import ( // A ClientResponse represents a client response. // -// This bridges between responses obtained from different transports +// This bridges between responses obtained from different transports. type ClientResponse interface { Code() int Message() string @@ -21,28 +21,28 @@ type ClientResponse interface { Body() io.ReadCloser } -// A ClientResponseReaderFunc turns a function into a ClientResponseReader interface implementation +// A ClientResponseReaderFunc turns a function into a [ClientResponseReader] interface implementation. type ClientResponseReaderFunc func(ClientResponse, Consumer) (any, error) -// ReadResponse reads the response +// ReadResponse reads the response. func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (any, error) { return read(resp, consumer) } // A ClientResponseReader is an interface for things want to read a response. -// An application of this is to create structs from response values +// An application of this is to create structs from response values. type ClientResponseReader interface { ReadResponse(ClientResponse, Consumer) (any, error) } -// APIError wraps an error model and captures the status code +// APIError wraps an error model and captures the status code. type APIError struct { OperationName string Response any Code int } -// NewAPIError creates a new API error +// NewAPIError creates a new API error. func NewAPIError(opName string, payload any, code int) *APIError { return &APIError{ OperationName: opName, @@ -51,7 +51,7 @@ func NewAPIError(opName string, payload any, code int) *APIError { } } -// sanitizer ensures that single quotes are escaped +// sanitizer ensures that single quotes are escaped. var sanitizer = strings.NewReplacer(`\`, `\\`, `'`, `\'`) func (o *APIError) Error() string { @@ -69,37 +69,37 @@ func (o *APIError) String() string { return o.Error() } -// IsSuccess returns true when this API response returns a 2xx status code +// IsSuccess returns true when this API response returns a 2xx status code. func (o *APIError) IsSuccess() bool { const statusOK = 2 return o.Code/100 == statusOK } -// IsRedirect returns true when this API response returns a 3xx status code +// IsRedirect returns true when this API response returns a 3xx status code. func (o *APIError) IsRedirect() bool { const statusRedirect = 3 return o.Code/100 == statusRedirect } -// IsClientError returns true when this API response returns a 4xx status code +// IsClientError returns true when this API response returns a 4xx status code. func (o *APIError) IsClientError() bool { const statusClientError = 4 return o.Code/100 == statusClientError } -// IsServerError returns true when this API response returns a 5xx status code +// IsServerError returns true when this API response returns a 5xx status code. func (o *APIError) IsServerError() bool { const statusServerError = 5 return o.Code/100 == statusServerError } -// IsCode returns true when this API response returns a given status code +// IsCode returns true when this API response returns a given status code. func (o *APIError) IsCode(code int) bool { return o.Code == code } // A ClientResponseStatus is a common interface implemented by all responses on the generated code -// You can use this to treat any client response based on status code +// You can use this to treat any client response based on status code. type ClientResponseStatus interface { IsSuccess() bool IsRedirect() bool diff --git a/vendor/github.com/go-openapi/runtime/constants.go b/vendor/github.com/go-openapi/runtime/constants.go index 62ae9eec..80de6c80 100644 --- a/vendor/github.com/go-openapi/runtime/constants.go +++ b/vendor/github.com/go-openapi/runtime/constants.go @@ -4,35 +4,35 @@ package runtime const ( - // HeaderContentType represents a http content-type header, it's value is supposed to be a mime type + // HeaderContentType represents a [http] content-type header, it's value is supposed to be a mime type. HeaderContentType = "Content-Type" - // HeaderTransferEncoding represents a http transfer-encoding header. + // HeaderTransferEncoding represents a [http] transfer-encoding header. HeaderTransferEncoding = "Transfer-Encoding" - // HeaderAccept the Accept header + // HeaderAccept the Accept header. HeaderAccept = "Accept" - // HeaderAuthorization the Authorization header + // HeaderAuthorization the Authorization header. HeaderAuthorization = "Authorization" charsetKey = "charset" - // DefaultMime the default fallback mime type + // DefaultMime the default fallback mime type. DefaultMime = "application/octet-stream" - // JSONMime the json mime type + // JSONMime the json mime type. JSONMime = "application/json" - // YAMLMime the yaml mime type + // YAMLMime the [yaml] mime type. YAMLMime = "application/x-yaml" - // XMLMime the xml mime type + // XMLMime the [xml] mime type. XMLMime = "application/xml" - // TextMime the text mime type + // TextMime the text mime type. TextMime = "text/plain" - // HTMLMime the html mime type + // HTMLMime the html mime type. HTMLMime = "text/html" - // CSVMime the csv mime type + // CSVMime the [csv] mime type. CSVMime = "text/csv" - // MultipartFormMime the multipart form mime type + // MultipartFormMime the multipart form mime type. MultipartFormMime = "multipart/form-data" - // URLencodedFormMime the url encoded form mime type + // URLencodedFormMime is the [url] encoded form mime type. URLencodedFormMime = "application/x-www-form-urlencoded" ) diff --git a/vendor/github.com/go-openapi/runtime/csv.go b/vendor/github.com/go-openapi/runtime/csv.go index 567e3d9d..558d0cb9 100644 --- a/vendor/github.com/go-openapi/runtime/csv.go +++ b/vendor/github.com/go-openapi/runtime/csv.go @@ -21,17 +21,18 @@ import ( // The consumer consumes CSV records from a provided reader into the data passed by reference. // // CSVOpts options may be specified to alter the default CSV behavior on the reader and the writer side (e.g. separator, skip header, ...). -// The defaults are those of the standard library's csv.Reader and csv.Writer. +// The defaults are those of the standard library's [csv.Reader] and [csv.Writer]. // // Supported output underlying types and interfaces, prioritized in this order: -// - *csv.Writer -// - CSVWriter (writer options are ignored) -// - io.Writer (as raw bytes) -// - io.ReaderFrom (as raw bytes) -// - encoding.BinaryUnmarshaler (as raw bytes) -// - *[][]string (as a collection of records) -// - *[]byte (as raw bytes) -// - *string (a raw bytes) +// +// - *[csv.Writer] +// - [CSVWriter] (writer options are ignored) +// - [io.Writer] (as raw bytes) +// - [io.ReaderFrom] (as raw bytes) +// - [encoding.BinaryUnmarshaler] (as raw bytes) +// - *[][]string (as a collection of records) +// - *[]byte (as raw bytes) +// - *string (a raw bytes) // // The consumer prioritizes situations where buffering the input is not required. func CSVConsumer(opts ...CSVOpt) Consumer { @@ -157,11 +158,12 @@ func CSVConsumer(opts ...CSVOpt) Consumer { // The producer takes input data then writes as CSV to an output writer (essentially as a pipe). // // Supported input underlying types and interfaces, prioritized in this order: -// - *csv.Reader -// - CSVReader (reader options are ignored) -// - io.Reader -// - io.WriterTo -// - encoding.BinaryMarshaler +// +// - *[csv.Reader] +// - [CSVReader] (reader options are ignored) +// - [io.Reader] +// - [io.WriterTo] +// - [encoding.BinaryMarshaler] // - [][]string // - []byte // - string @@ -283,7 +285,7 @@ func CSVProducer(opts ...CSVOpt) Producer { }) } -// pipeCSV copies CSV records from a CSV reader to a CSV writer +// pipeCSV copies CSV records from a CSV reader to a CSV writer. func pipeCSV(csvWriter CSVWriter, csvReader CSVReader, opts csvOpts) error { for ; opts.skippedLines > 0; opts.skippedLines-- { _, err := csvReader.Read() diff --git a/vendor/github.com/go-openapi/runtime/csv_options.go b/vendor/github.com/go-openapi/runtime/csv_options.go index 4cc04390..e778c64d 100644 --- a/vendor/github.com/go-openapi/runtime/csv_options.go +++ b/vendor/github.com/go-openapi/runtime/csv_options.go @@ -18,7 +18,7 @@ type csvOpts struct { closeStream bool } -// WithCSVReaderOpts specifies the options to csv.Reader +// WithCSVReaderOpts specifies the options to [csv.Reader] // when reading CSV. func WithCSVReaderOpts(reader csv.Reader) CSVOpt { return func(o *csvOpts) { @@ -26,7 +26,7 @@ func WithCSVReaderOpts(reader csv.Reader) CSVOpt { } } -// WithCSVWriterOpts specifies the options to csv.Writer +// WithCSVWriterOpts specifies the options to [csv.Writer] // when writing CSV. func WithCSVWriterOpts(writer csv.Writer) CSVOpt { return func(o *csvOpts) { @@ -94,7 +94,7 @@ var ( _ CSVReader = &csvRecordsWriter{} ) -// csvRecordsWriter is an internal container to move CSV records back and forth +// csvRecordsWriter is an internal container to move CSV records back and forth. type csvRecordsWriter struct { i int records [][]string diff --git a/vendor/github.com/go-openapi/runtime/doc.go b/vendor/github.com/go-openapi/runtime/doc.go new file mode 100644 index 00000000..300c6b15 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/doc.go @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package runtime exposes runtime client and server components +// for go-openapi toolkit. +package runtime diff --git a/vendor/github.com/go-openapi/runtime/go.work.sum b/vendor/github.com/go-openapi/runtime/go.work.sum index b0c2c9a6..b24a8cfa 100644 --- a/vendor/github.com/go-openapi/runtime/go.work.sum +++ b/vendor/github.com/go-openapi/runtime/go.work.sum @@ -14,6 +14,8 @@ github.com/go-openapi/swag/netutils v0.24.0/go.mod h1:WRgiHcYTnx+IqfMCtu0hy9oOaP github.com/go-openapi/swag/stringutils v0.24.0/go.mod h1:5nUXB4xA0kw2df5PRipZDslPJgJut+NjL7D25zPZ/4w= github.com/go-openapi/swag/typeutils v0.24.0/go.mod h1:q8C3Kmk/vh2VhpCLaoR2MVWOGP8y7Jc8l82qCTd1DYI= github.com/go-openapi/swag/yamlutils v0.24.0/go.mod h1:DpKv5aYuaGm/sULePoeiG8uwMpZSfReo1HR3Ik0yaG8= +github.com/go-openapi/testify/enable/yaml/v2 v2.4.0/go.mod h1:14iV8jyyQlinc9StD7w1xVPW3CO3q1Gj04Jy//Kw4VM= +github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= @@ -26,9 +28,13 @@ github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUt github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30 h1:BHT1/DKsYDGkUgQ2jmMaozVcdk+sVfz0+1ZJq4zkWgw= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= @@ -37,6 +43,7 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= @@ -44,11 +51,15 @@ golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= +golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= +golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -69,11 +80,14 @@ golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457/go.mod h1:pRgIJT+bRLFKnoM1ldnzKoxTIn14Yxz928LQRYYgIN0= golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488/go.mod h1:fGb/2+tgXXjhjHsTNdVEEMZNWA0quBnfrO+AfoDSAKw= +golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2/go.mod h1:b7fPSJ0pKZ3ccUh8gnTONJxhn3c/PS6tyzQvyqw4iA8= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= golang.org/x/term v0.35.0/go.mod h1:TPGtkTLesOwf2DE8CgVYiZinHAOuy5AYUYT1lENIZnA= golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss= +golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= +golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= @@ -88,6 +102,8 @@ golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0 golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/vendor/github.com/go-openapi/runtime/headers.go b/vendor/github.com/go-openapi/runtime/headers.go index 510e396c..4eb2b925 100644 --- a/vendor/github.com/go-openapi/runtime/headers.go +++ b/vendor/github.com/go-openapi/runtime/headers.go @@ -10,7 +10,7 @@ import ( "github.com/go-openapi/errors" ) -// ContentType parses a content type header +// ContentType parses a content type header. func ContentType(headers http.Header) (string, string, error) { ct := headers.Get(HeaderContentType) orig := ct diff --git a/vendor/github.com/go-openapi/runtime/interfaces.go b/vendor/github.com/go-openapi/runtime/interfaces.go index 90046bf3..a8b4b318 100644 --- a/vendor/github.com/go-openapi/runtime/interfaces.go +++ b/vendor/github.com/go-openapi/runtime/interfaces.go @@ -11,75 +11,75 @@ import ( "github.com/go-openapi/strfmt" ) -// OperationHandlerFunc an adapter for a function to the OperationHandler interface +// OperationHandlerFunc an adapter for a function to the [OperationHandler] interface. type OperationHandlerFunc func(any) (any, error) -// Handle implements the operation handler interface +// Handle implements the operation handler interface. func (s OperationHandlerFunc) Handle(data any) (any, error) { return s(data) } -// OperationHandler a handler for a swagger operation +// OperationHandler a handler for a swagger operation. type OperationHandler interface { Handle(any) (any, error) } -// ConsumerFunc represents a function that can be used as a consumer +// ConsumerFunc represents a function that can be used as a consumer. type ConsumerFunc func(io.Reader, any) error -// Consume consumes the reader into the data parameter +// Consume consumes the reader into the data parameter. func (fn ConsumerFunc) Consume(reader io.Reader, data any) error { return fn(reader, data) } // Consumer implementations know how to bind the values on the provided interface to -// data provided by the request body +// data provided by the request body. type Consumer interface { // Consume performs the binding of request values Consume(io.Reader, any) error } -// ProducerFunc represents a function that can be used as a producer +// ProducerFunc represents a function that can be used as a producer. type ProducerFunc func(io.Writer, any) error -// Produce produces the response for the provided data +// Produce produces the response for the provided data. func (f ProducerFunc) Produce(writer io.Writer, data any) error { return f(writer, data) } // Producer implementations know how to turn the provided interface into a valid -// HTTP response +// HTTP response. type Producer interface { // Produce writes to the http response Produce(io.Writer, any) error } -// AuthenticatorFunc turns a function into an authenticator +// AuthenticatorFunc turns a function into an authenticator. type AuthenticatorFunc func(any) (bool, any, error) -// Authenticate authenticates the request with the provided data +// Authenticate authenticates the request with the provided data. func (f AuthenticatorFunc) Authenticate(params any) (bool, any, error) { return f(params) } // Authenticator represents an authentication strategy // implementations of Authenticator know how to authenticate the -// request data and translate that into a valid principal object or an error +// request data and translate that into a valid principal object or an error. type Authenticator interface { Authenticate(any) (bool, any, error) } -// AuthorizerFunc turns a function into an authorizer +// AuthorizerFunc turns a function into an authorizer. type AuthorizerFunc func(*http.Request, any) error -// Authorize authorizes the processing of the request for the principal +// Authorize authorizes the processing of the request for the principal. func (f AuthorizerFunc) Authorize(r *http.Request, principal any) error { return f(r, principal) } // Authorizer represents an authorization strategy // implementations of Authorizer know how to authorize the principal object -// using the request data and returns error if unauthorized +// using the request data and returns error if unauthorized. type Authorizer interface { Authorize(*http.Request, any) error } @@ -87,7 +87,7 @@ type Authorizer interface { // Validatable types implementing this interface allow customizing their validation // this will be used instead of the reflective validation based on the spec document. // the implementations are assumed to have been generated by the swagger tool so they should -// contain all the validations obtained from the spec +// contain all the validations obtained from the spec. type Validatable interface { Validate(strfmt.Registry) error } @@ -95,7 +95,7 @@ type Validatable interface { // ContextValidatable types implementing this interface allow customizing their validation // this will be used instead of the reflective validation based on the spec document. // the implementations are assumed to have been generated by the swagger tool so they should -// contain all the context validations obtained from the spec +// contain all the context validations obtained from the spec. type ContextValidatable interface { ContextValidate(context.Context, strfmt.Registry) error } diff --git a/vendor/github.com/go-openapi/runtime/json.go b/vendor/github.com/go-openapi/runtime/json.go index 8f93eebf..2af5dcfe 100644 --- a/vendor/github.com/go-openapi/runtime/json.go +++ b/vendor/github.com/go-openapi/runtime/json.go @@ -8,7 +8,7 @@ import ( "io" ) -// JSONConsumer creates a new JSON consumer +// JSONConsumer creates a new JSON consumer. func JSONConsumer() Consumer { return ConsumerFunc(func(reader io.Reader, data any) error { dec := json.NewDecoder(reader) @@ -17,7 +17,7 @@ func JSONConsumer() Consumer { }) } -// JSONProducer creates a new JSON producer +// JSONProducer creates a new JSON producer. func JSONProducer() Producer { return ProducerFunc(func(writer io.Writer, data any) error { enc := json.NewEncoder(writer) diff --git a/vendor/github.com/go-openapi/runtime/middleware/context.go b/vendor/github.com/go-openapi/runtime/middleware/context.go index bb00b93b..1f85e86b 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/context.go +++ b/vendor/github.com/go-openapi/runtime/middleware/context.go @@ -24,10 +24,12 @@ import ( "github.com/go-openapi/runtime/security" ) -// Debug when true turns on verbose logging +// Debug when true turns on verbose logging. var Debug = logger.DebugEnabled() -// Logger is the standard libray logger used for printing debug messages +// Logger is the standard library logger used for printing debug messages. +// +// (Note: The correct spelling is "library", not "libra". "Libra" is a zodiac sign/constellation and wouldn't make sense in this context.) var Logger logger.Logger = logger.StandardLogger{} func debugLogfFunc(lg logger.Logger) func(string, ...any) { @@ -43,35 +45,35 @@ func debugLogfFunc(lg logger.Logger) func(string, ...any) { return func(_ string, _ ...any) {} } -// A Builder can create middlewares +// A Builder can create middlewares. type Builder func(http.Handler) http.Handler -// PassthroughBuilder returns the handler, aka the builder identity function +// PassthroughBuilder returns the handler, aka the builder identity function. func PassthroughBuilder(handler http.Handler) http.Handler { return handler } // RequestBinder is an interface for types to implement -// when they want to be able to bind from a request +// when they want to be able to bind from a request. type RequestBinder interface { BindRequest(*http.Request, *MatchedRoute) error } // Responder is an interface for types to implement -// when they want to be considered for writing HTTP responses +// when they want to be considered for writing HTTP responses. type Responder interface { WriteResponse(http.ResponseWriter, runtime.Producer) } -// ResponderFunc wraps a func as a Responder interface +// ResponderFunc wraps a func as a Responder interface. type ResponderFunc func(http.ResponseWriter, runtime.Producer) -// WriteResponse writes to the response +// WriteResponse writes to the response. func (fn ResponderFunc) WriteResponse(rw http.ResponseWriter, pr runtime.Producer) { fn(rw, pr) } -// Context is a type safe wrapper around an untyped request context +// Context is a type safe wrapper around an [untyped] request context // used throughout to store request context with the standard context attached -// to the http.Request +// to the [http.Request]. type Context struct { spec *loads.Document analyzer *analysis.Spec @@ -192,7 +194,7 @@ func (r *routableUntypedAPI) DefaultConsumes() string { // NewRoutableContext creates a new context for a routable API. // -// If a nil Router is provided, the DefaultRouter (denco-based) will be used. +// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Router) *Context { var an *analysis.Spec if spec != nil { @@ -202,9 +204,9 @@ func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Ro return NewRoutableContextWithAnalyzedSpec(spec, an, routableAPI, routes) } -// NewRoutableContextWithAnalyzedSpec is like NewRoutableContext but takes as input an already analysed spec. +// NewRoutableContextWithAnalyzedSpec is like [NewRoutableContext] but takes as input an already analysed spec. // -// If a nil Router is provided, the DefaultRouter (denco-based) will be used. +// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. func NewRoutableContextWithAnalyzedSpec(spec *loads.Document, an *analysis.Spec, routableAPI RoutableAPI, routes Router) *Context { // Either there are no spec doc and analysis, or both of them. if (spec != nil || an != nil) && (spec == nil || an == nil) { @@ -222,7 +224,7 @@ func NewRoutableContextWithAnalyzedSpec(spec *loads.Document, an *analysis.Spec, // NewContext creates a new context wrapper. // -// If a nil Router is provided, the DefaultRouter (denco-based) will be used. +// If a nil Router is provided, the [DefaultRouter] ([denco]-based) will be used. func NewContext(spec *loads.Document, api *untyped.API, routes Router) *Context { var an *analysis.Spec if spec != nil { @@ -239,13 +241,13 @@ func NewContext(spec *loads.Document, api *untyped.API, routes Router) *Context return ctx } -// Serve serves the specified spec with the specified api registrations as a http.Handler +// Serve serves the specified spec with the specified api registrations as a [http.Handler]. func Serve(spec *loads.Document, api *untyped.API) http.Handler { return ServeWithBuilder(spec, api, PassthroughBuilder) } -// ServeWithBuilder serves the specified spec with the specified api registrations as a http.Handler that is decorated -// by the Builder +// ServeWithBuilder serves the specified spec with the specified api registrations as a [http.Handler] that is decorated +// by the Builder. func ServeWithBuilder(spec *loads.Document, api *untyped.API, builder Builder) http.Handler { context := NewContext(spec, api, nil) return context.APIHandler(builder) @@ -294,7 +296,7 @@ type contentTypeValue struct { Charset string } -// BasePath returns the base path for this API +// BasePath returns the base path for this API. func (c *Context) BasePath() string { if c.spec == nil { return "" @@ -309,13 +311,13 @@ func (c *Context) SetLogger(lg logger.Logger) { c.debugLogf = debugLogfFunc(lg) } -// RequiredProduces returns the accepted content types for responses +// RequiredProduces returns the accepted content types for responses. func (c *Context) RequiredProduces() []string { return c.analyzer.RequiredProduces() } // BindValidRequest binds a params object to a request but only when the request is valid -// if the request is not valid an error will be returned +// if the request is not valid an error will be returned. func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, binder RequestBinder) error { var res []error var requestContentType string @@ -374,7 +376,7 @@ func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, b // Returns the media type, its charset and a shallow copy of the request // when its context doesn't contain the content type value, otherwise it returns // the same request -// Returns the error that runtime.ContentType may retunrs. +// Returns the error that [runtime.ContentType] may returns. func (c *Context) ContentType(request *http.Request) (string, string, *http.Request, error) { var rCtx = request.Context() @@ -390,7 +392,7 @@ func (c *Context) ContentType(request *http.Request) (string, string, *http.Requ return mt, cs, request.WithContext(rCtx), nil } -// LookupRoute looks a route up and returns true when it is found +// LookupRoute looks a route up and returns true when it is found. func (c *Context) LookupRoute(request *http.Request) (*MatchedRoute, bool) { if route, ok := c.router.Lookup(request.Method, request.URL.EscapedPath()); ok { return route, ok @@ -402,7 +404,7 @@ func (c *Context) LookupRoute(request *http.Request) (*MatchedRoute, bool) { // Returns the matched route, a shallow copy of the request if its context // contains the matched router, otherwise the same request, and a bool to // indicate if it the request matches one of the routes, if it doesn't -// then it returns false and nil for the other two return values +// then it returns false and nil for the other two return values. func (c *Context) RouteInfo(request *http.Request) (*MatchedRoute, *http.Request, bool) { var rCtx = request.Context() @@ -420,7 +422,7 @@ func (c *Context) RouteInfo(request *http.Request) (*MatchedRoute, *http.Request // ResponseFormat negotiates the response content type // Returns the response format and a shallow copy of the request if its context -// doesn't contain the response format, otherwise the same request +// doesn't contain the response format, otherwise the same request. func (c *Context) ResponseFormat(r *http.Request, offers []string) (string, *http.Request) { var rCtx = r.Context() @@ -438,12 +440,12 @@ func (c *Context) ResponseFormat(r *http.Request, offers []string) (string, *htt return format, r } -// AllowedMethods gets the allowed methods for the path of this request +// AllowedMethods gets the allowed methods for the path of this request. func (c *Context) AllowedMethods(request *http.Request) []string { return c.router.OtherMethods(request.Method, request.URL.EscapedPath()) } -// ResetAuth removes the current principal from the request context +// ResetAuth removes the current principal from the request context. func (c *Context) ResetAuth(request *http.Request) *http.Request { rctx := request.Context() rctx = stdContext.WithValue(rctx, ctxSecurityPrincipal, nil) @@ -454,7 +456,7 @@ func (c *Context) ResetAuth(request *http.Request) *http.Request { // Authorize authorizes the request // Returns the principal object and a shallow copy of the request when its // context doesn't contain the principal, otherwise the same request or an error -// (the last) if one of the authenticators returns one or an Unauthenticated error +// (the last) if one of the authenticators returns one or an Unauthenticated error. func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (any, *http.Request, error) { if route == nil || !route.HasAuth() { return nil, nil, nil @@ -492,7 +494,7 @@ func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (any, *h // BindAndValidate binds and validates the request // Returns the validation map and a shallow copy of the request when its context // doesn't contain the validation, otherwise it returns the same request or an -// CompositeValidationError error +// CompositeValidationError error. func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (any, *http.Request, error) { var rCtx = request.Context() @@ -513,12 +515,12 @@ func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) return result.bound, request, nil } -// NotFound the default not found responder for when no route has been matched yet +// NotFound the default not found responder for when no route has been matched yet. func (c *Context) NotFound(rw http.ResponseWriter, r *http.Request) { c.Respond(rw, r, []string{c.api.DefaultProduces()}, nil, errors.NotFound("not found")) } -// Respond renders the response after doing some content negotiation +// Respond renders the response after doing some content negotiation. func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data any) { c.debugLogf("responding to %s %s with produces: %v", r.Method, r.URL.Path, produces) offers := []string{} @@ -616,7 +618,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st // // This handler includes a swagger spec, router and the contract defined in the swagger spec. // -// A spec UI (SwaggerUI) is served at {API base path}/docs and the spec document at /swagger.json +// A spec UI ([SwaggerUI]) is served at {API base path}/docs and the spec document at /swagger.json // (these can be modified with uiOptions). func (c *Context) APIHandlerSwaggerUI(builder Builder, opts ...UIOption) http.Handler { b := builder @@ -635,7 +637,7 @@ func (c *Context) APIHandlerSwaggerUI(builder Builder, opts ...UIOption) http.Ha // // This handler includes a swagger spec, router and the contract defined in the swagger spec. // -// A spec UI (RapiDoc) is served at {API base path}/docs and the spec document at /swagger.json +// A spec UI ([RapiDoc]) is served at {API base path}/docs and the spec document at /swagger.json // (these can be modified with uiOptions). func (c *Context) APIHandlerRapiDoc(builder Builder, opts ...UIOption) http.Handler { b := builder @@ -654,7 +656,7 @@ func (c *Context) APIHandlerRapiDoc(builder Builder, opts ...UIOption) http.Hand // // This handler includes a swagger spec, router and the contract defined in the swagger spec. // -// A spec UI (Redoc) is served at {API base path}/docs and the spec document at /swagger.json +// A spec UI ([Redoc]) is served at {API base path}/docs and the spec document at /swagger.json // (these can be modified with uiOptions). func (c *Context) APIHandler(builder Builder, opts ...UIOption) http.Handler { b := builder @@ -669,7 +671,7 @@ func (c *Context) APIHandler(builder Builder, opts ...UIOption) http.Handler { return Spec(specPath, c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b)), specOpts...) } -// RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec +// RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec. func (c *Context) RoutesHandler(builder Builder) http.Handler { b := builder if b == nil { @@ -686,10 +688,12 @@ func (c Context) uiOptionsForHandler(opts []UIOption) (string, uiOptions, []Spec } // default options (may be overridden) - optsForContext := []UIOption{ + const baseOptions = 2 + optsForContext := make([]UIOption, 0, len(opts)+baseOptions) + optsForContext = append(optsForContext, WithUIBasePath(c.BasePath()), WithUITitle(title), - } + ) optsForContext = append(optsForContext, opts...) uiOpts := uiOptionsWithDefaults(optsForContext) diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/README.md b/vendor/github.com/go-openapi/runtime/middleware/denco/README.md index 30109e17..03e0b7f4 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/README.md +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/README.md @@ -8,7 +8,7 @@ However, Denco is optimized and some features added. ## Features * Fast (See [go-http-routing-benchmark](https://github.com/naoina/go-http-routing-benchmark)) -* [URL patterns](#url-patterns) (`/foo/:bar` and `/foo/*wildcard`) +*[URL patterns](#url-patterns) (`/foo/:bar` and `/foo/*wildcard`) * Small (but enough) URL router API * HTTP request multiplexer like `http.ServeMux` diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go index b371a2cf..f89d761c 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2014 Naoya Inada +// SPDX-License-Identifier: MIT // Package denco provides fast URL router. package denco @@ -24,7 +26,7 @@ const ( // SeparatorCharacter separates path segments. SeparatorCharacter = '/' - // PathParamCharacter indicates a RESTCONF path param + // PathParamCharacter indicates a RESTCONF path param. PathParamCharacter = '=' // MaxSize is max size of records and internal slice. @@ -52,7 +54,7 @@ func New() *Router { } // Lookup returns data and path parameters that associated with path. -// params is a slice of the Param that arranged in the order in which parameters appeared. +// params is a slice of the [Param] that arranged in the order in which parameters appeared. // e.g. when built routing path is "/path/to/:id/:name" and given path is "/path/to/1/alice". params order is [{"id": "1"}, {"name": "alice"}], not [{"name": "alice"}, {"id": "1"}]. func (rt *Router) Lookup(path string) (data any, params Params, found bool) { if data, found = rt.static[path]; found { @@ -138,7 +140,7 @@ func newDoubleArray() *doubleArray { // BASE (22bit) | Extra flags (2bit) | CHECK (8bit) // // |----------------------|--|--------| -// 32 10 8 0 +// 32 10 8 0. type baseCheck uint32 const ( @@ -155,7 +157,7 @@ func (bc *baseCheck) SetBase(base int) { } func (bc baseCheck) Check() byte { - return byte(bc) + return byte(bc) //nolint:gosec // integer conversion is ok } func (bc *baseCheck) SetCheck(check byte) { @@ -212,7 +214,7 @@ func (da *doubleArray) lookup(path string, params []Param, idx int) (*node, []Pa BACKTRACKING: for j := len(indices) - 1; j >= 0; j-- { - i, idx := int(indices[j]>>indexOffset), int(indices[j]&indexMask) //nolint:gosec // integer conversion is okay + i, idx := int(indices[j]>>indexOffset), int(indices[j]&indexMask) if da.bc[idx].IsSingleParam() { nextIdx := nextIndex(da.bc[idx].Base(), ParamCharacter) if nextIdx >= len(da.bc) { diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/server.go b/vendor/github.com/go-openapi/runtime/middleware/denco/server.go index 8f04d93d..e6c0976d 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/server.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/server.go @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2014 Naoya Inada +// SPDX-License-Identifier: MIT package denco @@ -10,27 +12,27 @@ import ( // Mux represents a multiplexer for HTTP request. type Mux struct{} -// NewMux returns a new Mux. +// NewMux returns a new [Mux]. func NewMux() *Mux { return &Mux{} } -// GET is shorthand of Mux.Handler("GET", path, handler). +// GET is shorthand of [Mux].Handler("GET", path, handler). func (m *Mux) GET(path string, handler HandlerFunc) Handler { return m.Handler("GET", path, handler) } -// POST is shorthand of Mux.Handler("POST", path, handler). +// POST is shorthand of [Mux].Handler("POST", path, handler). func (m *Mux) POST(path string, handler HandlerFunc) Handler { return m.Handler("POST", path, handler) } -// PUT is shorthand of Mux.Handler("PUT", path, handler). +// PUT is shorthand of [Mux].Handler("PUT", path, handler). func (m *Mux) PUT(path string, handler HandlerFunc) Handler { return m.Handler("PUT", path, handler) } -// HEAD is shorthand of Mux.Handler("HEAD", path, handler). +// HEAD is shorthand of [Mux].Handler("HEAD", path, handler). func (m *Mux) HEAD(path string, handler HandlerFunc) Handler { return m.Handler("HEAD", path, handler) } @@ -44,7 +46,7 @@ func (m *Mux) Handler(method, path string, handler HandlerFunc) Handler { } } -// Build builds a http.Handler. +// Build builds a [http.Handler]. func (m *Mux) Build(handlers []Handler) (http.Handler, error) { recordMap := make(map[string][]Record) for _, h := range handlers { @@ -73,7 +75,7 @@ type Handler struct { Func HandlerFunc } -// The HandlerFunc type is aliased to type of handler function. +// HandlerFunc is aliased to type of handler function. type HandlerFunc func(w http.ResponseWriter, r *http.Request, params Params) type serveMux struct { diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/util.go b/vendor/github.com/go-openapi/runtime/middleware/denco/util.go index f002bc46..e7da4226 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/util.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/util.go @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2014 Naoya Inada +// SPDX-License-Identifier: MIT package denco diff --git a/vendor/github.com/go-openapi/runtime/middleware/doc.go b/vendor/github.com/go-openapi/runtime/middleware/doc.go index 04b83223..f78ec52c 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/doc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/doc.go @@ -1,52 +1,50 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 -/* -Package middleware provides the library with helper functions for serving swagger APIs. - -Pseudo middleware handler - - import ( - "net/http" - - "github.com/go-openapi/errors" - ) - - func newCompleteMiddleware(ctx *Context) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - // use context to lookup routes - if matched, ok := ctx.RouteInfo(r); ok { - - if matched.NeedsAuth() { - if _, err := ctx.Authorize(r, matched); err != nil { - ctx.Respond(rw, r, matched.Produces, matched, err) - return - } - } - - bound, validation := ctx.BindAndValidate(r, matched) - if validation != nil { - ctx.Respond(rw, r, matched.Produces, matched, validation) - return - } - - result, err := matched.Handler.Handle(bound) - if err != nil { - ctx.Respond(rw, r, matched.Produces, matched, err) - return - } - - ctx.Respond(rw, r, matched.Produces, matched, result) - return - } - - // Not found, check if it exists in the other methods first - if others := ctx.AllowedMethods(r); len(others) > 0 { - ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others)) - return - } - ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.Path)) - }) - } -*/ +// Package middleware provides the library with helper functions for serving swagger APIs. +// +// Pseudo middleware handler. +// +// import ( +// "net/http" +// +// "github.com/go-openapi/errors" +// ) +// +// func newCompleteMiddleware(ctx *Context) http.Handler { +// return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { +// // use context to lookup routes +// if matched, ok := ctx.RouteInfo(r); ok { +// +// if matched.NeedsAuth() { +// if _, err := ctx.Authorize(r, matched); err != nil { +// ctx.Respond(rw, r, matched.Produces, matched, err) +// return +// } +// } +// +// bound, validation := ctx.BindAndValidate(r, matched) +// if validation != nil { +// ctx.Respond(rw, r, matched.Produces, matched, validation) +// return +// } +// +// result, err := matched.Handler.Handle(bound) +// if err != nil { +// ctx.Respond(rw, r, matched.Produces, matched, err) +// return +// } +// +// ctx.Respond(rw, r, matched.Produces, matched, result) +// return +// } +// +// // Not found, check if it exists in the other methods first +// if others := ctx.AllowedMethods(r); len(others) > 0 { +// ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others)) +// return +// } +// ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.Path)) +// }) +// } package middleware diff --git a/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go b/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go index 2e63780c..4d286a6c 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go +++ b/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go @@ -31,13 +31,13 @@ func (e *errorResp) WriteResponse(rw http.ResponseWriter, producer runtime.Produ } } -// NotImplemented the error response when the response is not implemented +// NotImplemented the error response when the response is not implemented. func NotImplemented(message string) Responder { return Error(http.StatusNotImplemented, message) } // Error creates a generic responder for returning errors, the data will be serialized -// with the matching producer for the request +// with the matching producer for the request. func Error(code int, data any, headers ...http.Header) Responder { var hdr http.Header for _, h := range headers { diff --git a/vendor/github.com/go-openapi/runtime/middleware/operation.go b/vendor/github.com/go-openapi/runtime/middleware/operation.go index 2a7ab1fa..24f466b5 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/operation.go +++ b/vendor/github.com/go-openapi/runtime/middleware/operation.go @@ -5,7 +5,7 @@ package middleware import "net/http" -// NewOperationExecutor creates a context aware middleware that handles the operations after routing +// NewOperationExecutor creates a context aware [middleware] that handles the operations after routing. func NewOperationExecutor(ctx *Context) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { // use context to lookup routes diff --git a/vendor/github.com/go-openapi/runtime/middleware/parameter.go b/vendor/github.com/go-openapi/runtime/middleware/parameter.go index 7d630d6c..a9d2a364 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/parameter.go +++ b/vendor/github.com/go-openapi/runtime/middleware/parameter.go @@ -28,7 +28,7 @@ const ( typeArray = "array" ) -var textUnmarshalType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem() +var textUnmarshalType = reflect.TypeFor[encoding.TextUnmarshaler]() func newUntypedParamBinder(param spec.Parameter, spec *spec.Swagger, formats strfmt.Registry) *untypedParamBinder { binder := new(untypedParamBinder) diff --git a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go b/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go index 6039a26f..1574defb 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go @@ -11,7 +11,7 @@ import ( "path" ) -// RapiDocOpts configures the RapiDoc middlewares +// RapiDocOpts configures the [RapiDoc] middlewares. type RapiDocOpts struct { // BasePath for the UI, defaults to: / BasePath string @@ -50,9 +50,9 @@ func (r *RapiDocOpts) EnsureDefaults() { } } -// RapiDoc creates a middleware to serve a documentation site for a swagger spec. +// RapiDoc creates a [middleware] to serve a documentation site for a swagger spec. // -// This allows for altering the spec before starting the http listener. +// This allows for altering the spec before starting the [http] listener. func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler { opts.EnsureDefaults() diff --git a/vendor/github.com/go-openapi/runtime/middleware/redoc.go b/vendor/github.com/go-openapi/runtime/middleware/redoc.go index cbaec73c..1007409a 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/redoc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/redoc.go @@ -11,7 +11,7 @@ import ( "path" ) -// RedocOpts configures the Redoc middlewares +// RedocOpts configures the [Redoc] middlewares. type RedocOpts struct { // BasePath for the UI, defaults to: / BasePath string @@ -36,7 +36,7 @@ type RedocOpts struct { RedocURL string } -// EnsureDefaults in case some options are missing +// EnsureDefaults in case some options are missing. func (r *RedocOpts) EnsureDefaults() { common := toCommonUIOptions(r) common.EnsureDefaults() @@ -51,9 +51,9 @@ func (r *RedocOpts) EnsureDefaults() { } } -// Redoc creates a middleware to serve a documentation site for a swagger spec. +// Redoc creates a [middleware] to serve a documentation site for a swagger spec. // -// This allows for altering the spec before starting the http listener. +// This allows for altering the spec before starting the [http] listener. func Redoc(opts RedocOpts, next http.Handler) http.Handler { opts.EnsureDefaults() diff --git a/vendor/github.com/go-openapi/runtime/middleware/request.go b/vendor/github.com/go-openapi/runtime/middleware/request.go index 52facfef..ad781663 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/request.go +++ b/vendor/github.com/go-openapi/runtime/middleware/request.go @@ -14,7 +14,7 @@ import ( "github.com/go-openapi/strfmt" ) -// UntypedRequestBinder binds and validates the data from a http request +// UntypedRequestBinder binds and validates the data from a [http] request. type UntypedRequestBinder struct { Spec *spec.Swagger Parameters map[string]spec.Parameter @@ -38,7 +38,7 @@ func NewUntypedRequestBinder(parameters map[string]spec.Parameter, spec *spec.Sw } } -// Bind perform the databinding and validation +// Bind perform the databinding and validation. func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, data any) error { val := reflect.Indirect(reflect.ValueOf(data)) isMap := val.Kind() == reflect.Map diff --git a/vendor/github.com/go-openapi/runtime/middleware/router.go b/vendor/github.com/go-openapi/runtime/middleware/router.go index 16816580..e828653b 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/router.go @@ -25,16 +25,16 @@ import ( // RouteParam is a object to capture route params in a framework agnostic way. // implementations of the muxer should use these route params to communicate with the -// swagger framework +// swagger framework. type RouteParam struct { Name string Value string } -// RouteParams the collection of route params +// RouteParams the collection of route params. type RouteParams []RouteParam -// Get gets the value for the route param for the specified key +// Get gets the value for the route param for the specified key. func (r RouteParams) Get(name string) string { vv, _, _ := r.GetOK(name) if len(vv) > 0 { @@ -44,9 +44,9 @@ func (r RouteParams) Get(name string) string { } // GetOK gets the value but also returns booleans to indicate if a key or value -// is present. This aids in validation and satisfies an interface in use there +// is present. This aids in validation and satisfies an interface in use there. // -// The returned values are: data, has key, has value +// The returned values are: data, has key, has value. func (r RouteParams) GetOK(name string) ([]string, bool, bool) { for _, p := range r { if p.Name == name { @@ -56,7 +56,7 @@ func (r RouteParams) GetOK(name string) ([]string, bool, bool) { return nil, false, false } -// NewRouter creates a new context-aware router middleware +// NewRouter creates a new context-aware router [middleware]. func NewRouter(ctx *Context, next http.Handler) http.Handler { if ctx.router == nil { ctx.router = DefaultRouter(ctx.spec, ctx.api, WithDefaultRouterLoggerFunc(ctx.debugLogf)) @@ -68,18 +68,22 @@ func NewRouter(ctx *Context, next http.Handler) http.Handler { return } + // Always use the default producer Content-Type for Method not + // allowed and Not found responses + produces := []string{ctx.api.DefaultProduces()} + // Not found, check if it exists in the other methods first if others := ctx.AllowedMethods(r); len(others) > 0 { - ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others)) + ctx.Respond(rw, r, produces, nil, errors.MethodNotAllowed(r.Method, others)) return } - ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.EscapedPath())) + ctx.Respond(rw, r, produces, nil, errors.NotFound("path %s was not found", r.URL.EscapedPath())) }) } // RoutableAPI represents an interface for things that can serve -// as a provider of implementations for the swagger router +// as a provider of implementations for the swagger router. type RoutableAPI interface { HandlerFor(string, string) (http.Handler, bool) ServeErrorFor(string) func(http.ResponseWriter, *http.Request, error) @@ -92,7 +96,7 @@ type RoutableAPI interface { DefaultConsumes() string } -// Router represents a swagger-aware router +// Router represents a swagger-aware router. type Router interface { Lookup(method, path string) (*MatchedRoute, bool) OtherMethods(method, path string) []string @@ -153,7 +157,7 @@ func WithDefaultRouterLoggerFunc(fn func(string, ...any)) DefaultRouterOpt { } } -// DefaultRouter creates a default implementation of the router +// DefaultRouter creates a default implementation of the router. func DefaultRouter(spec *loads.Document, api RoutableAPI, opts ...DefaultRouterOpt) Router { builder := newDefaultRouteBuilder(spec, api, opts...) if spec != nil { @@ -170,7 +174,7 @@ func DefaultRouter(spec *loads.Document, api RoutableAPI, opts ...DefaultRouterO // RouteAuthenticator is an authenticator that can compose several authenticators together. // It also knows when it contains an authenticator that allows for anonymous pass through. -// Contains a group of 1 or more authenticators that have a logical AND relationship +// Contains a group of 1 or more authenticators that have a logical AND relationship. type RouteAuthenticator struct { Authenticator map[string]runtime.Authenticator Schemes []string @@ -185,18 +189,18 @@ func (ra *RouteAuthenticator) AllowsAnonymous() bool { } // AllScopes returns a list of unique scopes that is the combination -// of all the scopes in the requirements +// of all the scopes in the requirements. func (ra *RouteAuthenticator) AllScopes() []string { return ra.allScopes } // CommonScopes returns a list of unique scopes that are common in all the -// scopes in the requirements +// scopes in the requirements. func (ra *RouteAuthenticator) CommonScopes() []string { return ra.commonScopes } -// Authenticate Authenticator interface implementation +// Authenticate Authenticator interface implementation. func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, any, error) { if ra.allowAnonymous { route.Authenticator = ra @@ -262,10 +266,10 @@ func stringSliceIntersection(slices ...[]string) []string { return intersection } -// RouteAuthenticators represents a group of authenticators that represent a logical OR +// RouteAuthenticators represents a group of authenticators that represent a logical OR. type RouteAuthenticators []RouteAuthenticator -// AllowsAnonymous returns true when there is an authenticator that means optional auth +// AllowsAnonymous returns true when there is an authenticator that means optional auth. func (ras RouteAuthenticators) AllowsAnonymous() bool { for _, ra := range ras { if ra.AllowsAnonymous() { @@ -275,7 +279,7 @@ func (ras RouteAuthenticators) AllowsAnonymous() bool { return false } -// Authenticate method implemention so this collection can be used as authenticator +// Authenticate method implementation so this collection can be used as authenticator. func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, any, error) { var lastError error var allowsAnon bool @@ -320,7 +324,7 @@ type routeEntry struct { Authorizer runtime.Authorizer } -// MatchedRoute represents the route that was matched in this request +// MatchedRoute represents the route that was matched in this request. type MatchedRoute struct { routeEntry @@ -330,13 +334,13 @@ type MatchedRoute struct { Authenticator *RouteAuthenticator } -// HasAuth returns true when the route has a security requirement defined +// HasAuth returns true when the route has a security requirement defined. func (m *MatchedRoute) HasAuth() bool { return len(m.Authenticators) > 0 } // NeedsAuth returns true when the request still -// needs to perform authentication +// needs to perform authentication. func (m *MatchedRoute) NeedsAuth() bool { return m.HasAuth() && m.Authenticator == nil } @@ -407,7 +411,7 @@ func (d *defaultRouter) SetLogger(lg logger.Logger) { d.debugLogf = debugLogfFunc(lg) } -// convert swagger parameters per path segment into a denco parameter as multiple parameters per segment are not supported in denco +// convert swagger parameters per path segment into a denco parameter as multiple parameters per segment are not supported in denco. var pathConverter = regexp.MustCompile(`{(.+?)}([^/]*)`) func decodeCompositParams(name string, value string, pattern string, names []string, values []string) ([]string, []string) { diff --git a/vendor/github.com/go-openapi/runtime/middleware/spec.go b/vendor/github.com/go-openapi/runtime/middleware/spec.go index 9cc9940a..0a64a957 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/spec.go +++ b/vendor/github.com/go-openapi/runtime/middleware/spec.go @@ -13,7 +13,7 @@ const ( applicationJSON = "application/json" ) -// SpecOption can be applied to the Spec serving middleware +// SpecOption can be applied to the Spec serving [middleware]. type SpecOption func(*specOptions) var defaultSpecOptions = specOptions{ @@ -35,12 +35,12 @@ func specOptionsWithDefaults(opts []SpecOption) specOptions { return o } -// Spec creates a middleware to serve a swagger spec as a JSON document. +// Spec creates a [middleware] to serve a swagger spec as a JSON document. // -// This allows for altering the spec before starting the http listener. +// This allows for altering the spec before starting the [http] listener. // // The basePath argument indicates the path of the spec document (defaults to "/"). -// Additional SpecOption can be used to change the name of the document (defaults to "swagger.json"). +// Additional [SpecOption] can be used to change the name of the document (defaults to "swagger.json"). func Spec(basePath string, b []byte, next http.Handler, opts ...SpecOption) http.Handler { if basePath == "" { basePath = "/" @@ -68,7 +68,7 @@ func Spec(basePath string, b []byte, next http.Handler, opts ...SpecOption) http }) } -// WithSpecPath sets the path to be joined to the base path of the Spec middleware. +// WithSpecPath sets the path to be joined to the base path of the Spec [middleware]. // // This is empty by default. func WithSpecPath(pth string) SpecOption { @@ -79,7 +79,7 @@ func WithSpecPath(pth string) SpecOption { // WithSpecDocument sets the name of the JSON document served as a spec. // -// By default, this is "swagger.json" +// By default, this is "swagger.json". func WithSpecDocument(doc string) SpecOption { return func(o *specOptions) { if doc == "" { diff --git a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go b/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go index b25a3a2c..14ed37ce 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go +++ b/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go @@ -11,7 +11,7 @@ import ( "path" ) -// SwaggerUIOpts configures the SwaggerUI middleware +// SwaggerUIOpts configures the [SwaggerUI] [middleware]. type SwaggerUIOpts struct { // BasePath for the API, defaults to: / BasePath string @@ -47,7 +47,7 @@ type SwaggerUIOpts struct { Favicon16 string } -// EnsureDefaults in case some options are missing +// EnsureDefaults in case some options are missing. func (r *SwaggerUIOpts) EnsureDefaults() { r.ensureDefaults() @@ -90,9 +90,9 @@ func (r *SwaggerUIOpts) ensureDefaults() { } } -// SwaggerUI creates a middleware to serve a documentation site for a swagger spec. +// SwaggerUI creates a [middleware] to serve a documentation site for a swagger spec. // -// This allows for altering the spec before starting the http listener. +// This allows for altering the spec before starting the [http] listener. func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler { opts.EnsureDefaults() diff --git a/vendor/github.com/go-openapi/runtime/middleware/ui_options.go b/vendor/github.com/go-openapi/runtime/middleware/ui_options.go index cf2f673d..ed255426 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/ui_options.go +++ b/vendor/github.com/go-openapi/runtime/middleware/ui_options.go @@ -13,7 +13,7 @@ import ( ) const ( - // constants that are common to all UI-serving middlewares + // constants that are common to all UI-serving middlewares. defaultDocsPath = "docs" defaultDocsURL = "/swagger.json" defaultDocsTitle = "API Documentation" @@ -75,8 +75,8 @@ func fromCommonToAnyOptions[T any](source uiOptions, target *T) { } } -// UIOption can be applied to UI serving middleware, such as Context.APIHandler or -// Context.APIHandlerSwaggerUI to alter the defaut behavior. +// UIOption can be applied to UI serving [middleware], such as Context.[APIHandler] or +// Context.[APIHandlerSwaggerUI] to alter the default behavior. type UIOption func(*uiOptions) func uiOptionsWithDefaults(opts []UIOption) uiOptions { @@ -90,7 +90,7 @@ func uiOptionsWithDefaults(opts []UIOption) uiOptions { // WithUIBasePath sets the base path from where to serve the UI assets. // -// By default, Context middleware sets this value to the API base path. +// By default, Context [middleware] sets this value to the API base path. func WithUIBasePath(base string) UIOption { return func(o *uiOptions) { if !strings.HasPrefix(base, "/") { @@ -111,7 +111,7 @@ func WithUIPath(pth string) UIOption { // // This may be specified as a full URL or a path. // -// By default, this is "/swagger.json" +// By default, this is "/swagger.json". func WithUISpecURL(specURL string) UIOption { return func(o *uiOptions) { o.SpecURL = specURL @@ -120,7 +120,7 @@ func WithUISpecURL(specURL string) UIOption { // WithUITitle sets the title of the UI. // -// By default, Context middleware sets this value to the title found in the API spec. +// By default, Context [middleware] sets this value to the title found in the API spec. func WithUITitle(title string) UIOption { return func(o *uiOptions) { o.Title = title @@ -129,14 +129,14 @@ func WithUITitle(title string) UIOption { // WithTemplate allows to set a custom template for the UI. // -// UI middleware will panic if the template does not parse or execute properly. +// UI [middleware] will panic if the template does not parse or execute properly. func WithTemplate(tpl string) UIOption { return func(o *uiOptions) { o.Template = tpl } } -// EnsureDefaults in case some options are missing +// EnsureDefaults in case some options are missing. func (r *uiOptions) EnsureDefaults() { if r.BasePath == "" { r.BasePath = "/" diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go b/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go index 774da0ba..f4c966ba 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go +++ b/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go @@ -23,7 +23,7 @@ const ( mediumPreallocatedSlots = 30 ) -// API represents an untyped mux for a swagger spec +// API represents an untyped mux for a swagger spec. type API struct { spec *loads.Document analyzer *analysis.Spec @@ -39,7 +39,7 @@ type API struct { formats strfmt.Registry } -// NewAPI creates the default untyped API +// NewAPI creates the default untyped API. func NewAPI(spec *loads.Document) *API { var an *analysis.Spec if spec != nil && spec.Spec() != nil { @@ -60,7 +60,7 @@ func NewAPI(spec *loads.Document) *API { return api.WithJSONDefaults() } -// WithJSONDefaults loads the json defaults for this api +// WithJSONDefaults loads the json defaults for this api. func (d *API) WithJSONDefaults() *API { d.DefaultConsumes = runtime.JSONMime d.DefaultProduces = runtime.JSONMime @@ -69,7 +69,7 @@ func (d *API) WithJSONDefaults() *API { return d } -// WithoutJSONDefaults clears the json defaults for this api +// WithoutJSONDefaults clears the json defaults for this api. func (d *API) WithoutJSONDefaults() *API { d.DefaultConsumes = "" d.DefaultProduces = "" @@ -78,7 +78,7 @@ func (d *API) WithoutJSONDefaults() *API { return d } -// Formats returns the registered string formats +// Formats returns the registered string formats. func (d *API) Formats() strfmt.Registry { if d.formats == nil { d.formats = strfmt.NewFormats() @@ -86,7 +86,7 @@ func (d *API) Formats() strfmt.Registry { return d.formats } -// RegisterFormat registers a custom format validator +// RegisterFormat registers a custom format validator. func (d *API) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { if d.formats == nil { d.formats = strfmt.NewFormats() @@ -94,7 +94,7 @@ func (d *API) RegisterFormat(name string, format strfmt.Format, validator strfmt d.formats.Add(name, format, validator) } -// RegisterAuth registers an auth handler in this api +// RegisterAuth registers an auth handler in this api. func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) { if d.authenticators == nil { d.authenticators = make(map[string]runtime.Authenticator) @@ -102,7 +102,7 @@ func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) { d.authenticators[scheme] = handler } -// RegisterAuthorizer registers an authorizer handler in this api +// RegisterAuthorizer registers an authorizer handler in this api. func (d *API) RegisterAuthorizer(handler runtime.Authorizer) { d.authorizer = handler } @@ -115,7 +115,7 @@ func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) { d.consumers[strings.ToLower(mediaType)] = handler } -// RegisterProducer registers a producer for a media type +// RegisterProducer registers a producer for a media type. func (d *API) RegisterProducer(mediaType string, handler runtime.Producer) { if d.producers == nil { d.producers = make(map[string]runtime.Producer, smallPreallocatedSlots) @@ -123,7 +123,7 @@ func (d *API) RegisterProducer(mediaType string, handler runtime.Producer) { d.producers[strings.ToLower(mediaType)] = handler } -// RegisterOperation registers an operation handler for an operation name +// RegisterOperation registers an operation handler for an operation name. func (d *API) RegisterOperation(method, path string, handler runtime.OperationHandler) { if d.operations == nil { d.operations = make(map[string]map[string]runtime.OperationHandler, mediumPreallocatedSlots) @@ -135,7 +135,7 @@ func (d *API) RegisterOperation(method, path string, handler runtime.OperationHa d.operations[um][path] = handler } -// OperationHandlerFor returns the operation handler for the specified id if it can be found +// OperationHandlerFor returns the operation handler for the specified id if it can be found. func (d *API) OperationHandlerFor(method, path string) (runtime.OperationHandler, bool) { if d.operations == nil { return nil, false @@ -147,7 +147,7 @@ func (d *API) OperationHandlerFor(method, path string) (runtime.OperationHandler return nil, false } -// ConsumersFor gets the consumers for the specified media types +// ConsumersFor gets the consumers for the specified media types. func (d *API) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { result := make(map[string]runtime.Consumer) for _, mt := range mediaTypes { @@ -158,7 +158,7 @@ func (d *API) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { return result } -// ProducersFor gets the producers for the specified media types +// ProducersFor gets the producers for the specified media types. func (d *API) ProducersFor(mediaTypes []string) map[string]runtime.Producer { result := make(map[string]runtime.Producer) for _, mt := range mediaTypes { @@ -169,7 +169,7 @@ func (d *API) ProducersFor(mediaTypes []string) map[string]runtime.Producer { return result } -// AuthenticatorsFor gets the authenticators for the specified security schemes +// AuthenticatorsFor gets the authenticators for the specified security schemes. func (d *API) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { result := make(map[string]runtime.Authenticator) for k := range schemes { @@ -180,17 +180,17 @@ func (d *API) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[stri return result } -// Authorizer returns the registered authorizer +// Authorizer returns the registered authorizer. func (d *API) Authorizer() runtime.Authorizer { return d.authorizer } -// Validate validates this API for any missing items +// Validate validates this API for any missing items. func (d *API) Validate() error { return d.validate() } -// validateWith validates the registrations in this API against the provided spec analyzer +// validateWith validates the registrations in this API against the provided spec analyzer. func (d *API) validate() error { consumes := make([]string, 0, len(d.consumers)) for k := range d.consumers { diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation.go b/vendor/github.com/go-openapi/runtime/middleware/validation.go index ed026d62..8a564906 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/validation.go +++ b/vendor/github.com/go-openapi/runtime/middleware/validation.go @@ -21,7 +21,7 @@ type validation struct { bound map[string]any } -// ContentType validates the content type of a request +// ContentType validates the content type of a request. func validateContentType(allowed []string, actual string) error { if len(allowed) == 0 { return nil diff --git a/vendor/github.com/go-openapi/runtime/request.go b/vendor/github.com/go-openapi/runtime/request.go index aab7b8c0..5c45339a 100644 --- a/vendor/github.com/go-openapi/runtime/request.go +++ b/vendor/github.com/go-openapi/runtime/request.go @@ -14,25 +14,25 @@ import ( "github.com/go-openapi/swag/stringutils" ) -// CanHaveBody returns true if this method can have a body +// CanHaveBody returns true if this method can have a body. func CanHaveBody(method string) bool { mn := strings.ToUpper(method) return mn == "POST" || mn == "PUT" || mn == "PATCH" || mn == "DELETE" } -// IsSafe returns true if this is a request with a safe method +// IsSafe returns true if this is a request with a safe method. func IsSafe(r *http.Request) bool { mn := strings.ToUpper(r.Method) return mn == "GET" || mn == "HEAD" } -// AllowsBody returns true if the request allows for a body +// AllowsBody returns true if the request allows for a body. func AllowsBody(r *http.Request) bool { mn := strings.ToUpper(r.Method) return mn != "HEAD" } -// HasBody returns true if this method needs a content-type +// HasBody returns true if this method needs a content-type. func HasBody(r *http.Request) bool { // happy case: we have a content length set if r.ContentLength > 0 { @@ -104,9 +104,9 @@ func (p *peekingReader) Close() error { return nil } -// JSONRequest creates a new http request with json headers set. +// JSONRequest creates a new [http] request with json headers set. // -// It uses context.Background. +// It uses [context.Background]. func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) { req, err := http.NewRequestWithContext(context.Background(), method, urlStr, body) if err != nil { @@ -117,12 +117,12 @@ func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) { return req, nil } -// Gettable for things with a method GetOK(string) (data string, hasKey bool, hasValue bool) +// Gettable for things with a method [GetOK](string) (data string, hasKey bool, hasValue bool). type Gettable interface { GetOK(string) ([]string, bool, bool) } -// ReadSingleValue reads a single value from the source +// ReadSingleValue reads a single value from the source. func ReadSingleValue(values Gettable, name string) string { vv, _, hv := values.GetOK(name) if hv { @@ -131,7 +131,7 @@ func ReadSingleValue(values Gettable, name string) string { return "" } -// ReadCollectionValue reads a collection value from a string data source +// ReadCollectionValue reads a collection value from a string data source. func ReadCollectionValue(values Gettable, name, collectionFormat string) []string { v := ReadSingleValue(values, name) return stringutils.SplitByFormat(v, collectionFormat) diff --git a/vendor/github.com/go-openapi/runtime/security/authenticator.go b/vendor/github.com/go-openapi/runtime/security/authenticator.go index b5b7904d..4c091018 100644 --- a/vendor/github.com/go-openapi/runtime/security/authenticator.go +++ b/vendor/github.com/go-openapi/runtime/security/authenticator.go @@ -19,7 +19,7 @@ const ( accessTokenParam = "access_token" ) -// HttpAuthenticator is a function that authenticates a HTTP request +// HttpAuthenticator is a function that authenticates a HTTP request. func HttpAuthenticator(handler func(*http.Request) (bool, any, error)) runtime.Authenticator { //nolint:revive return runtime.AuthenticatorFunc(func(params any) (bool, any, error) { if request, ok := params.(*http.Request); ok { @@ -32,7 +32,7 @@ func HttpAuthenticator(handler func(*http.Request) (bool, any, error)) runtime.A }) } -// ScopedAuthenticator is a function that authenticates a HTTP request against a list of valid scopes +// ScopedAuthenticator is a function that authenticates a HTTP request against a list of valid scopes. func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, any, error)) runtime.Authenticator { return runtime.AuthenticatorFunc(func(params any) (bool, any, error) { if request, ok := params.(*ScopedAuthRequest); ok { @@ -42,22 +42,22 @@ func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, any, error)) ru }) } -// UserPassAuthentication authentication function +// UserPassAuthentication authentication function. type UserPassAuthentication func(string, string) (any, error) -// UserPassAuthenticationCtx authentication function with context.Context +// UserPassAuthenticationCtx authentication function with [context.Context]. type UserPassAuthenticationCtx func(context.Context, string, string) (context.Context, any, error) -// TokenAuthentication authentication function +// TokenAuthentication authentication function. type TokenAuthentication func(string) (any, error) -// TokenAuthenticationCtx authentication function with context.Context +// TokenAuthenticationCtx authentication function with [context.Context]. type TokenAuthenticationCtx func(context.Context, string) (context.Context, any, error) -// ScopedTokenAuthentication authentication function +// ScopedTokenAuthentication authentication function. type ScopedTokenAuthentication func(string, []string) (any, error) -// ScopedTokenAuthenticationCtx authentication function with context.Context +// ScopedTokenAuthenticationCtx authentication function with [context.Context]. type ScopedTokenAuthenticationCtx func(context.Context, string, []string) (context.Context, any, error) var DefaultRealmName = "API" @@ -93,12 +93,12 @@ func OAuth2SchemeNameCtx(ctx context.Context) string { return v } -// BasicAuth creates a basic auth authenticator with the provided authentication function +// BasicAuth creates a basic auth authenticator with the provided authentication function. func BasicAuth(authenticate UserPassAuthentication) runtime.Authenticator { return BasicAuthRealm(DefaultRealmName, authenticate) } -// BasicAuthRealm creates a basic auth authenticator with the provided authentication function and realm name +// BasicAuthRealm creates a basic auth authenticator with the provided authentication function and realm name. func BasicAuthRealm(realm string, authenticate UserPassAuthentication) runtime.Authenticator { if realm == "" { realm = DefaultRealmName @@ -117,12 +117,12 @@ func BasicAuthRealm(realm string, authenticate UserPassAuthentication) runtime.A }) } -// BasicAuthCtx creates a basic auth authenticator with the provided authentication function with support for context.Context +// BasicAuthCtx creates a basic auth authenticator with the provided authentication function with support for [context.Context]. func BasicAuthCtx(authenticate UserPassAuthenticationCtx) runtime.Authenticator { return BasicAuthRealmCtx(DefaultRealmName, authenticate) } -// BasicAuthRealmCtx creates a basic auth authenticator with the provided authentication function and realm name with support for context.Context +// BasicAuthRealmCtx creates a basic auth authenticator with the provided authentication function and realm name with support for [context.Context]. func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) runtime.Authenticator { if realm == "" { realm = DefaultRealmName @@ -143,7 +143,7 @@ func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) run } // APIKeyAuth creates an authenticator that uses a token for authorization. -// This token can be obtained from either a header or a query string +// This token can be obtained from either a header or a query string. func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authenticator { inl := strings.ToLower(in) if inl != query && inl != header { @@ -170,8 +170,8 @@ func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authe }) } -// APIKeyAuthCtx creates an authenticator that uses a token for authorization with support for context.Context. -// This token can be obtained from either a header or a query string +// APIKeyAuthCtx creates an authenticator that uses a token for authorization with support for [context.Context]. +// This token can be obtained from either a header or a query string. func APIKeyAuthCtx(name, in string, authenticate TokenAuthenticationCtx) runtime.Authenticator { inl := strings.ToLower(in) if inl != query && inl != header { @@ -199,13 +199,13 @@ func APIKeyAuthCtx(name, in string, authenticate TokenAuthenticationCtx) runtime }) } -// ScopedAuthRequest contains both a http request and the required scopes for a particular operation +// ScopedAuthRequest contains both a [http] request and the required scopes for a particular operation. type ScopedAuthRequest struct { Request *http.Request RequiredScopes []string } -// BearerAuth for use with oauth2 flows +// BearerAuth for use with oauth2 flows. func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Authenticator { const prefix = "Bearer " return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, any, error) { @@ -235,7 +235,7 @@ func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Aut }) } -// BearerAuthCtx for use with oauth2 flows with support for context.Context. +// BearerAuthCtx for use with oauth2 flows with support for [context.Context]. func BearerAuthCtx(name string, authenticate ScopedTokenAuthenticationCtx) runtime.Authenticator { const prefix = "Bearer " return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, any, error) { diff --git a/vendor/github.com/go-openapi/runtime/security/authorizer.go b/vendor/github.com/go-openapi/runtime/security/authorizer.go index 69bd497a..8beef19f 100644 --- a/vendor/github.com/go-openapi/runtime/security/authorizer.go +++ b/vendor/github.com/go-openapi/runtime/security/authorizer.go @@ -9,8 +9,8 @@ import ( "github.com/go-openapi/runtime" ) -// Authorized provides a default implementation of the Authorizer interface where all -// requests are authorized (successful) +// Authorized provides a default implementation of the [Authorizer] interface where all +// requests are authorized (successful). func Authorized() runtime.Authorizer { return runtime.AuthorizerFunc(func(_ *http.Request, _ any) error { return nil }) } diff --git a/vendor/github.com/go-openapi/runtime/statuses.go b/vendor/github.com/go-openapi/runtime/statuses.go index 7e10a5a5..c0f3e6b4 100644 --- a/vendor/github.com/go-openapi/runtime/statuses.go +++ b/vendor/github.com/go-openapi/runtime/statuses.go @@ -3,7 +3,7 @@ package runtime -// Statuses lists the most common HTTP status codes to default message +// Statuses lists the most common HTTP status codes to default message. // taken from https://httpstatuses.com/ var Statuses = map[int]string{ 100: "Continue", diff --git a/vendor/github.com/go-openapi/runtime/text.go b/vendor/github.com/go-openapi/runtime/text.go index 2b8e4ac0..1252ac88 100644 --- a/vendor/github.com/go-openapi/runtime/text.go +++ b/vendor/github.com/go-openapi/runtime/text.go @@ -14,7 +14,7 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// TextConsumer creates a new text consumer +// TextConsumer creates a new text consumer. func TextConsumer() Consumer { return ConsumerFunc(func(reader io.Reader, data any) error { if reader == nil { @@ -56,7 +56,7 @@ func TextConsumer() Consumer { }) } -// TextProducer creates a new text producer +// TextProducer creates a new text producer. func TextProducer() Producer { return ProducerFunc(func(writer io.Writer, data any) error { if writer == nil { diff --git a/vendor/github.com/go-openapi/runtime/values.go b/vendor/github.com/go-openapi/runtime/values.go index 19894e78..af4d9be7 100644 --- a/vendor/github.com/go-openapi/runtime/values.go +++ b/vendor/github.com/go-openapi/runtime/values.go @@ -3,7 +3,7 @@ package runtime -// Values typically represent parameters on a http request. +// Values typically represent parameters on a [http] request. type Values map[string][]string // GetOK returns the values collection for the given key. diff --git a/vendor/github.com/go-openapi/runtime/xml.go b/vendor/github.com/go-openapi/runtime/xml.go index 5060b5c8..9cd2540c 100644 --- a/vendor/github.com/go-openapi/runtime/xml.go +++ b/vendor/github.com/go-openapi/runtime/xml.go @@ -8,7 +8,7 @@ import ( "io" ) -// XMLConsumer creates a new XML consumer +// XMLConsumer creates a new XML consumer. func XMLConsumer() Consumer { return ConsumerFunc(func(reader io.Reader, data any) error { dec := xml.NewDecoder(reader) @@ -16,7 +16,7 @@ func XMLConsumer() Consumer { }) } -// XMLProducer creates a new XML producer +// XMLProducer creates a new XML producer. func XMLProducer() Producer { return ProducerFunc(func(writer io.Writer, data any) error { enc := xml.NewEncoder(writer) diff --git a/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go b/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go index ca63430e..ca71edbb 100644 --- a/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go +++ b/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go @@ -10,7 +10,7 @@ import ( yaml "go.yaml.in/yaml/v3" ) -// YAMLConsumer creates a consumer for yaml data +// YAMLConsumer creates a consumer for [yaml] data. func YAMLConsumer() runtime.Consumer { return runtime.ConsumerFunc(func(r io.Reader, v any) error { dec := yaml.NewDecoder(r) @@ -18,7 +18,7 @@ func YAMLConsumer() runtime.Consumer { }) } -// YAMLProducer creates a producer for yaml data +// YAMLProducer creates a producer for [yaml] data. func YAMLProducer() runtime.Producer { return runtime.ProducerFunc(func(w io.Writer, v any) error { enc := yaml.NewEncoder(w) diff --git a/vendor/github.com/go-openapi/spec/.cliff.toml b/vendor/github.com/go-openapi/spec/.cliff.toml deleted file mode 100644 index 702629f5..00000000 --- a/vendor/github.com/go-openapi/spec/.cliff.toml +++ /dev/null @@ -1,181 +0,0 @@ -# git-cliff ~ configuration file -# https://git-cliff.org/docs/configuration - -[changelog] -header = """ -""" - -footer = """ - ------ - -**[{{ remote.github.repo }}]({{ self::remote_url() }}) license terms** - -[![License][license-badge]][license-url] - -[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg -[license-url]: {{ self::remote_url() }}/?tab=Apache-2.0-1-ov-file#readme - -{%- macro remote_url() -%} - https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} -{%- endmacro -%} -""" - -body = """ -{%- if version %} -## [{{ version | trim_start_matches(pat="v") }}]({{ self::remote_url() }}/tree/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} -{%- else %} -## [unreleased] -{%- endif %} -{%- if message %} - {%- raw %}\n{% endraw %} -{{ message }} - {%- raw %}\n{% endraw %} -{%- endif %} -{%- if version %} - {%- if previous.version %} - -**Full Changelog**: <{{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}> - {%- endif %} -{%- else %} - {%- raw %}\n{% endraw %} -{%- endif %} - -{%- if statistics %}{% if statistics.commit_count %} - {%- raw %}\n{% endraw %} -{{ statistics.commit_count }} commits in this release. - {%- raw %}\n{% endraw %} -{%- endif %}{% endif %} ------ - -{%- for group, commits in commits | group_by(attribute="group") %} - {%- raw %}\n{% endraw %} -### {{ group | upper_first }} - {%- raw %}\n{% endraw %} - {%- for commit in commits %} - {%- if commit.remote.pr_title %} - {%- set commit_message = commit.remote.pr_title %} - {%- else %} - {%- set commit_message = commit.message %} - {%- endif %} -* {{ commit_message | split(pat="\n") | first | trim }} - {%- if commit.remote.username %} -{%- raw %} {% endraw %}by [@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) - {%- endif %} - {%- if commit.remote.pr_number %} -{%- raw %} {% endraw %}in [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) - {%- endif %} -{%- raw %} {% endraw %}[...]({{ self::remote_url() }}/commit/{{ commit.id }}) - {%- endfor %} -{%- endfor %} - -{%- if github %} -{%- raw %}\n{% endraw -%} - {%- set all_contributors = github.contributors | length %} - {%- if github.contributors | filter(attribute="username", value="dependabot[bot]") | length < all_contributors %} ------ - -### People who contributed to this release - {% endif %} - {%- for contributor in github.contributors | filter(attribute="username") | sort(attribute="username") %} - {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} -* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) - {%- endif %} - {%- endfor %} - - {% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} ------ - {%- raw %}\n{% endraw %} - -### New Contributors - {%- endif %} - - {%- for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} - {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} -* @{{ contributor.username }} made their first contribution - {%- if contributor.pr_number %} - in [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ - {%- endif %} - {%- endif %} - {%- endfor %} -{%- endif %} - -{%- raw %}\n{% endraw %} - -{%- macro remote_url() -%} - https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} -{%- endmacro -%} -""" -# Remove leading and trailing whitespaces from the changelog's body. -trim = true -# Render body even when there are no releases to process. -render_always = true -# An array of regex based postprocessors to modify the changelog. -postprocessors = [ - # Replace the placeholder with a URL. - #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, -] -# output file path -# output = "test.md" - -[git] -# Parse commits according to the conventional commits specification. -# See https://www.conventionalcommits.org -conventional_commits = false -# Exclude commits that do not match the conventional commits specification. -filter_unconventional = false -# Require all commits to be conventional. -# Takes precedence over filter_unconventional. -require_conventional = false -# Split commits on newlines, treating each line as an individual commit. -split_commits = false -# An array of regex based parsers to modify commit messages prior to further processing. -commit_preprocessors = [ - # Replace issue numbers with link templates to be updated in `changelog.postprocessors`. - #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, - # Check spelling of the commit message using https://github.com/crate-ci/typos. - # If the spelling is incorrect, it will be fixed automatically. - #{ pattern = '.*', replace_command = 'typos --write-changes -' } -] -# Prevent commits that are breaking from being excluded by commit parsers. -protect_breaking_commits = false -# An array of regex based parsers for extracting data from the commit message. -# Assigns commits to groups. -# Optionally sets the commit's scope and can decide to exclude commits from further processing. -commit_parsers = [ - { message = "^[Cc]hore\\([Rr]elease\\): prepare for", skip = true }, - { message = "(^[Mm]erge)|([Mm]erge conflict)", skip = true }, - { field = "author.name", pattern = "dependabot*", group = "Updates" }, - { message = "([Ss]ecurity)|([Vv]uln)", group = "Security" }, - { body = "(.*[Ss]ecurity)|([Vv]uln)", group = "Security" }, - { message = "([Cc]hore\\(lint\\))|(style)|(lint)|(codeql)|(golangci)", group = "Code quality" }, - { message = "(^[Dd]oc)|((?i)readme)|(badge)|(typo)|(documentation)", group = "Documentation" }, - { message = "(^[Ff]eat)|(^[Ee]nhancement)", group = "Implemented enhancements" }, - { message = "(^ci)|(\\(ci\\))|(fixup\\s+ci)|(fix\\s+ci)|(license)|(example)", group = "Miscellaneous tasks" }, - { message = "^test", group = "Testing" }, - { message = "(^fix)|(panic)", group = "Fixed bugs" }, - { message = "(^refact)|(rework)", group = "Refactor" }, - { message = "(^[Pp]erf)|(performance)", group = "Performance" }, - { message = "(^[Cc]hore)", group = "Miscellaneous tasks" }, - { message = "^[Rr]evert", group = "Reverted changes" }, - { message = "(upgrade.*?go)|(go\\s+version)", group = "Updates" }, - { message = ".*", group = "Other" }, -] -# Exclude commits that are not matched by any commit parser. -filter_commits = false -# An array of link parsers for extracting external references, and turning them into URLs, using regex. -link_parsers = [] -# Include only the tags that belong to the current branch. -use_branch_tags = false -# Order releases topologically instead of chronologically. -topo_order = false -# Order releases topologically instead of chronologically. -topo_order_commits = true -# Order of commits in each group/release within the changelog. -# Allowed values: newest, oldest -sort_commits = "newest" -# Process submodules commits -recurse_submodules = false - -#[remote.github] -#owner = "go-openapi" diff --git a/vendor/github.com/go-openapi/spec/.gitignore b/vendor/github.com/go-openapi/spec/.gitignore index f47cb204..885dc27a 100644 --- a/vendor/github.com/go-openapi/spec/.gitignore +++ b/vendor/github.com/go-openapi/spec/.gitignore @@ -1 +1,6 @@ *.out +*.cov +.idea +.env +.mcp.json +.claude/ diff --git a/vendor/github.com/go-openapi/spec/.golangci.yml b/vendor/github.com/go-openapi/spec/.golangci.yml index fdae591b..dc7c9605 100644 --- a/vendor/github.com/go-openapi/spec/.golangci.yml +++ b/vendor/github.com/go-openapi/spec/.golangci.yml @@ -12,6 +12,7 @@ linters: - paralleltest - recvcheck - testpackage + - thelper - tparallel - varnamelen - whitespace diff --git a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/spec/CONTRIBUTORS.md b/vendor/github.com/go-openapi/spec/CONTRIBUTORS.md index d97b9d33..2967e3ce 100644 --- a/vendor/github.com/go-openapi/spec/CONTRIBUTORS.md +++ b/vendor/github.com/go-openapi/spec/CONTRIBUTORS.md @@ -4,47 +4,47 @@ | Total Contributors | Total Contributions | | --- | --- | -| 38 | 391 | +| 38 | 392 | | Username | All Time Contribution Count | All Commits | | --- | --- | --- | -| @casualjim | 191 | https://github.com/go-openapi/spec/commits?author=casualjim | -| @fredbi | 89 | https://github.com/go-openapi/spec/commits?author=fredbi | -| @pytlesk4 | 26 | https://github.com/go-openapi/spec/commits?author=pytlesk4 | -| @kul-amr | 10 | https://github.com/go-openapi/spec/commits?author=kul-amr | -| @keramix | 10 | https://github.com/go-openapi/spec/commits?author=keramix | -| @youyuanwu | 8 | https://github.com/go-openapi/spec/commits?author=youyuanwu | -| @pengsrc | 7 | https://github.com/go-openapi/spec/commits?author=pengsrc | -| @alphacentory | 5 | https://github.com/go-openapi/spec/commits?author=alphacentory | -| @mtfelian | 4 | https://github.com/go-openapi/spec/commits?author=mtfelian | -| @Capstan | 4 | https://github.com/go-openapi/spec/commits?author=Capstan | -| @sdghchj | 4 | https://github.com/go-openapi/spec/commits?author=sdghchj | -| @databus23 | 2 | https://github.com/go-openapi/spec/commits?author=databus23 | -| @vburenin | 2 | https://github.com/go-openapi/spec/commits?author=vburenin | -| @petrkotas | 2 | https://github.com/go-openapi/spec/commits?author=petrkotas | -| @nikhita | 2 | https://github.com/go-openapi/spec/commits?author=nikhita | -| @hypnoglow | 2 | https://github.com/go-openapi/spec/commits?author=hypnoglow | -| @carvind | 2 | https://github.com/go-openapi/spec/commits?author=carvind | -| @ujjwalsh | 1 | https://github.com/go-openapi/spec/commits?author=ujjwalsh | -| @mbohlool | 1 | https://github.com/go-openapi/spec/commits?author=mbohlool | -| @j2gg0s | 1 | https://github.com/go-openapi/spec/commits?author=j2gg0s | -| @ishveda | 1 | https://github.com/go-openapi/spec/commits?author=ishveda | -| @micln | 1 | https://github.com/go-openapi/spec/commits?author=micln | -| @GlenDC | 1 | https://github.com/go-openapi/spec/commits?author=GlenDC | -| @agmikhailov | 1 | https://github.com/go-openapi/spec/commits?author=agmikhailov | -| @tgraf | 1 | https://github.com/go-openapi/spec/commits?author=tgraf | -| @zhsj | 1 | https://github.com/go-openapi/spec/commits?author=zhsj | -| @sebastien-rosset | 1 | https://github.com/go-openapi/spec/commits?author=sebastien-rosset | -| @alexandear | 1 | https://github.com/go-openapi/spec/commits?author=alexandear | -| @morlay | 1 | https://github.com/go-openapi/spec/commits?author=morlay | -| @mikedanese | 1 | https://github.com/go-openapi/spec/commits?author=mikedanese | -| @koron | 1 | https://github.com/go-openapi/spec/commits?author=koron | -| @honza | 1 | https://github.com/go-openapi/spec/commits?author=honza | -| @gbjk | 1 | https://github.com/go-openapi/spec/commits?author=gbjk | -| @faguirre1 | 1 | https://github.com/go-openapi/spec/commits?author=faguirre1 | -| @ethantkoenig | 1 | https://github.com/go-openapi/spec/commits?author=ethantkoenig | -| @sttts | 1 | https://github.com/go-openapi/spec/commits?author=sttts | -| @ChandanChainani | 1 | https://github.com/go-openapi/spec/commits?author=ChandanChainani | -| @bvwells | 1 | https://github.com/go-openapi/spec/commits?author=bvwells | +| @casualjim | 191 | | +| @fredbi | 90 | | +| @pytlesk4 | 26 | | +| @kul-amr | 10 | | +| @keramix | 10 | | +| @youyuanwu | 8 | | +| @pengsrc | 7 | | +| @alphacentory | 5 | | +| @mtfelian | 4 | | +| @Capstan | 4 | | +| @sdghchj | 4 | | +| @databus23 | 2 | | +| @vburenin | 2 | | +| @petrkotas | 2 | | +| @nikhita | 2 | | +| @hypnoglow | 2 | | +| @carvind | 2 | | +| @ujjwalsh | 1 | | +| @mbohlool | 1 | | +| @j2gg0s | 1 | | +| @ishveda | 1 | | +| @micln | 1 | | +| @GlenDC | 1 | | +| @agmikhailov | 1 | | +| @tgraf | 1 | | +| @zhsj | 1 | | +| @sebastien-rosset | 1 | | +| @alexandear | 1 | | +| @morlay | 1 | | +| @mikedanese | 1 | | +| @koron | 1 | | +| @honza | 1 | | +| @gbjk | 1 | | +| @faguirre1 | 1 | | +| @ethantkoenig | 1 | | +| @sttts | 1 | | +| @ChandanChainani | 1 | | +| @bvwells | 1 | | _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/spec/README.md b/vendor/github.com/go-openapi/spec/README.md index 13a2a17e..134809fd 100644 --- a/vendor/github.com/go-openapi/spec/README.md +++ b/vendor/github.com/go-openapi/spec/README.md @@ -55,7 +55,7 @@ go get github.com/go-openapi/spec > There is no plan to make it evolve toward supporting OpenAPI 3.x. > This [discussion thread](https://github.com/go-openapi/spec/issues/21) relates the full story. > -> An early attempt to support Swagger 3 may be found at: https://github.com/go-openapi/spec3 +> An early attempt to support Swagger 3 may be found at: * Does the unmarshaling support YAML? @@ -64,13 +64,13 @@ go get github.com/go-openapi/spec > In order to load a YAML document as a Swagger spec, you need to use the loaders provided by > github.com/go-openapi/loads > -> Take a look at the example there: https://pkg.go.dev/github.com/go-openapi/loads#example-Spec +> Take a look at the example there: > -> See also https://github.com/go-openapi/spec/issues/164 +> See also * How can I validate a spec? -> Validation is provided by [the validate package](http://github.com/go-openapi/validate) +Validation is provided by [the validate package](http://github.com/go-openapi/validate) * Why do we have an `ID` field for `Schema` which is not part of the swagger spec? @@ -78,7 +78,7 @@ go get github.com/go-openapi/spec > how `$ref` are resolved. > This `id` does not conflict with any property named `id`. > -> See also https://github.com/go-openapi/spec/issues/23 +> See also ## Change log @@ -136,7 +136,7 @@ Maintainers can cut a new release by either: [slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM [slack-url]: https://goswagger.slack.com/archives/C04R30YMU [discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue -[discord-url]: https://discord.gg/DrafRmZx +[discord-url]: https://discord.gg/twZ9BwT3 [license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg diff --git a/vendor/github.com/go-openapi/spec/SECURITY.md b/vendor/github.com/go-openapi/spec/SECURITY.md index 2a7b6f09..1fea2c57 100644 --- a/vendor/github.com/go-openapi/spec/SECURITY.md +++ b/vendor/github.com/go-openapi/spec/SECURITY.md @@ -6,14 +6,32 @@ This policy outlines the commitment and practices of the go-openapi maintainers | Version | Supported | | ------- | ------------------ | -| 0.22.x | :white_check_mark: | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. ## Reporting a vulnerability If you become aware of a security vulnerability that affects the current repository, -please report it privately to the maintainers. +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. -Please follow the instructions provided by github to -[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". -TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/spec/cache.go b/vendor/github.com/go-openapi/spec/cache.go index 10fba77a..06495d2c 100644 --- a/vendor/github.com/go-openapi/spec/cache.go +++ b/vendor/github.com/go-openapi/spec/cache.go @@ -8,10 +8,10 @@ import ( "sync" ) -// ResolutionCache a cache for resolving urls +// ResolutionCache a cache for resolving urls. type ResolutionCache interface { - Get(string) (any, bool) - Set(string, any) + Get(uri string) (any, bool) + Set(uri string, data any) } type simpleCache struct { @@ -19,7 +19,7 @@ type simpleCache struct { store map[string]any } -func (s *simpleCache) ShallowClone() ResolutionCache { +func (s *simpleCache) ShallowClone() ResolutionCache { //nolint:ireturn // returns the public interface type by design store := make(map[string]any, len(s.store)) s.lock.RLock() maps.Copy(store, s.store) @@ -30,7 +30,7 @@ func (s *simpleCache) ShallowClone() ResolutionCache { } } -// Get retrieves a cached URI +// Get retrieves a cached URI. func (s *simpleCache) Get(uri string) (any, bool) { s.lock.RLock() v, ok := s.store[uri] @@ -39,7 +39,7 @@ func (s *simpleCache) Get(uri string) (any, bool) { return v, ok } -// Set caches a URI +// Set caches a URI. func (s *simpleCache) Set(uri string, data any) { s.lock.Lock() s.store[uri] = data @@ -56,8 +56,8 @@ var ( // // All subsequent utilizations of this cache are produced from a shallow // clone of this initial version. - resCache *simpleCache - onceCache sync.Once + resCache *simpleCache //nolint:gochecknoglobals // package-level lazy cache for $ref resolution + onceCache sync.Once //nolint:gochecknoglobals // guards lazy init of resCache _ ResolutionCache = &simpleCache{} ) @@ -74,7 +74,7 @@ func defaultResolutionCache() *simpleCache { }} } -func cacheOrDefault(cache ResolutionCache) ResolutionCache { +func cacheOrDefault(cache ResolutionCache) ResolutionCache { //nolint:ireturn // returns the public interface type by design onceCache.Do(initResolutionCache) if cache != nil { diff --git a/vendor/github.com/go-openapi/spec/contact_info.go b/vendor/github.com/go-openapi/spec/contact_info.go index fafe639b..46fada5d 100644 --- a/vendor/github.com/go-openapi/spec/contact_info.go +++ b/vendor/github.com/go-openapi/spec/contact_info.go @@ -17,14 +17,14 @@ type ContactInfo struct { VendorExtensible } -// ContactInfoProps hold the properties of a ContactInfo object +// ContactInfoProps hold the properties of a ContactInfo object. type ContactInfoProps struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` Email string `json:"email,omitempty"` } -// UnmarshalJSON hydrates ContactInfo from json +// UnmarshalJSON hydrates ContactInfo from json. func (c *ContactInfo) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &c.ContactInfoProps); err != nil { return err @@ -32,7 +32,7 @@ func (c *ContactInfo) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &c.VendorExtensible) } -// MarshalJSON produces ContactInfo as json +// MarshalJSON produces ContactInfo as json. func (c ContactInfo) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(c.ContactInfoProps) if err != nil { diff --git a/vendor/github.com/go-openapi/spec/debug.go b/vendor/github.com/go-openapi/spec/debug.go index f4316c26..fa52b0c7 100644 --- a/vendor/github.com/go-openapi/spec/debug.go +++ b/vendor/github.com/go-openapi/spec/debug.go @@ -14,14 +14,12 @@ import ( // Debug is true when the SWAGGER_DEBUG env var is not empty. // // It enables a more verbose logging of this package. -var Debug = os.Getenv("SWAGGER_DEBUG") != "" +var Debug = os.Getenv("SWAGGER_DEBUG") != "" //nolint:gochecknoglobals // public toggle for debug logging -var ( - // specLogger is a debug logger for this package - specLogger *log.Logger -) +// specLogger is a debug logger for this package. +var specLogger *log.Logger //nolint:gochecknoglobals // package-level debug logger -func init() { +func init() { //nolint:gochecknoinits // initializes debug logger at package load debugOptions() } diff --git a/vendor/github.com/go-openapi/spec/errors.go b/vendor/github.com/go-openapi/spec/errors.go index e39ab8bf..eaca01cc 100644 --- a/vendor/github.com/go-openapi/spec/errors.go +++ b/vendor/github.com/go-openapi/spec/errors.go @@ -5,21 +5,21 @@ package spec import "errors" -// Error codes +// Error codes. var ( - // ErrUnknownTypeForReference indicates that a resolved reference was found in an unsupported container type + // ErrUnknownTypeForReference indicates that a resolved reference was found in an unsupported container type. ErrUnknownTypeForReference = errors.New("unknown type for the resolved reference") - // ErrResolveRefNeedsAPointer indicates that a $ref target must be a valid JSON pointer + // ErrResolveRefNeedsAPointer indicates that a $ref target must be a valid JSON pointer. ErrResolveRefNeedsAPointer = errors.New("resolve ref: target needs to be a pointer") // ErrDerefUnsupportedType indicates that a resolved reference was found in an unsupported container type. - // At the moment, $ref are supported only inside: schemas, parameters, responses, path items + // At the moment, $ref are supported only inside: schemas, parameters, responses, path items. ErrDerefUnsupportedType = errors.New("deref: unsupported type") - // ErrExpandUnsupportedType indicates that $ref expansion is attempted on some invalid type + // ErrExpandUnsupportedType indicates that $ref expansion is attempted on some invalid type. ErrExpandUnsupportedType = errors.New("expand: unsupported type. Input should be of type *Parameter or *Response") - // ErrSpec is an error raised by the spec package + // ErrSpec is an error raised by the spec package. ErrSpec = errors.New("spec error") ) diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go index ff45350a..f9c2fa32 100644 --- a/vendor/github.com/go-openapi/spec/expander.go +++ b/vendor/github.com/go-openapi/spec/expander.go @@ -38,7 +38,7 @@ func optionsOrDefault(opts *ExpandOptions) *ExpandOptions { return &ExpandOptions{} } -// ExpandSpec expands the references in a swagger spec +// ExpandSpec expands the references in a swagger spec. func ExpandSpec(spec *Swagger, options *ExpandOptions) error { options = optionsOrDefault(options) resolver := defaultSchemaLoader(spec, options, nil, nil) @@ -92,7 +92,7 @@ func ExpandSpec(spec *Swagger, options *ExpandOptions) error { const rootBase = ".root" // baseForRoot loads in the cache the root document and produces a fake ".root" base path entry -// for further $ref resolution +// for further $ref resolution. func baseForRoot(root any, cache ResolutionCache) string { // cache the root document to resolve $ref's normalizedBase := normalizeBase(rootBase) @@ -190,6 +190,7 @@ func expandItems(target Schema, parentRefs []string, resolver *schemaLoader, bas return &target, nil } +//nolint:gocognit,gocyclo,cyclop // complex but well-tested $ref expansion logic; refactoring deferred to dedicated PR func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { if target.Ref.String() == "" && target.Ref.IsRoot() { newRef := normalizeRef(&target.Ref, basePath) @@ -464,7 +465,7 @@ func ExpandResponseWithRoot(response *Response, root any, cache ResolutionCache) // ExpandResponse expands a response based on a basepath // -// All refs inside response will be resolved relative to basePath +// All refs inside response will be resolved relative to basePath. func ExpandResponse(response *Response, basePath string) error { opts := optionsOrDefault(&ExpandOptions{ RelativeBase: basePath, @@ -491,7 +492,7 @@ func ExpandParameterWithRoot(parameter *Parameter, root any, cache ResolutionCac // ExpandParameter expands a parameter based on a basepath. // This is the exported version of expandParameter -// all refs inside parameter will be resolved relative to basePath +// all refs inside parameter will be resolved relative to basePath. func ExpandParameter(parameter *Parameter, basePath string) error { opts := optionsOrDefault(&ExpandOptions{ RelativeBase: basePath, @@ -565,7 +566,7 @@ func expandParameterOrResponse(input any, resolver *schemaLoader, basePath strin return nil } - if sch.Ref.String() != "" { + if sch.Ref.String() != "" { //nolint:nestif // intertwined ref rebasing and circularity check rebasedRef, ern := NewRef(normalizeURI(sch.Ref.String(), basePath)) if ern != nil { return ern diff --git a/vendor/github.com/go-openapi/spec/header.go b/vendor/github.com/go-openapi/spec/header.go index ab251ef7..599ba2c5 100644 --- a/vendor/github.com/go-openapi/spec/header.go +++ b/vendor/github.com/go-openapi/spec/header.go @@ -15,7 +15,7 @@ const ( jsonArray = "array" ) -// HeaderProps describes a response header +// HeaderProps describes a response header. type HeaderProps struct { Description string `json:"description,omitempty"` } @@ -30,25 +30,25 @@ type Header struct { HeaderProps } -// ResponseHeader creates a new header instance for use in a response +// ResponseHeader creates a new header instance for use in a response. func ResponseHeader() *Header { return new(Header) } -// WithDescription sets the description on this response, allows for chaining +// WithDescription sets the description on this response, allows for chaining. func (h *Header) WithDescription(description string) *Header { h.Description = description return h } -// Typed a fluent builder method for the type of parameter +// Typed a fluent builder method for the type of parameter. func (h *Header) Typed(tpe, format string) *Header { h.Type = tpe h.Format = format return h } -// CollectionOf a fluent builder method for an array item +// CollectionOf a fluent builder method for an array item. func (h *Header) CollectionOf(items *Items, format string) *Header { h.Type = jsonArray h.Items = items @@ -56,87 +56,87 @@ func (h *Header) CollectionOf(items *Items, format string) *Header { return h } -// WithDefault sets the default value on this item +// WithDefault sets the default value on this item. func (h *Header) WithDefault(defaultValue any) *Header { h.Default = defaultValue return h } -// WithMaxLength sets a max length value +// WithMaxLength sets a max length value. func (h *Header) WithMaxLength(maximum int64) *Header { h.MaxLength = &maximum return h } -// WithMinLength sets a min length value +// WithMinLength sets a min length value. func (h *Header) WithMinLength(minimum int64) *Header { h.MinLength = &minimum return h } -// WithPattern sets a pattern value +// WithPattern sets a pattern value. func (h *Header) WithPattern(pattern string) *Header { h.Pattern = pattern return h } -// WithMultipleOf sets a multiple of value +// WithMultipleOf sets a multiple of value. func (h *Header) WithMultipleOf(number float64) *Header { h.MultipleOf = &number return h } -// WithMaximum sets a maximum number value +// WithMaximum sets a maximum number value. func (h *Header) WithMaximum(maximum float64, exclusive bool) *Header { h.Maximum = &maximum h.ExclusiveMaximum = exclusive return h } -// WithMinimum sets a minimum number value +// WithMinimum sets a minimum number value. func (h *Header) WithMinimum(minimum float64, exclusive bool) *Header { h.Minimum = &minimum h.ExclusiveMinimum = exclusive return h } -// WithEnum sets a the enum values (replace) +// WithEnum sets a the enum values (replace). func (h *Header) WithEnum(values ...any) *Header { h.Enum = append([]any{}, values...) return h } -// WithMaxItems sets the max items +// WithMaxItems sets the max items. func (h *Header) WithMaxItems(size int64) *Header { h.MaxItems = &size return h } -// WithMinItems sets the min items +// WithMinItems sets the min items. func (h *Header) WithMinItems(size int64) *Header { h.MinItems = &size return h } -// UniqueValues dictates that this array can only have unique items +// UniqueValues dictates that this array can only have unique items. func (h *Header) UniqueValues() *Header { h.UniqueItems = true return h } -// AllowDuplicates this array can have duplicates +// AllowDuplicates this array can have duplicates. func (h *Header) AllowDuplicates() *Header { h.UniqueItems = false return h } -// WithValidations is a fluent method to set header validations +// WithValidations is a fluent method to set header validations. func (h *Header) WithValidations(val CommonValidations) *Header { h.SetValidations(SchemaValidations{CommonValidations: val}) return h } -// MarshalJSON marshal this to JSON +// MarshalJSON marshal this to JSON. func (h Header) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(h.CommonValidations) if err != nil { @@ -153,7 +153,7 @@ func (h Header) MarshalJSON() ([]byte, error) { return jsonutils.ConcatJSON(b1, b2, b3), nil } -// UnmarshalJSON unmarshals this header from JSON +// UnmarshalJSON unmarshals this header from JSON. func (h *Header) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &h.CommonValidations); err != nil { return err @@ -167,7 +167,7 @@ func (h *Header) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &h.HeaderProps) } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (h Header) JSONLookup(token string) (any, error) { if ex, ok := h.Extensions[token]; ok { return &ex, nil diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go index 9401065b..0ccfdccc 100644 --- a/vendor/github.com/go-openapi/spec/info.go +++ b/vendor/github.com/go-openapi/spec/info.go @@ -12,16 +12,16 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// Extensions vendor specific extensions +// Extensions vendor specific extensions. type Extensions map[string]any -// Add adds a value to these extensions +// Add adds a value to these extensions. func (e Extensions) Add(key string, value any) { realKey := strings.ToLower(key) e[realKey] = value } -// GetString gets a string value from the extensions +// GetString gets a string value from the extensions. func (e Extensions) GetString(key string) (string, bool) { if v, ok := e[strings.ToLower(key)]; ok { str, ok := v.(string) @@ -30,7 +30,7 @@ func (e Extensions) GetString(key string) (string, bool) { return "", false } -// GetInt gets a int value from the extensions +// GetInt gets a int value from the extensions. func (e Extensions) GetInt(key string) (int, bool) { realKey := strings.ToLower(key) @@ -48,7 +48,7 @@ func (e Extensions) GetInt(key string) (int, bool) { return -1, false } -// GetBool gets a string value from the extensions +// GetBool gets a string value from the extensions. func (e Extensions) GetBool(key string) (bool, bool) { if v, ok := e[strings.ToLower(key)]; ok { str, ok := v.(bool) @@ -57,7 +57,7 @@ func (e Extensions) GetBool(key string) (bool, bool) { return false, false } -// GetStringSlice gets a string value from the extensions +// GetStringSlice gets a string value from the extensions. func (e Extensions) GetStringSlice(key string) ([]string, bool) { if v, ok := e[strings.ToLower(key)]; ok { arr, isSlice := v.([]any) @@ -82,7 +82,7 @@ type VendorExtensible struct { Extensions Extensions } -// AddExtension adds an extension to this extensible object +// AddExtension adds an extension to this extensible object. func (v *VendorExtensible) AddExtension(key string, value any) { if value == nil { return @@ -93,7 +93,7 @@ func (v *VendorExtensible) AddExtension(key string, value any) { v.Extensions.Add(key, value) } -// MarshalJSON marshals the extensions to json +// MarshalJSON marshals the extensions to json. func (v VendorExtensible) MarshalJSON() ([]byte, error) { toser := make(map[string]any) for k, v := range v.Extensions { @@ -105,7 +105,7 @@ func (v VendorExtensible) MarshalJSON() ([]byte, error) { return json.Marshal(toser) } -// UnmarshalJSON for this extensible object +// UnmarshalJSON for this extensible object. func (v *VendorExtensible) UnmarshalJSON(data []byte) error { var d map[string]any if err := json.Unmarshal(data, &d); err != nil { @@ -123,7 +123,7 @@ func (v *VendorExtensible) UnmarshalJSON(data []byte) error { return nil } -// InfoProps the properties for an info definition +// InfoProps the properties for an info definition. type InfoProps struct { Description string `json:"description,omitempty"` Title string `json:"title,omitempty"` @@ -142,7 +142,7 @@ type Info struct { InfoProps } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (i Info) JSONLookup(token string) (any, error) { if ex, ok := i.Extensions[token]; ok { return &ex, nil @@ -151,7 +151,7 @@ func (i Info) JSONLookup(token string) (any, error) { return r, err } -// MarshalJSON marshal this to JSON +// MarshalJSON marshal this to JSON. func (i Info) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(i.InfoProps) if err != nil { @@ -164,7 +164,7 @@ func (i Info) MarshalJSON() ([]byte, error) { return jsonutils.ConcatJSON(b1, b2), nil } -// UnmarshalJSON marshal this from JSON +// UnmarshalJSON marshal this from JSON. func (i *Info) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &i.InfoProps); err != nil { return err diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go index d30ca356..daf5a4fd 100644 --- a/vendor/github.com/go-openapi/spec/items.go +++ b/vendor/github.com/go-openapi/spec/items.go @@ -15,7 +15,7 @@ const ( jsonRef = "$ref" ) -// SimpleSchema describe swagger simple schemas for parameters and headers +// SimpleSchema describe swagger simple schemas for parameters and headers. type SimpleSchema struct { Type string `json:"type,omitempty"` Nullable bool `json:"nullable,omitempty"` @@ -26,7 +26,7 @@ type SimpleSchema struct { Example any `json:"example,omitempty"` } -// TypeName return the type (or format) of a simple schema +// TypeName return the type (or format) of a simple schema. func (s *SimpleSchema) TypeName() string { if s.Format != "" { return s.Format @@ -34,7 +34,7 @@ func (s *SimpleSchema) TypeName() string { return s.Type } -// ItemsTypeName yields the type of items in a simple schema array +// ItemsTypeName yields the type of items in a simple schema array. func (s *SimpleSchema) ItemsTypeName() string { if s.Items == nil { return "" @@ -53,12 +53,12 @@ type Items struct { VendorExtensible } -// NewItems creates a new instance of items +// NewItems creates a new instance of items. func NewItems() *Items { return &Items{} } -// Typed a fluent builder method for the type of item +// Typed a fluent builder method for the type of item. func (i *Items) Typed(tpe, format string) *Items { i.Type = tpe i.Format = format @@ -71,7 +71,7 @@ func (i *Items) AsNullable() *Items { return i } -// CollectionOf a fluent builder method for an array item +// CollectionOf a fluent builder method for an array item. func (i *Items) CollectionOf(items *Items, format string) *Items { i.Type = jsonArray i.Items = items @@ -79,87 +79,87 @@ func (i *Items) CollectionOf(items *Items, format string) *Items { return i } -// WithDefault sets the default value on this item +// WithDefault sets the default value on this item. func (i *Items) WithDefault(defaultValue any) *Items { i.Default = defaultValue return i } -// WithMaxLength sets a max length value +// WithMaxLength sets a max length value. func (i *Items) WithMaxLength(maximum int64) *Items { i.MaxLength = &maximum return i } -// WithMinLength sets a min length value +// WithMinLength sets a min length value. func (i *Items) WithMinLength(minimum int64) *Items { i.MinLength = &minimum return i } -// WithPattern sets a pattern value +// WithPattern sets a pattern value. func (i *Items) WithPattern(pattern string) *Items { i.Pattern = pattern return i } -// WithMultipleOf sets a multiple of value +// WithMultipleOf sets a multiple of value. func (i *Items) WithMultipleOf(number float64) *Items { i.MultipleOf = &number return i } -// WithMaximum sets a maximum number value +// WithMaximum sets a maximum number value. func (i *Items) WithMaximum(maximum float64, exclusive bool) *Items { i.Maximum = &maximum i.ExclusiveMaximum = exclusive return i } -// WithMinimum sets a minimum number value +// WithMinimum sets a minimum number value. func (i *Items) WithMinimum(minimum float64, exclusive bool) *Items { i.Minimum = &minimum i.ExclusiveMinimum = exclusive return i } -// WithEnum sets a the enum values (replace) +// WithEnum sets a the enum values (replace). func (i *Items) WithEnum(values ...any) *Items { i.Enum = append([]any{}, values...) return i } -// WithMaxItems sets the max items +// WithMaxItems sets the max items. func (i *Items) WithMaxItems(size int64) *Items { i.MaxItems = &size return i } -// WithMinItems sets the min items +// WithMinItems sets the min items. func (i *Items) WithMinItems(size int64) *Items { i.MinItems = &size return i } -// UniqueValues dictates that this array can only have unique items +// UniqueValues dictates that this array can only have unique items. func (i *Items) UniqueValues() *Items { i.UniqueItems = true return i } -// AllowDuplicates this array can have duplicates +// AllowDuplicates this array can have duplicates. func (i *Items) AllowDuplicates() *Items { i.UniqueItems = false return i } -// WithValidations is a fluent method to set Items validations +// WithValidations is a fluent method to set Items validations. func (i *Items) WithValidations(val CommonValidations) *Items { i.SetValidations(SchemaValidations{CommonValidations: val}) return i } -// UnmarshalJSON hydrates this items instance with the data from JSON +// UnmarshalJSON hydrates this items instance with the data from JSON. func (i *Items) UnmarshalJSON(data []byte) error { var validations CommonValidations if err := json.Unmarshal(data, &validations); err != nil { @@ -184,7 +184,7 @@ func (i *Items) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON converts this items object to JSON +// MarshalJSON converts this items object to JSON. func (i Items) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(i.CommonValidations) if err != nil { @@ -205,7 +205,7 @@ func (i Items) MarshalJSON() ([]byte, error) { return jsonutils.ConcatJSON(b4, b3, b1, b2), nil } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (i Items) JSONLookup(token string) (any, error) { if token == jsonRef { return &i.Ref, nil diff --git a/vendor/github.com/go-openapi/spec/license.go b/vendor/github.com/go-openapi/spec/license.go index 286b237e..8209f218 100644 --- a/vendor/github.com/go-openapi/spec/license.go +++ b/vendor/github.com/go-openapi/spec/license.go @@ -17,13 +17,13 @@ type License struct { VendorExtensible } -// LicenseProps holds the properties of a License object +// LicenseProps holds the properties of a License object. type LicenseProps struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` } -// UnmarshalJSON hydrates License from json +// UnmarshalJSON hydrates License from json. func (l *License) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &l.LicenseProps); err != nil { return err @@ -31,7 +31,7 @@ func (l *License) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &l.VendorExtensible) } -// MarshalJSON produces License as json +// MarshalJSON produces License as json. func (l License) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(l.LicenseProps) if err != nil { diff --git a/vendor/github.com/go-openapi/spec/normalizer.go b/vendor/github.com/go-openapi/spec/normalizer.go index e1d7c58d..68252dc3 100644 --- a/vendor/github.com/go-openapi/spec/normalizer.go +++ b/vendor/github.com/go-openapi/spec/normalizer.go @@ -138,7 +138,7 @@ func rebase(ref *Ref, v *url.URL, notEqual bool) (Ref, bool) { return MustCreateRef(newBase.String()), true } -// normalizeRef canonicalize a Ref, using a canonical relativeBase as its absolute anchor +// normalizeRef canonicalize a Ref, using a canonical relativeBase as its absolute anchor. func normalizeRef(ref *Ref, relativeBase string) *Ref { r := MustCreateRef(normalizeURI(ref.String(), relativeBase)) return &r diff --git a/vendor/github.com/go-openapi/spec/operation.go b/vendor/github.com/go-openapi/spec/operation.go index 29d9c4f4..cd70d254 100644 --- a/vendor/github.com/go-openapi/spec/operation.go +++ b/vendor/github.com/go-openapi/spec/operation.go @@ -13,7 +13,7 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -func init() { +func init() { //nolint:gochecknoinits // registers gob types for Operation serialization gob.Register(map[string]any{}) gob.Register([]any{}) } @@ -22,7 +22,7 @@ func init() { // // NOTES: // - schemes, when present must be from [http, https, ws, wss]: see validate -// - Security is handled as a special case: see MarshalJSON function +// - Security is handled as a special case: see MarshalJSON function. type OperationProps struct { Description string `json:"description,omitempty"` Consumes []string `json:"consumes,omitempty"` @@ -82,7 +82,7 @@ func NewOperation(id string) *Operation { return op } -// SuccessResponse gets a success response model +// SuccessResponse gets a success response model. func (o *Operation) SuccessResponse() (*Response, int, bool) { if o.Responses == nil { return nil, 0, false @@ -103,7 +103,7 @@ func (o *Operation) SuccessResponse() (*Response, int, bool) { return o.Responses.Default, 0, false } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (o Operation) JSONLookup(token string) (any, error) { if ex, ok := o.Extensions[token]; ok { return &ex, nil @@ -112,7 +112,7 @@ func (o Operation) JSONLookup(token string) (any, error) { return r, err } -// UnmarshalJSON hydrates this items instance with the data from JSON +// UnmarshalJSON hydrates this items instance with the data from JSON. func (o *Operation) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &o.OperationProps); err != nil { return err @@ -120,7 +120,7 @@ func (o *Operation) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &o.VendorExtensible) } -// MarshalJSON converts this items object to JSON +// MarshalJSON converts this items object to JSON. func (o Operation) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(o.OperationProps) if err != nil { @@ -140,13 +140,13 @@ func (o *Operation) WithID(id string) *Operation { return o } -// WithDescription sets the description on this operation, allows for chaining +// WithDescription sets the description on this operation, allows for chaining. func (o *Operation) WithDescription(description string) *Operation { o.Description = description return o } -// WithSummary sets the summary on this operation, allows for chaining +// WithSummary sets the summary on this operation, allows for chaining. func (o *Operation) WithSummary(summary string) *Operation { o.Summary = summary return o @@ -170,38 +170,38 @@ func (o *Operation) WithExternalDocs(description, url string) *Operation { return o } -// Deprecate marks the operation as deprecated +// Deprecate marks the operation as deprecated. func (o *Operation) Deprecate() *Operation { o.Deprecated = true return o } -// Undeprecate marks the operation as not deprecated +// Undeprecate marks the operation as not deprecated. func (o *Operation) Undeprecate() *Operation { o.Deprecated = false return o } -// WithConsumes adds media types for incoming body values +// WithConsumes adds media types for incoming body values. func (o *Operation) WithConsumes(mediaTypes ...string) *Operation { o.Consumes = append(o.Consumes, mediaTypes...) return o } -// WithProduces adds media types for outgoing body values +// WithProduces adds media types for outgoing body values. func (o *Operation) WithProduces(mediaTypes ...string) *Operation { o.Produces = append(o.Produces, mediaTypes...) return o } -// WithTags adds tags for this operation +// WithTags adds tags for this operation. func (o *Operation) WithTags(tags ...string) *Operation { o.Tags = append(o.Tags, tags...) return o } // AddParam adds a parameter to this operation, when a parameter for that location -// and with that name already exists it will be replaced +// and with that name already exists it will be replaced. func (o *Operation) AddParam(param *Parameter) *Operation { if param == nil { return o @@ -223,7 +223,7 @@ func (o *Operation) AddParam(param *Parameter) *Operation { return o } -// RemoveParam removes a parameter from the operation +// RemoveParam removes a parameter from the operation. func (o *Operation) RemoveParam(name, in string) *Operation { for i, p := range o.Parameters { if p.Name == name && p.In == in { @@ -241,14 +241,14 @@ func (o *Operation) SecuredWith(name string, scopes ...string) *Operation { } // WithDefaultResponse adds a default response to the operation. -// Passing a nil value will remove the response +// Passing a nil value will remove the response. func (o *Operation) WithDefaultResponse(response *Response) *Operation { return o.RespondsWith(0, response) } // RespondsWith adds a status code response to the operation. // When the code is 0 the value of the response will be used as default response value. -// When the value of the response is nil it will be removed from the operation +// When the value of the response is nil it will be removed from the operation. func (o *Operation) RespondsWith(code int, response *Response) *Operation { if o.Responses == nil { o.Responses = new(Responses) @@ -279,7 +279,7 @@ type gobAlias struct { SecurityIsEmpty bool } -// GobEncode provides a safe gob encoder for Operation, including empty security requirements +// GobEncode provides a safe gob encoder for Operation, including empty security requirements. func (o Operation) GobEncode() ([]byte, error) { raw := struct { Ext VendorExtensible @@ -293,7 +293,7 @@ func (o Operation) GobEncode() ([]byte, error) { return b.Bytes(), err } -// GobDecode provides a safe gob decoder for Operation, including empty security requirements +// GobDecode provides a safe gob decoder for Operation, including empty security requirements. func (o *Operation) GobDecode(b []byte) error { var raw struct { Ext VendorExtensible @@ -310,7 +310,7 @@ func (o *Operation) GobDecode(b []byte) error { return nil } -// GobEncode provides a safe gob encoder for Operation, including empty security requirements +// GobEncode provides a safe gob encoder for Operation, including empty security requirements. func (op OperationProps) GobEncode() ([]byte, error) { raw := gobAlias{ Alias: (*opsAlias)(&op), @@ -355,7 +355,7 @@ func (op OperationProps) GobEncode() ([]byte, error) { return b.Bytes(), err } -// GobDecode provides a safe gob decoder for Operation, including empty security requirements +// GobDecode provides a safe gob decoder for Operation, including empty security requirements. func (op *OperationProps) GobDecode(b []byte) error { var raw gobAlias diff --git a/vendor/github.com/go-openapi/spec/parameter.go b/vendor/github.com/go-openapi/spec/parameter.go index b94b7682..516f5d95 100644 --- a/vendor/github.com/go-openapi/spec/parameter.go +++ b/vendor/github.com/go-openapi/spec/parameter.go @@ -11,45 +11,51 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// QueryParam creates a query parameter +// QueryParam creates a query parameter. func QueryParam(name string) *Parameter { return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}} } -// HeaderParam creates a header parameter, this is always required by default +// HeaderParam creates a header parameter, this is always required by default. func HeaderParam(name string) *Parameter { return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}} } -// PathParam creates a path parameter, this is always required +// PathParam creates a path parameter, this is always required. func PathParam(name string) *Parameter { return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}} } -// BodyParam creates a body parameter +// BodyParam creates a body parameter. func BodyParam(name string, schema *Schema) *Parameter { return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema}} } -// FormDataParam creates a body parameter +// FormDataParam creates a body parameter. func FormDataParam(name string) *Parameter { return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}} } -// FileParam creates a body parameter +// FileParam creates a body parameter. func FileParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}, - SimpleSchema: SimpleSchema{Type: "file"}} + return &Parameter{ + ParamProps: ParamProps{Name: name, In: "formData"}, + SimpleSchema: SimpleSchema{Type: "file"}, + } } -// SimpleArrayParam creates a param for a simple array (string, int, date etc) +// SimpleArrayParam creates a param for a simple array (string, int, date etc). func SimpleArrayParam(name, tpe, fmt string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name}, - SimpleSchema: SimpleSchema{Type: jsonArray, CollectionFormat: "csv", - Items: &Items{SimpleSchema: SimpleSchema{Type: tpe, Format: fmt}}}} + return &Parameter{ + ParamProps: ParamProps{Name: name}, + SimpleSchema: SimpleSchema{ + Type: jsonArray, CollectionFormat: "csv", + Items: &Items{SimpleSchema: SimpleSchema{Type: tpe, Format: fmt}}, + }, + } } -// ParamRef creates a parameter that's a json reference +// ParamRef creates a parameter that's a json reference. func ParamRef(uri string) *Parameter { p := new(Parameter) p.Ref = MustCreateRef(uri) @@ -60,7 +66,7 @@ func ParamRef(uri string) *Parameter { // // NOTE: // - Schema is defined when "in" == "body": see validate -// - AllowEmptyValue is allowed where "in" == "query" || "formData" +// - AllowEmptyValue is allowed where "in" == "query" || "formData". type ParamProps struct { Description string `json:"description,omitempty"` Name string `json:"name,omitempty"` @@ -104,7 +110,7 @@ type Parameter struct { ParamProps } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (p Parameter) JSONLookup(token string) (any, error) { if ex, ok := p.Extensions[token]; ok { return &ex, nil @@ -131,32 +137,32 @@ func (p Parameter) JSONLookup(token string) (any, error) { return r, err } -// WithDescription a fluent builder method for the description of the parameter +// WithDescription a fluent builder method for the description of the parameter. func (p *Parameter) WithDescription(description string) *Parameter { p.Description = description return p } -// Named a fluent builder method to override the name of the parameter +// Named a fluent builder method to override the name of the parameter. func (p *Parameter) Named(name string) *Parameter { p.Name = name return p } -// WithLocation a fluent builder method to override the location of the parameter +// WithLocation a fluent builder method to override the location of the parameter. func (p *Parameter) WithLocation(in string) *Parameter { p.In = in return p } -// Typed a fluent builder method for the type of the parameter value +// Typed a fluent builder method for the type of the parameter value. func (p *Parameter) Typed(tpe, format string) *Parameter { p.Type = tpe p.Format = format return p } -// CollectionOf a fluent builder method for an array parameter +// CollectionOf a fluent builder method for an array parameter. func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { p.Type = jsonArray p.Items = items @@ -164,32 +170,32 @@ func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { return p } -// WithDefault sets the default value on this parameter +// WithDefault sets the default value on this parameter. func (p *Parameter) WithDefault(defaultValue any) *Parameter { p.AsOptional() // with default implies optional p.Default = defaultValue return p } -// AllowsEmptyValues flags this parameter as being ok with empty values +// AllowsEmptyValues flags this parameter as being ok with empty values. func (p *Parameter) AllowsEmptyValues() *Parameter { p.AllowEmptyValue = true return p } -// NoEmptyValues flags this parameter as not liking empty values +// NoEmptyValues flags this parameter as not liking empty values. func (p *Parameter) NoEmptyValues() *Parameter { p.AllowEmptyValue = false return p } -// AsOptional flags this parameter as optional +// AsOptional flags this parameter as optional. func (p *Parameter) AsOptional() *Parameter { p.Required = false return p } -// AsRequired flags this parameter as required +// AsRequired flags this parameter as required. func (p *Parameter) AsRequired() *Parameter { if p.Default != nil { // with a default required makes no sense return p @@ -198,81 +204,81 @@ func (p *Parameter) AsRequired() *Parameter { return p } -// WithMaxLength sets a max length value +// WithMaxLength sets a max length value. func (p *Parameter) WithMaxLength(maximum int64) *Parameter { p.MaxLength = &maximum return p } -// WithMinLength sets a min length value +// WithMinLength sets a min length value. func (p *Parameter) WithMinLength(minimum int64) *Parameter { p.MinLength = &minimum return p } -// WithPattern sets a pattern value +// WithPattern sets a pattern value. func (p *Parameter) WithPattern(pattern string) *Parameter { p.Pattern = pattern return p } -// WithMultipleOf sets a multiple of value +// WithMultipleOf sets a multiple of value. func (p *Parameter) WithMultipleOf(number float64) *Parameter { p.MultipleOf = &number return p } -// WithMaximum sets a maximum number value +// WithMaximum sets a maximum number value. func (p *Parameter) WithMaximum(maximum float64, exclusive bool) *Parameter { p.Maximum = &maximum p.ExclusiveMaximum = exclusive return p } -// WithMinimum sets a minimum number value +// WithMinimum sets a minimum number value. func (p *Parameter) WithMinimum(minimum float64, exclusive bool) *Parameter { p.Minimum = &minimum p.ExclusiveMinimum = exclusive return p } -// WithEnum sets a the enum values (replace) +// WithEnum sets a the enum values (replace). func (p *Parameter) WithEnum(values ...any) *Parameter { p.Enum = append([]any{}, values...) return p } -// WithMaxItems sets the max items +// WithMaxItems sets the max items. func (p *Parameter) WithMaxItems(size int64) *Parameter { p.MaxItems = &size return p } -// WithMinItems sets the min items +// WithMinItems sets the min items. func (p *Parameter) WithMinItems(size int64) *Parameter { p.MinItems = &size return p } -// UniqueValues dictates that this array can only have unique items +// UniqueValues dictates that this array can only have unique items. func (p *Parameter) UniqueValues() *Parameter { p.UniqueItems = true return p } -// AllowDuplicates this array can have duplicates +// AllowDuplicates this array can have duplicates. func (p *Parameter) AllowDuplicates() *Parameter { p.UniqueItems = false return p } -// WithValidations is a fluent method to set parameter validations +// WithValidations is a fluent method to set parameter validations. func (p *Parameter) WithValidations(val CommonValidations) *Parameter { p.SetValidations(SchemaValidations{CommonValidations: val}) return p } -// UnmarshalJSON hydrates this items instance with the data from JSON +// UnmarshalJSON hydrates this items instance with the data from JSON. func (p *Parameter) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &p.CommonValidations); err != nil { return err @@ -289,7 +295,7 @@ func (p *Parameter) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &p.ParamProps) } -// MarshalJSON converts this items object to JSON +// MarshalJSON converts this items object to JSON. func (p Parameter) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(p.CommonValidations) if err != nil { diff --git a/vendor/github.com/go-openapi/spec/path_item.go b/vendor/github.com/go-openapi/spec/path_item.go index c692b89e..4408ece4 100644 --- a/vendor/github.com/go-openapi/spec/path_item.go +++ b/vendor/github.com/go-openapi/spec/path_item.go @@ -10,7 +10,7 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// PathItemProps the path item specific properties +// PathItemProps the path item specific properties. type PathItemProps struct { Get *Operation `json:"get,omitempty"` Put *Operation `json:"put,omitempty"` @@ -34,7 +34,7 @@ type PathItem struct { PathItemProps } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (p PathItem) JSONLookup(token string) (any, error) { if ex, ok := p.Extensions[token]; ok { return &ex, nil @@ -46,7 +46,7 @@ func (p PathItem) JSONLookup(token string) (any, error) { return r, err } -// UnmarshalJSON hydrates this items instance with the data from JSON +// UnmarshalJSON hydrates this items instance with the data from JSON. func (p *PathItem) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &p.Refable); err != nil { return err @@ -57,7 +57,7 @@ func (p *PathItem) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &p.PathItemProps) } -// MarshalJSON converts this items object to JSON +// MarshalJSON converts this items object to JSON. func (p PathItem) MarshalJSON() ([]byte, error) { b3, err := json.Marshal(p.Refable) if err != nil { diff --git a/vendor/github.com/go-openapi/spec/paths.go b/vendor/github.com/go-openapi/spec/paths.go index b9e42184..5daf5a67 100644 --- a/vendor/github.com/go-openapi/spec/paths.go +++ b/vendor/github.com/go-openapi/spec/paths.go @@ -23,7 +23,7 @@ type Paths struct { Paths map[string]PathItem `json:"-"` // custom serializer to flatten this, each entry must start with "/" } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (p Paths) JSONLookup(token string) (any, error) { if pi, ok := p.Paths[token]; ok { return &pi, nil @@ -34,7 +34,7 @@ func (p Paths) JSONLookup(token string) (any, error) { return nil, fmt.Errorf("object has no field %q: %w", token, ErrSpec) } -// UnmarshalJSON hydrates this items instance with the data from JSON +// UnmarshalJSON hydrates this items instance with the data from JSON. func (p *Paths) UnmarshalJSON(data []byte) error { var res map[string]json.RawMessage if err := json.Unmarshal(data, &res); err != nil { @@ -65,7 +65,7 @@ func (p *Paths) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON converts this items object to JSON +// MarshalJSON converts this items object to JSON. func (p Paths) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(p.VendorExtensible) if err != nil { diff --git a/vendor/github.com/go-openapi/spec/properties.go b/vendor/github.com/go-openapi/spec/properties.go index c4988180..b8e97271 100644 --- a/vendor/github.com/go-openapi/spec/properties.go +++ b/vendor/github.com/go-openapi/spec/properties.go @@ -10,7 +10,7 @@ import ( "sort" ) -// OrderSchemaItem holds a named schema (e.g. from a property of an object) +// OrderSchemaItem holds a named schema (e.g. from a property of an object). type OrderSchemaItem struct { Schema @@ -53,7 +53,7 @@ func (items OrderSchemaItems) Swap(i, j int) { items[i], items[j] = items[j], it func (items OrderSchemaItems) Less(i, j int) (ret bool) { ii, oki := items[i].Extensions.GetInt("x-order") ij, okj := items[j].Extensions.GetInt("x-order") - if oki { + if oki { //nolint:nestif // nested recover logic for safe type comparison if okj { defer func() { if err := recover(); err != nil { @@ -94,7 +94,7 @@ func (items OrderSchemaItems) marshalJSONItem(item OrderSchemaItem, output *byte // It knows how to transform its keys into an ordered slice. type SchemaProperties map[string]Schema -// ToOrderedSchemaItems transforms the map of properties into a sortable slice +// ToOrderedSchemaItems transforms the map of properties into a sortable slice. func (properties SchemaProperties) ToOrderedSchemaItems() OrderSchemaItems { items := make(OrderSchemaItems, 0, len(properties)) for k, v := range properties { diff --git a/vendor/github.com/go-openapi/spec/ref.go b/vendor/github.com/go-openapi/spec/ref.go index 1d1c7591..40b7d486 100644 --- a/vendor/github.com/go-openapi/spec/ref.go +++ b/vendor/github.com/go-openapi/spec/ref.go @@ -14,28 +14,28 @@ import ( "github.com/go-openapi/jsonreference" ) -// Refable is a struct for things that accept a $ref property +// Refable is a struct for things that accept a $ref property. type Refable struct { Ref Ref } -// MarshalJSON marshals the ref to json +// MarshalJSON marshals the ref to json. func (r Refable) MarshalJSON() ([]byte, error) { return r.Ref.MarshalJSON() } -// UnmarshalJSON unmarshals the ref from json +// UnmarshalJSON unmarshals the ref from json. func (r *Refable) UnmarshalJSON(d []byte) error { return json.Unmarshal(d, &r.Ref) } -// Ref represents a json reference that is potentially resolved +// Ref represents a json reference that is potentially resolved. type Ref struct { jsonreference.Ref } // NewRef creates a new instance of a ref object -// returns an error when the reference uri is an invalid uri +// returns an error when the reference uri is an invalid uri. func NewRef(refURI string) (Ref, error) { ref, err := jsonreference.New(refURI) if err != nil { @@ -51,7 +51,7 @@ func MustCreateRef(refURI string) Ref { return Ref{Ref: jsonreference.MustCreateRef(refURI)} } -// RemoteURI gets the remote uri part of the ref +// RemoteURI gets the remote uri part of the ref. func (r *Ref) RemoteURI() string { if r.String() == "" { return "" @@ -62,7 +62,7 @@ func (r *Ref) RemoteURI() string { return u.String() } -// IsValidURI returns true when the url the ref points to can be found +// IsValidURI returns true when the url the ref points to can be found. func (r *Ref) IsValidURI(basepaths ...string) bool { if r.String() == "" { return true @@ -112,7 +112,7 @@ func (r *Ref) IsValidURI(basepaths ...string) bool { } // Inherits creates a new reference from a parent and a child -// If the child cannot inherit from the parent, an error is returned +// If the child cannot inherit from the parent, an error is returned. func (r *Ref) Inherits(child Ref) (*Ref, error) { ref, err := r.Ref.Inherits(child.Ref) if err != nil { @@ -121,7 +121,7 @@ func (r *Ref) Inherits(child Ref) (*Ref, error) { return &Ref{Ref: *ref}, nil } -// MarshalJSON marshals this ref into a JSON object +// MarshalJSON marshals this ref into a JSON object. func (r Ref) MarshalJSON() ([]byte, error) { str := r.String() if str == "" { @@ -134,7 +134,7 @@ func (r Ref) MarshalJSON() ([]byte, error) { return json.Marshal(v) } -// UnmarshalJSON unmarshals this ref from a JSON object +// UnmarshalJSON unmarshals this ref from a JSON object. func (r *Ref) UnmarshalJSON(d []byte) error { var v map[string]any if err := json.Unmarshal(d, &v); err != nil { @@ -143,7 +143,7 @@ func (r *Ref) UnmarshalJSON(d []byte) error { return r.fromMap(v) } -// GobEncode provides a safe gob encoder for Ref +// GobEncode provides a safe gob encoder for Ref. func (r Ref) GobEncode() ([]byte, error) { var b bytes.Buffer raw, err := r.MarshalJSON() @@ -154,7 +154,7 @@ func (r Ref) GobEncode() ([]byte, error) { return b.Bytes(), err } -// GobDecode provides a safe gob decoder for Ref +// GobDecode provides a safe gob decoder for Ref. func (r *Ref) GobDecode(b []byte) error { var raw []byte buf := bytes.NewBuffer(b) diff --git a/vendor/github.com/go-openapi/spec/resolver.go b/vendor/github.com/go-openapi/spec/resolver.go index 600574e1..1bf90c86 100644 --- a/vendor/github.com/go-openapi/spec/resolver.go +++ b/vendor/github.com/go-openapi/spec/resolver.go @@ -20,7 +20,7 @@ func resolveAnyWithBase(root any, ref *Ref, result any, options *ExpandOptions) return nil } -// ResolveRefWithBase resolves a reference against a context root with preservation of base path +// ResolveRefWithBase resolves a reference against a context root with preservation of base path. func ResolveRefWithBase(root any, ref *Ref, options *ExpandOptions) (*Schema, error) { result := new(Schema) @@ -34,7 +34,7 @@ func ResolveRefWithBase(root any, ref *Ref, options *ExpandOptions) (*Schema, er // ResolveRef resolves a reference for a schema against a context root // ref is guaranteed to be in root (no need to go to external files) // -// ResolveRef is ONLY called from the code generation module +// ResolveRef is ONLY called from the code generation module. func ResolveRef(root any, ref *Ref) (*Schema, error) { res, _, err := ref.GetPointer().Get(root) if err != nil { @@ -57,7 +57,7 @@ func ResolveRef(root any, ref *Ref) (*Schema, error) { } } -// ResolveParameterWithBase resolves a parameter reference against a context root and base path +// ResolveParameterWithBase resolves a parameter reference against a context root and base path. func ResolveParameterWithBase(root any, ref Ref, options *ExpandOptions) (*Parameter, error) { result := new(Parameter) @@ -68,12 +68,12 @@ func ResolveParameterWithBase(root any, ref Ref, options *ExpandOptions) (*Param return result, nil } -// ResolveParameter resolves a parameter reference against a context root +// ResolveParameter resolves a parameter reference against a context root. func ResolveParameter(root any, ref Ref) (*Parameter, error) { return ResolveParameterWithBase(root, ref, nil) } -// ResolveResponseWithBase resolves response a reference against a context root and base path +// ResolveResponseWithBase resolves response a reference against a context root and base path. func ResolveResponseWithBase(root any, ref Ref, options *ExpandOptions) (*Response, error) { result := new(Response) @@ -85,12 +85,12 @@ func ResolveResponseWithBase(root any, ref Ref, options *ExpandOptions) (*Respon return result, nil } -// ResolveResponse resolves response a reference against a context root +// ResolveResponse resolves response a reference against a context root. func ResolveResponse(root any, ref Ref) (*Response, error) { return ResolveResponseWithBase(root, ref, nil) } -// ResolvePathItemWithBase resolves response a path item against a context root and base path +// ResolvePathItemWithBase resolves response a path item against a context root and base path. func ResolvePathItemWithBase(root any, ref Ref, options *ExpandOptions) (*PathItem, error) { result := new(PathItem) @@ -103,7 +103,7 @@ func ResolvePathItemWithBase(root any, ref Ref, options *ExpandOptions) (*PathIt // ResolvePathItem resolves response a path item against a context root and base path // -// Deprecated: use ResolvePathItemWithBase instead +// Deprecated: use ResolvePathItemWithBase instead. func ResolvePathItem(root any, ref Ref, options *ExpandOptions) (*PathItem, error) { return ResolvePathItemWithBase(root, ref, options) } @@ -124,7 +124,7 @@ func ResolveItemsWithBase(root any, ref Ref, options *ExpandOptions) (*Items, er // ResolveItems resolves parameter items reference against a context root and base path. // -// Deprecated: use ResolveItemsWithBase instead +// Deprecated: use ResolveItemsWithBase instead. func ResolveItems(root any, ref Ref, options *ExpandOptions) (*Items, error) { return ResolveItemsWithBase(root, ref, options) } diff --git a/vendor/github.com/go-openapi/spec/response.go b/vendor/github.com/go-openapi/spec/response.go index e5a7e5c4..4bb6a2bc 100644 --- a/vendor/github.com/go-openapi/spec/response.go +++ b/vendor/github.com/go-openapi/spec/response.go @@ -10,7 +10,7 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// ResponseProps properties specific to a response +// ResponseProps properties specific to a response. type ResponseProps struct { Description string `json:"description"` Schema *Schema `json:"schema,omitempty"` @@ -27,19 +27,19 @@ type Response struct { VendorExtensible } -// NewResponse creates a new response instance +// NewResponse creates a new response instance. func NewResponse() *Response { return new(Response) } -// ResponseRef creates a response as a json reference +// ResponseRef creates a response as a json reference. func ResponseRef(url string) *Response { resp := NewResponse() resp.Ref = MustCreateRef(url) return resp } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (r Response) JSONLookup(token string) (any, error) { if ex, ok := r.Extensions[token]; ok { return &ex, nil @@ -51,7 +51,7 @@ func (r Response) JSONLookup(token string) (any, error) { return ptr, err } -// UnmarshalJSON hydrates this items instance with the data from JSON +// UnmarshalJSON hydrates this items instance with the data from JSON. func (r *Response) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &r.ResponseProps); err != nil { return err @@ -62,7 +62,7 @@ func (r *Response) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &r.VendorExtensible) } -// MarshalJSON converts this items object to JSON +// MarshalJSON converts this items object to JSON. func (r Response) MarshalJSON() ([]byte, error) { var ( b1 []byte @@ -100,20 +100,20 @@ func (r Response) MarshalJSON() ([]byte, error) { return jsonutils.ConcatJSON(b1, b2, b3), nil } -// WithDescription sets the description on this response, allows for chaining +// WithDescription sets the description on this response, allows for chaining. func (r *Response) WithDescription(description string) *Response { r.Description = description return r } // WithSchema sets the schema on this response, allows for chaining. -// Passing a nil argument removes the schema from this response +// Passing a nil argument removes the schema from this response. func (r *Response) WithSchema(schema *Schema) *Response { r.Schema = schema return r } -// AddHeader adds a header to this response +// AddHeader adds a header to this response. func (r *Response) AddHeader(name string, header *Header) *Response { if header == nil { return r.RemoveHeader(name) @@ -125,13 +125,13 @@ func (r *Response) AddHeader(name string, header *Header) *Response { return r } -// RemoveHeader removes a header from this response +// RemoveHeader removes a header from this response. func (r *Response) RemoveHeader(name string) *Response { delete(r.Headers, name) return r } -// AddExample adds an example to this response +// AddExample adds an example to this response. func (r *Response) AddExample(mediaType string, example any) *Response { if r.Examples == nil { r.Examples = make(map[string]any) diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go index 733a1315..fb369e4a 100644 --- a/vendor/github.com/go-openapi/spec/responses.go +++ b/vendor/github.com/go-openapi/spec/responses.go @@ -31,7 +31,7 @@ type Responses struct { ResponsesProps } -// JSONLookup implements an interface to customize json pointer lookup +// JSONLookup implements an interface to customize json pointer lookup. func (r Responses) JSONLookup(token string) (any, error) { if token == "default" { return r.Default, nil @@ -47,7 +47,7 @@ func (r Responses) JSONLookup(token string) (any, error) { return nil, fmt.Errorf("object has no field %q: %w", token, ErrSpec) } -// UnmarshalJSON hydrates this items instance with the data from JSON +// UnmarshalJSON hydrates this items instance with the data from JSON. func (r *Responses) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { return err @@ -62,7 +62,7 @@ func (r *Responses) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON converts this items object to JSON +// MarshalJSON converts this items object to JSON. func (r Responses) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(r.ResponsesProps) if err != nil { @@ -84,7 +84,7 @@ type ResponsesProps struct { StatusCodeResponses map[int]Response } -// MarshalJSON marshals responses as JSON +// MarshalJSON marshals responses as JSON. func (r ResponsesProps) MarshalJSON() ([]byte, error) { toser := map[string]Response{} if r.Default != nil { @@ -96,7 +96,7 @@ func (r ResponsesProps) MarshalJSON() ([]byte, error) { return json.Marshal(toser) } -// UnmarshalJSON unmarshals responses from JSON +// UnmarshalJSON unmarshals responses from JSON. func (r *ResponsesProps) UnmarshalJSON(data []byte) error { var res map[string]json.RawMessage if err := json.Unmarshal(data, &res); err != nil { diff --git a/vendor/github.com/go-openapi/spec/schema.go b/vendor/github.com/go-openapi/spec/schema.go index 6623728a..d7a481bf 100644 --- a/vendor/github.com/go-openapi/spec/schema.go +++ b/vendor/github.com/go-openapi/spec/schema.go @@ -13,86 +13,88 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// BooleanProperty creates a boolean property +// BooleanProperty creates a boolean property. func BooleanProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} } -// BoolProperty creates a boolean property +// BoolProperty creates a boolean property. func BoolProperty() *Schema { return BooleanProperty() } -// StringProperty creates a string property +// StringProperty creates a string property. func StringProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} } -// CharProperty creates a string property +// CharProperty creates a string property. func CharProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} } -// Float64Property creates a float64/double property +// Float64Property creates a float64/double property. func Float64Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} } -// Float32Property creates a float32/float property +// Float32Property creates a float32/float property. func Float32Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} } -// Int8Property creates an int8 property +// Int8Property creates an int8 property. func Int8Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} } -// Int16Property creates an int16 property +// Int16Property creates an int16 property. func Int16Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} } -// Int32Property creates an int32 property +// Int32Property creates an int32 property. func Int32Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} } -// Int64Property creates an int64 property +// Int64Property creates an int64 property. func Int64Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} } -// StrFmtProperty creates a property for the named string format +// StrFmtProperty creates a property for the named string format. func StrFmtProperty(format string) *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} } -// DateProperty creates a date property +// DateProperty creates a date property. func DateProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} } -// DateTimeProperty creates a date time property +// DateTimeProperty creates a date time property. func DateTimeProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} } -// MapProperty creates a map property +// MapProperty creates a map property. func MapProperty(property *Schema) *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, - AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} + return &Schema{SchemaProps: SchemaProps{ + Type: []string{"object"}, + AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}, + }} } -// RefProperty creates a ref property +// RefProperty creates a ref property. func RefProperty(name string) *Schema { return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} } -// RefSchema creates a ref property +// RefSchema creates a ref property. func RefSchema(name string) *Schema { return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} } -// ArrayProperty creates an array property +// ArrayProperty creates an array property. func ArrayProperty(items *Schema) *Schema { if items == nil { return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} @@ -100,17 +102,17 @@ func ArrayProperty(items *Schema) *Schema { return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} } -// ComposedSchema creates a schema with allOf +// ComposedSchema creates a schema with allOf. func ComposedSchema(schemas ...Schema) *Schema { s := new(Schema) s.AllOf = schemas return s } -// SchemaURL represents a schema url +// SchemaURL represents a schema url. type SchemaURL string -// MarshalJSON marshal this to JSON +// MarshalJSON marshal this to JSON. func (r SchemaURL) MarshalJSON() ([]byte, error) { if r == "" { return []byte("{}"), nil @@ -119,7 +121,7 @@ func (r SchemaURL) MarshalJSON() ([]byte, error) { return json.Marshal(v) } -// UnmarshalJSON unmarshal this from JSON +// UnmarshalJSON unmarshal this from JSON. func (r *SchemaURL) UnmarshalJSON(data []byte) error { var v map[string]any if err := json.Unmarshal(data, &v); err != nil { @@ -145,7 +147,7 @@ func (r *SchemaURL) fromMap(v map[string]any) error { return nil } -// SchemaProps describes a JSON schema (draft 4) +// SchemaProps describes a JSON schema (draft 4). type SchemaProps struct { ID string `json:"id,omitempty"` Ref Ref `json:"-"` @@ -184,7 +186,7 @@ type SchemaProps struct { Definitions Definitions `json:"definitions,omitempty"` } -// SwaggerSchemaProps are additional properties supported by swagger schemas, but not JSON-schema (draft 4) +// SwaggerSchemaProps are additional properties supported by swagger schemas, but not JSON-schema (draft 4). type SwaggerSchemaProps struct { Discriminator string `json:"discriminator,omitempty"` ReadOnly bool `json:"readOnly,omitempty"` @@ -208,7 +210,7 @@ type Schema struct { ExtraProps map[string]any `json:"-"` } -// JSONLookup implements an interface to customize json pointer lookup +// JSONLookup implements an interface to customize json pointer lookup. func (s Schema) JSONLookup(token string) (any, error) { if ex, ok := s.Extensions[token]; ok { return &ex, nil @@ -226,31 +228,31 @@ func (s Schema) JSONLookup(token string) (any, error) { return r, err } -// WithID sets the id for this schema, allows for chaining +// WithID sets the id for this schema, allows for chaining. func (s *Schema) WithID(id string) *Schema { s.ID = id return s } -// WithTitle sets the title for this schema, allows for chaining +// WithTitle sets the title for this schema, allows for chaining. func (s *Schema) WithTitle(title string) *Schema { s.Title = title return s } -// WithDescription sets the description for this schema, allows for chaining +// WithDescription sets the description for this schema, allows for chaining. func (s *Schema) WithDescription(description string) *Schema { s.Description = description return s } -// WithProperties sets the properties for this schema +// WithProperties sets the properties for this schema. func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { s.Properties = schemas return s } -// SetProperty sets a property on this schema +// SetProperty sets a property on this schema. func (s *Schema) SetProperty(name string, schema Schema) *Schema { if s.Properties == nil { s.Properties = make(map[string]Schema) @@ -259,32 +261,32 @@ func (s *Schema) SetProperty(name string, schema Schema) *Schema { return s } -// WithAllOf sets the all of property +// WithAllOf sets the all of property. func (s *Schema) WithAllOf(schemas ...Schema) *Schema { s.AllOf = schemas return s } -// WithMaxProperties sets the max number of properties an object can have +// WithMaxProperties sets the max number of properties an object can have. func (s *Schema) WithMaxProperties(maximum int64) *Schema { s.MaxProperties = &maximum return s } -// WithMinProperties sets the min number of properties an object must have +// WithMinProperties sets the min number of properties an object must have. func (s *Schema) WithMinProperties(minimum int64) *Schema { s.MinProperties = &minimum return s } -// Typed sets the type of this schema for a single value item +// Typed sets the type of this schema for a single value item. func (s *Schema) Typed(tpe, format string) *Schema { s.Type = []string{tpe} s.Format = format return s } -// AddType adds a type with potential format to the types for this schema +// AddType adds a type with potential format to the types for this schema. func (s *Schema) AddType(tpe, format string) *Schema { s.Type = append(s.Type, tpe) if format != "" { @@ -299,124 +301,124 @@ func (s *Schema) AsNullable() *Schema { return s } -// CollectionOf a fluent builder method for an array parameter +// CollectionOf a fluent builder method for an array parameter. func (s *Schema) CollectionOf(items Schema) *Schema { s.Type = []string{jsonArray} s.Items = &SchemaOrArray{Schema: &items} return s } -// WithDefault sets the default value on this parameter +// WithDefault sets the default value on this parameter. func (s *Schema) WithDefault(defaultValue any) *Schema { s.Default = defaultValue return s } -// WithRequired flags this parameter as required +// WithRequired flags this parameter as required. func (s *Schema) WithRequired(items ...string) *Schema { s.Required = items return s } -// AddRequired adds field names to the required properties array +// AddRequired adds field names to the required properties array. func (s *Schema) AddRequired(items ...string) *Schema { s.Required = append(s.Required, items...) return s } -// WithMaxLength sets a max length value +// WithMaxLength sets a max length value. func (s *Schema) WithMaxLength(maximum int64) *Schema { s.MaxLength = &maximum return s } -// WithMinLength sets a min length value +// WithMinLength sets a min length value. func (s *Schema) WithMinLength(minimum int64) *Schema { s.MinLength = &minimum return s } -// WithPattern sets a pattern value +// WithPattern sets a pattern value. func (s *Schema) WithPattern(pattern string) *Schema { s.Pattern = pattern return s } -// WithMultipleOf sets a multiple of value +// WithMultipleOf sets a multiple of value. func (s *Schema) WithMultipleOf(number float64) *Schema { s.MultipleOf = &number return s } -// WithMaximum sets a maximum number value +// WithMaximum sets a maximum number value. func (s *Schema) WithMaximum(maximum float64, exclusive bool) *Schema { s.Maximum = &maximum s.ExclusiveMaximum = exclusive return s } -// WithMinimum sets a minimum number value +// WithMinimum sets a minimum number value. func (s *Schema) WithMinimum(minimum float64, exclusive bool) *Schema { s.Minimum = &minimum s.ExclusiveMinimum = exclusive return s } -// WithEnum sets a the enum values (replace) +// WithEnum sets a the enum values (replace). func (s *Schema) WithEnum(values ...any) *Schema { s.Enum = append([]any{}, values...) return s } -// WithMaxItems sets the max items +// WithMaxItems sets the max items. func (s *Schema) WithMaxItems(size int64) *Schema { s.MaxItems = &size return s } -// WithMinItems sets the min items +// WithMinItems sets the min items. func (s *Schema) WithMinItems(size int64) *Schema { s.MinItems = &size return s } -// UniqueValues dictates that this array can only have unique items +// UniqueValues dictates that this array can only have unique items. func (s *Schema) UniqueValues() *Schema { s.UniqueItems = true return s } -// AllowDuplicates this array can have duplicates +// AllowDuplicates this array can have duplicates. func (s *Schema) AllowDuplicates() *Schema { s.UniqueItems = false return s } -// AddToAllOf adds a schema to the allOf property +// AddToAllOf adds a schema to the allOf property. func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { s.AllOf = append(s.AllOf, schemas...) return s } -// WithDiscriminator sets the name of the discriminator field +// WithDiscriminator sets the name of the discriminator field. func (s *Schema) WithDiscriminator(discriminator string) *Schema { s.Discriminator = discriminator return s } -// AsReadOnly flags this schema as readonly +// AsReadOnly flags this schema as readonly. func (s *Schema) AsReadOnly() *Schema { s.ReadOnly = true return s } -// AsWritable flags this schema as writeable (not read-only) +// AsWritable flags this schema as writeable (not read-only). func (s *Schema) AsWritable() *Schema { s.ReadOnly = false return s } -// WithExample sets the example for this schema +// WithExample sets the example for this schema. func (s *Schema) WithExample(example any) *Schema { s.Example = example return s @@ -440,7 +442,7 @@ func (s *Schema) WithExternalDocs(description, url string) *Schema { return s } -// WithXMLName sets the xml name for the object +// WithXMLName sets the xml name for the object. func (s *Schema) WithXMLName(name string) *Schema { if s.XML == nil { s.XML = new(XMLObject) @@ -449,7 +451,7 @@ func (s *Schema) WithXMLName(name string) *Schema { return s } -// WithXMLNamespace sets the xml namespace for the object +// WithXMLNamespace sets the xml namespace for the object. func (s *Schema) WithXMLNamespace(namespace string) *Schema { if s.XML == nil { s.XML = new(XMLObject) @@ -458,7 +460,7 @@ func (s *Schema) WithXMLNamespace(namespace string) *Schema { return s } -// WithXMLPrefix sets the xml prefix for the object +// WithXMLPrefix sets the xml prefix for the object. func (s *Schema) WithXMLPrefix(prefix string) *Schema { if s.XML == nil { s.XML = new(XMLObject) @@ -467,7 +469,7 @@ func (s *Schema) WithXMLPrefix(prefix string) *Schema { return s } -// AsXMLAttribute flags this object as xml attribute +// AsXMLAttribute flags this object as xml attribute. func (s *Schema) AsXMLAttribute() *Schema { if s.XML == nil { s.XML = new(XMLObject) @@ -476,7 +478,7 @@ func (s *Schema) AsXMLAttribute() *Schema { return s } -// AsXMLElement flags this object as an xml node +// AsXMLElement flags this object as an xml node. func (s *Schema) AsXMLElement() *Schema { if s.XML == nil { s.XML = new(XMLObject) @@ -485,7 +487,7 @@ func (s *Schema) AsXMLElement() *Schema { return s } -// AsWrappedXML flags this object as wrapped, this is mostly useful for array types +// AsWrappedXML flags this object as wrapped, this is mostly useful for array types. func (s *Schema) AsWrappedXML() *Schema { if s.XML == nil { s.XML = new(XMLObject) @@ -494,7 +496,7 @@ func (s *Schema) AsWrappedXML() *Schema { return s } -// AsUnwrappedXML flags this object as an xml node +// AsUnwrappedXML flags this object as an xml node. func (s *Schema) AsUnwrappedXML() *Schema { if s.XML == nil { s.XML = new(XMLObject) @@ -524,13 +526,13 @@ func (s *Schema) SetValidations(val SchemaValidations) { s.PatternProperties = val.PatternProperties } -// WithValidations is a fluent method to set schema validations +// WithValidations is a fluent method to set schema validations. func (s *Schema) WithValidations(val SchemaValidations) *Schema { s.SetValidations(val) return s } -// Validations returns a clone of the validations for this schema +// Validations returns a clone of the validations for this schema. func (s Schema) Validations() SchemaValidations { return SchemaValidations{ CommonValidations: CommonValidations{ @@ -553,40 +555,40 @@ func (s Schema) Validations() SchemaValidations { } } -// MarshalJSON marshal this to JSON +// MarshalJSON marshal this to JSON. func (s Schema) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(s.SchemaProps) if err != nil { - return nil, fmt.Errorf("schema props %v: %w", err, ErrSpec) + return nil, fmt.Errorf("schema props %w: %w", err, ErrSpec) } b2, err := json.Marshal(s.VendorExtensible) if err != nil { - return nil, fmt.Errorf("vendor props %v: %w", err, ErrSpec) + return nil, fmt.Errorf("vendor props %w: %w", err, ErrSpec) } b3, err := s.Ref.MarshalJSON() if err != nil { - return nil, fmt.Errorf("ref prop %v: %w", err, ErrSpec) + return nil, fmt.Errorf("ref prop %w: %w", err, ErrSpec) } b4, err := s.Schema.MarshalJSON() if err != nil { - return nil, fmt.Errorf("schema prop %v: %w", err, ErrSpec) + return nil, fmt.Errorf("schema prop %w: %w", err, ErrSpec) } b5, err := json.Marshal(s.SwaggerSchemaProps) if err != nil { - return nil, fmt.Errorf("common validations %v: %w", err, ErrSpec) + return nil, fmt.Errorf("common validations %w: %w", err, ErrSpec) } var b6 []byte if s.ExtraProps != nil { jj, err := json.Marshal(s.ExtraProps) if err != nil { - return nil, fmt.Errorf("extra props %v: %w", err, ErrSpec) + return nil, fmt.Errorf("extra props %w: %w", err, ErrSpec) } b6 = jj } return jsonutils.ConcatJSON(b1, b2, b3, b4, b5, b6), nil } -// UnmarshalJSON marshal this from JSON +// UnmarshalJSON marshal this from JSON. func (s *Schema) UnmarshalJSON(data []byte) error { props := struct { SchemaProps diff --git a/vendor/github.com/go-openapi/spec/schema_loader.go b/vendor/github.com/go-openapi/spec/schema_loader.go index 8d4a9853..0894c932 100644 --- a/vendor/github.com/go-openapi/spec/schema_loader.go +++ b/vendor/github.com/go-openapi/spec/schema_loader.go @@ -24,7 +24,7 @@ import ( // NOTE: if you are using the go-openapi/loads package, it will override // this value with its own default (a loader to retrieve YAML documents as // well as JSON ones). -var PathLoader = func(pth string) (json.RawMessage, error) { +var PathLoader = func(pth string) (json.RawMessage, error) { //nolint:gochecknoglobals // package-level default loader, overridable by go-openapi/loads data, err := loading.LoadFromFileOrHTTP(pth) if err != nil { return nil, err @@ -76,7 +76,7 @@ type schemaLoader struct { // // If the schema the ref is referring to holds nested refs, Resolve doesn't resolve them. // -// If basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct +// If basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct. func (r *schemaLoader) Resolve(ref *Ref, target any, basePath string) error { return r.resolveRef(ref, target, basePath) } @@ -136,7 +136,7 @@ func (r *schemaLoader) resolveRef(ref *Ref, target any, basePath string) error { root := r.root if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" { if baseRef, erb := NewRef(basePath); erb == nil { - root, _, _, _ = r.load(baseRef.GetURL()) + root, _ = r.load(baseRef.GetURL()) } } @@ -144,7 +144,7 @@ func (r *schemaLoader) resolveRef(ref *Ref, target any, basePath string) error { data = root } else { baseRef := normalizeRef(ref, basePath) - data, _, _, err = r.load(baseRef.GetURL()) + data, err = r.load(baseRef.GetURL()) if err != nil { return err } @@ -160,33 +160,32 @@ func (r *schemaLoader) resolveRef(ref *Ref, target any, basePath string) error { return jsonutils.FromDynamicJSON(res, target) } -func (r *schemaLoader) load(refURL *url.URL) (any, url.URL, bool, error) { +func (r *schemaLoader) load(refURL *url.URL) (any, error) { debugLog("loading schema from url: %s", refURL) toFetch := *refURL toFetch.Fragment = "" - var err error pth := toFetch.String() normalized := normalizeBase(pth) debugLog("loading doc from: %s", normalized) data, fromCache := r.cache.Get(normalized) if fromCache { - return data, toFetch, fromCache, nil + return data, nil } b, err := r.context.loadDoc(normalized) if err != nil { - return nil, url.URL{}, false, err + return nil, err } var doc any if err := json.Unmarshal(b, &doc); err != nil { - return nil, url.URL{}, false, err + return nil, err } r.cache.Set(normalized, doc) - return doc, toFetch, fromCache, nil + return doc, nil } // isCircular detects cycles in sequences of $ref. @@ -293,8 +292,8 @@ func defaultSchemaLoader( root any, expandOptions *ExpandOptions, cache ResolutionCache, - context *resolverContext) *schemaLoader { - + context *resolverContext, +) *schemaLoader { if expandOptions == nil { expandOptions = &ExpandOptions{} } diff --git a/vendor/github.com/go-openapi/spec/security_scheme.go b/vendor/github.com/go-openapi/spec/security_scheme.go index 46a4a7e2..6d9019e7 100644 --- a/vendor/github.com/go-openapi/spec/security_scheme.go +++ b/vendor/github.com/go-openapi/spec/security_scheme.go @@ -20,17 +20,17 @@ const ( accessCode = "accessCode" ) -// BasicAuth creates a basic auth security scheme +// BasicAuth creates a basic auth security scheme. func BasicAuth() *SecurityScheme { return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: basic}} } -// APIKeyAuth creates an api key auth security scheme +// APIKeyAuth creates an api key auth security scheme. func APIKeyAuth(fieldName, valueSource string) *SecurityScheme { return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: apiKey, Name: fieldName, In: valueSource}} } -// OAuth2Implicit creates an implicit flow oauth2 security scheme +// OAuth2Implicit creates an implicit flow oauth2 security scheme. func OAuth2Implicit(authorizationURL string) *SecurityScheme { return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ Type: oauth2, @@ -39,7 +39,7 @@ func OAuth2Implicit(authorizationURL string) *SecurityScheme { }} } -// OAuth2Password creates a password flow oauth2 security scheme +// OAuth2Password creates a password flow oauth2 security scheme. func OAuth2Password(tokenURL string) *SecurityScheme { return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ Type: oauth2, @@ -48,7 +48,7 @@ func OAuth2Password(tokenURL string) *SecurityScheme { }} } -// OAuth2Application creates an application flow oauth2 security scheme +// OAuth2Application creates an application flow oauth2 security scheme. func OAuth2Application(tokenURL string) *SecurityScheme { return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ Type: oauth2, @@ -57,7 +57,7 @@ func OAuth2Application(tokenURL string) *SecurityScheme { }} } -// OAuth2AccessToken creates an access token flow oauth2 security scheme +// OAuth2AccessToken creates an access token flow oauth2 security scheme. func OAuth2AccessToken(authorizationURL, tokenURL string) *SecurityScheme { return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ Type: oauth2, @@ -67,7 +67,7 @@ func OAuth2AccessToken(authorizationURL, tokenURL string) *SecurityScheme { }} } -// SecuritySchemeProps describes a swagger security scheme in the securityDefinitions section +// SecuritySchemeProps describes a swagger security scheme in the securityDefinitions section. type SecuritySchemeProps struct { Description string `json:"description,omitempty"` Type string `json:"type"` @@ -79,7 +79,7 @@ type SecuritySchemeProps struct { Scopes map[string]string `json:"scopes,omitempty"` // oauth2 } -// AddScope adds a scope to this security scheme +// AddScope adds a scope to this security scheme. func (s *SecuritySchemeProps) AddScope(scope, description string) { if s.Scopes == nil { s.Scopes = make(map[string]string) @@ -97,7 +97,7 @@ type SecurityScheme struct { SecuritySchemeProps } -// JSONLookup implements an interface to customize json pointer lookup +// JSONLookup implements an interface to customize json pointer lookup. func (s SecurityScheme) JSONLookup(token string) (any, error) { if ex, ok := s.Extensions[token]; ok { return &ex, nil @@ -107,7 +107,7 @@ func (s SecurityScheme) JSONLookup(token string) (any, error) { return r, err } -// MarshalJSON marshal this to JSON +// MarshalJSON marshal this to JSON. func (s SecurityScheme) MarshalJSON() ([]byte, error) { var ( b1 []byte @@ -150,7 +150,7 @@ func (s SecurityScheme) MarshalJSON() ([]byte, error) { return jsonutils.ConcatJSON(b1, b2), nil } -// UnmarshalJSON marshal this from JSON +// UnmarshalJSON marshal this from JSON. func (s *SecurityScheme) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { return err diff --git a/vendor/github.com/go-openapi/spec/spec.go b/vendor/github.com/go-openapi/spec/spec.go index 0d0aaabc..4eba04b2 100644 --- a/vendor/github.com/go-openapi/spec/spec.go +++ b/vendor/github.com/go-openapi/spec/spec.go @@ -13,13 +13,13 @@ import ( //go:generate perl -pi -e s,Json,JSON,g bindata.go const ( - // SwaggerSchemaURL the url for the swagger 2.0 schema to validate specs + // SwaggerSchemaURL the url for the swagger 2.0 schema to validate specs. SwaggerSchemaURL = "http://swagger.io/v2/schema.json#" - // JSONSchemaURL the url for the json schema + // JSONSchemaURL the url for the json schema. JSONSchemaURL = "http://json-schema.org/draft-04/schema#" ) -// MustLoadJSONSchemaDraft04 panics when Swagger20Schema returns an error +// MustLoadJSONSchemaDraft04 panics when Swagger20Schema returns an error. func MustLoadJSONSchemaDraft04() *Schema { d, e := JSONSchemaDraft04() if e != nil { @@ -28,7 +28,7 @@ func MustLoadJSONSchemaDraft04() *Schema { return d } -// JSONSchemaDraft04 loads the json schema document for json schema draft04 +// JSONSchemaDraft04 loads the json schema document for json schema draft04. func JSONSchemaDraft04() (*Schema, error) { b, err := jsonschemaDraft04JSONBytes() if err != nil { @@ -42,7 +42,7 @@ func JSONSchemaDraft04() (*Schema, error) { return schema, nil } -// MustLoadSwagger20Schema panics when Swagger20Schema returns an error +// MustLoadSwagger20Schema panics when Swagger20Schema returns an error. func MustLoadSwagger20Schema() *Schema { d, e := Swagger20Schema() if e != nil { @@ -51,9 +51,8 @@ func MustLoadSwagger20Schema() *Schema { return d } -// Swagger20Schema loads the swagger 2.0 schema from the embedded assets +// Swagger20Schema loads the swagger 2.0 schema from the embedded assets. func Swagger20Schema() (*Schema, error) { - b, err := v2SchemaJSONBytes() if err != nil { return nil, err diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go index f7cd0f60..dbe32db8 100644 --- a/vendor/github.com/go-openapi/spec/swagger.go +++ b/vendor/github.com/go-openapi/spec/swagger.go @@ -25,7 +25,7 @@ type Swagger struct { SwaggerProps } -// JSONLookup look up a value by the json property name +// JSONLookup look up a value by the json property name. func (s Swagger) JSONLookup(token string) (any, error) { if ex, ok := s.Extensions[token]; ok { return &ex, nil @@ -34,7 +34,7 @@ func (s Swagger) JSONLookup(token string) (any, error) { return r, err } -// MarshalJSON marshals this swagger structure to json +// MarshalJSON marshals this swagger structure to json. func (s Swagger) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(s.SwaggerProps) if err != nil { @@ -47,7 +47,7 @@ func (s Swagger) MarshalJSON() ([]byte, error) { return jsonutils.ConcatJSON(b1, b2), nil } -// UnmarshalJSON unmarshals a swagger spec from json +// UnmarshalJSON unmarshals a swagger spec from json. func (s *Swagger) UnmarshalJSON(data []byte) error { var sw Swagger if err := json.Unmarshal(data, &sw.SwaggerProps); err != nil { @@ -60,7 +60,7 @@ func (s *Swagger) UnmarshalJSON(data []byte) error { return nil } -// GobEncode provides a safe gob encoder for Swagger, including extensions +// GobEncode provides a safe gob encoder for Swagger, including extensions. func (s Swagger) GobEncode() ([]byte, error) { var b bytes.Buffer raw := struct { @@ -74,7 +74,7 @@ func (s Swagger) GobEncode() ([]byte, error) { return b.Bytes(), err } -// GobDecode provides a safe gob decoder for Swagger, including extensions +// GobDecode provides a safe gob decoder for Swagger, including extensions. func (s *Swagger) GobDecode(b []byte) error { var raw struct { Props SwaggerProps @@ -95,7 +95,7 @@ func (s *Swagger) GobDecode(b []byte) error { // NOTE: validation rules // - the scheme, when present must be from [http, https, ws, wss] // - BasePath must start with a leading "/" -// - Paths is required +// - Paths is required. type SwaggerProps struct { ID string `json:"id,omitempty"` Consumes []string `json:"consumes,omitempty"` @@ -126,7 +126,7 @@ type gobSwaggerPropsAlias struct { SecurityIsEmpty bool } -// GobEncode provides a safe gob encoder for SwaggerProps, including empty security requirements +// GobEncode provides a safe gob encoder for SwaggerProps, including empty security requirements. func (o SwaggerProps) GobEncode() ([]byte, error) { raw := gobSwaggerPropsAlias{ Alias: (*swaggerPropsAlias)(&o), @@ -171,7 +171,7 @@ func (o SwaggerProps) GobEncode() ([]byte, error) { return b.Bytes(), err } -// GobDecode provides a safe gob decoder for SwaggerProps, including empty security requirements +// GobDecode provides a safe gob decoder for SwaggerProps, including empty security requirements. func (o *SwaggerProps) GobDecode(b []byte) error { var raw gobSwaggerPropsAlias @@ -207,16 +207,16 @@ func (o *SwaggerProps) GobDecode(b []byte) error { return nil } -// Dependencies represent a dependencies property +// Dependencies represent a dependencies property. type Dependencies map[string]SchemaOrStringArray -// SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property +// SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property. type SchemaOrBool struct { Allows bool Schema *Schema } -// JSONLookup implements an interface to customize json pointer lookup +// JSONLookup implements an interface to customize json pointer lookup. func (s SchemaOrBool) JSONLookup(token string) (any, error) { if token == "allows" { return s.Allows, nil @@ -225,10 +225,12 @@ func (s SchemaOrBool) JSONLookup(token string) (any, error) { return r, err } -var jsTrue = []byte("true") -var jsFalse = []byte("false") +var ( + jsTrue = []byte("true") //nolint:gochecknoglobals // constant-like byte slices for JSON marshaling + jsFalse = []byte("false") //nolint:gochecknoglobals // constant-like byte slices for JSON marshaling +) -// MarshalJSON convert this object to JSON +// MarshalJSON convert this object to JSON. func (s SchemaOrBool) MarshalJSON() ([]byte, error) { if s.Schema != nil { return json.Marshal(s.Schema) @@ -240,7 +242,7 @@ func (s SchemaOrBool) MarshalJSON() ([]byte, error) { return jsTrue, nil } -// UnmarshalJSON converts this bool or schema object from a JSON structure +// UnmarshalJSON converts this bool or schema object from a JSON structure. func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { var nw SchemaOrBool if len(data) > 0 { @@ -257,19 +259,19 @@ func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { return nil } -// SchemaOrStringArray represents a schema or a string array +// SchemaOrStringArray represents a schema or a string array. type SchemaOrStringArray struct { Schema *Schema Property []string } -// JSONLookup implements an interface to customize json pointer lookup +// JSONLookup implements an interface to customize json pointer lookup. func (s SchemaOrStringArray) JSONLookup(token string) (any, error) { r, _, err := jsonpointer.GetForToken(s.Schema, token) return r, err } -// MarshalJSON converts this schema object or array into JSON structure +// MarshalJSON converts this schema object or array into JSON structure. func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { if len(s.Property) > 0 { return json.Marshal(s.Property) @@ -280,7 +282,7 @@ func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { return []byte("null"), nil } -// UnmarshalJSON converts this schema object or array from a JSON structure +// UnmarshalJSON converts this schema object or array from a JSON structure. func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { var first byte if len(data) > 1 { @@ -318,15 +320,15 @@ type Definitions map[string]Schema type SecurityDefinitions map[string]*SecurityScheme // StringOrArray represents a value that can either be a string -// or an array of strings. Mainly here for serialization purposes +// or an array of strings. Mainly here for serialization purposes. type StringOrArray []string -// Contains returns true when the value is contained in the slice +// Contains returns true when the value is contained in the slice. func (s StringOrArray) Contains(value string) bool { return slices.Contains(s, value) } -// JSONLookup implements an interface to customize json pointer lookup +// JSONLookup implements an interface to customize json pointer lookup. func (s SchemaOrArray) JSONLookup(token string) (any, error) { if _, err := strconv.Atoi(token); err == nil { r, _, err := jsonpointer.GetForToken(s.Schemas, token) @@ -336,7 +338,7 @@ func (s SchemaOrArray) JSONLookup(token string) (any, error) { return r, err } -// UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string +// UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string. func (s *StringOrArray) UnmarshalJSON(data []byte) error { var first byte if len(data) > 1 { @@ -368,7 +370,7 @@ func (s *StringOrArray) UnmarshalJSON(data []byte) error { } } -// MarshalJSON converts this string or array to a JSON array or JSON string +// MarshalJSON converts this string or array to a JSON array or JSON string. func (s StringOrArray) MarshalJSON() ([]byte, error) { if len(s) == 1 { return json.Marshal([]string(s)[0]) @@ -377,13 +379,13 @@ func (s StringOrArray) MarshalJSON() ([]byte, error) { } // SchemaOrArray represents a value that can either be a Schema -// or an array of Schema. Mainly here for serialization purposes +// or an array of Schema. Mainly here for serialization purposes. type SchemaOrArray struct { Schema *Schema Schemas []Schema } -// Len returns the number of schemas in this property +// Len returns the number of schemas in this property. func (s SchemaOrArray) Len() int { if s.Schema != nil { return 1 @@ -391,7 +393,7 @@ func (s SchemaOrArray) Len() int { return len(s.Schemas) } -// ContainsType returns true when one of the schemas is of the specified type +// ContainsType returns true when one of the schemas is of the specified type. func (s *SchemaOrArray) ContainsType(name string) bool { if s.Schema != nil { return s.Schema.Type != nil && s.Schema.Type.Contains(name) @@ -399,7 +401,7 @@ func (s *SchemaOrArray) ContainsType(name string) bool { return false } -// MarshalJSON converts this schema object or array into JSON structure +// MarshalJSON converts this schema object or array into JSON structure. func (s SchemaOrArray) MarshalJSON() ([]byte, error) { if len(s.Schemas) > 0 { return json.Marshal(s.Schemas) @@ -407,7 +409,7 @@ func (s SchemaOrArray) MarshalJSON() ([]byte, error) { return json.Marshal(s.Schema) } -// UnmarshalJSON converts this schema object or array from a JSON structure +// UnmarshalJSON converts this schema object or array from a JSON structure. func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { var nw SchemaOrArray var first byte diff --git a/vendor/github.com/go-openapi/spec/tag.go b/vendor/github.com/go-openapi/spec/tag.go index ae98fd98..af3fb0a4 100644 --- a/vendor/github.com/go-openapi/spec/tag.go +++ b/vendor/github.com/go-openapi/spec/tag.go @@ -10,7 +10,7 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// TagProps describe a tag entry in the top level tags section of a swagger spec +// TagProps describe a tag entry in the top level tags section of a swagger spec. type TagProps struct { Description string `json:"description,omitempty"` Name string `json:"name,omitempty"` @@ -27,12 +27,12 @@ type Tag struct { TagProps } -// NewTag creates a new tag +// NewTag creates a new tag. func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag { return Tag{TagProps: TagProps{Description: description, Name: name, ExternalDocs: externalDocs}} } -// JSONLookup implements an interface to customize json pointer lookup +// JSONLookup implements an interface to customize json pointer lookup. func (t Tag) JSONLookup(token string) (any, error) { if ex, ok := t.Extensions[token]; ok { return &ex, nil @@ -42,7 +42,7 @@ func (t Tag) JSONLookup(token string) (any, error) { return r, err } -// MarshalJSON marshal this to JSON +// MarshalJSON marshal this to JSON. func (t Tag) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(t.TagProps) if err != nil { @@ -55,7 +55,7 @@ func (t Tag) MarshalJSON() ([]byte, error) { return jsonutils.ConcatJSON(b1, b2), nil } -// UnmarshalJSON marshal this from JSON +// UnmarshalJSON marshal this from JSON. func (t *Tag) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &t.TagProps); err != nil { return err diff --git a/vendor/github.com/go-openapi/spec/validations.go b/vendor/github.com/go-openapi/spec/validations.go index 2c0dc424..a82c2ffe 100644 --- a/vendor/github.com/go-openapi/spec/validations.go +++ b/vendor/github.com/go-openapi/spec/validations.go @@ -3,7 +3,7 @@ package spec -// CommonValidations describe common JSON-schema validations +// CommonValidations describe common JSON-schema validations. type CommonValidations struct { Maximum *float64 `json:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` @@ -143,22 +143,22 @@ func (v CommonValidations) Validations() SchemaValidations { } } -// HasNumberValidations indicates if the validations are for numbers or integers +// HasNumberValidations indicates if the validations are for numbers or integers. func (v CommonValidations) HasNumberValidations() bool { return v.Maximum != nil || v.Minimum != nil || v.MultipleOf != nil } -// HasStringValidations indicates if the validations are for strings +// HasStringValidations indicates if the validations are for strings. func (v CommonValidations) HasStringValidations() bool { return v.MaxLength != nil || v.MinLength != nil || v.Pattern != "" } -// HasArrayValidations indicates if the validations are for arrays +// HasArrayValidations indicates if the validations are for arrays. func (v CommonValidations) HasArrayValidations() bool { return v.MaxItems != nil || v.MinItems != nil || v.UniqueItems } -// HasEnum indicates if the validation includes some enum constraint +// HasEnum indicates if the validation includes some enum constraint. func (v CommonValidations) HasEnum() bool { return len(v.Enum) > 0 } @@ -175,12 +175,12 @@ type SchemaValidations struct { MinProperties *int64 `json:"minProperties,omitempty"` } -// HasObjectValidations indicates if the validations are for objects +// HasObjectValidations indicates if the validations are for objects. func (v SchemaValidations) HasObjectValidations() bool { return v.MaxProperties != nil || v.MinProperties != nil || v.PatternProperties != nil } -// SetValidations for schema validations +// SetValidations for schema validations. func (v *SchemaValidations) SetValidations(val SchemaValidations) { v.CommonValidations.SetValidations(val) v.PatternProperties = val.PatternProperties @@ -188,7 +188,7 @@ func (v *SchemaValidations) SetValidations(val SchemaValidations) { v.MinProperties = val.MinProperties } -// Validations for a schema +// Validations for a schema. func (v SchemaValidations) Validations() SchemaValidations { val := v.CommonValidations.Validations() val.PatternProperties = v.PatternProperties diff --git a/vendor/github.com/go-openapi/spec/xml_object.go b/vendor/github.com/go-openapi/spec/xml_object.go index bf2f8f18..07f7ef8c 100644 --- a/vendor/github.com/go-openapi/spec/xml_object.go +++ b/vendor/github.com/go-openapi/spec/xml_object.go @@ -14,43 +14,43 @@ type XMLObject struct { Wrapped bool `json:"wrapped,omitempty"` } -// WithName sets the xml name for the object +// WithName sets the xml name for the object. func (x *XMLObject) WithName(name string) *XMLObject { x.Name = name return x } -// WithNamespace sets the xml namespace for the object +// WithNamespace sets the xml namespace for the object. func (x *XMLObject) WithNamespace(namespace string) *XMLObject { x.Namespace = namespace return x } -// WithPrefix sets the xml prefix for the object +// WithPrefix sets the xml prefix for the object. func (x *XMLObject) WithPrefix(prefix string) *XMLObject { x.Prefix = prefix return x } -// AsAttribute flags this object as xml attribute +// AsAttribute flags this object as xml attribute. func (x *XMLObject) AsAttribute() *XMLObject { x.Attribute = true return x } -// AsElement flags this object as an xml node +// AsElement flags this object as an xml node. func (x *XMLObject) AsElement() *XMLObject { x.Attribute = false return x } -// AsWrapped flags this object as wrapped, this is mostly useful for array types +// AsWrapped flags this object as wrapped, this is mostly useful for array types. func (x *XMLObject) AsWrapped() *XMLObject { x.Wrapped = true return x } -// AsUnwrapped flags this object as an xml node +// AsUnwrapped flags this object as an xml node. func (x *XMLObject) AsUnwrapped() *XMLObject { x.Wrapped = false return x diff --git a/vendor/github.com/go-openapi/errors/.cliff.toml b/vendor/github.com/go-openapi/strfmt/.cliff.toml similarity index 100% rename from vendor/github.com/go-openapi/errors/.cliff.toml rename to vendor/github.com/go-openapi/strfmt/.cliff.toml diff --git a/vendor/github.com/go-openapi/strfmt/.gitignore b/vendor/github.com/go-openapi/strfmt/.gitignore index dd91ed6a..885dc27a 100644 --- a/vendor/github.com/go-openapi/strfmt/.gitignore +++ b/vendor/github.com/go-openapi/strfmt/.gitignore @@ -1,2 +1,6 @@ -secrets.yml -coverage.out +*.out +*.cov +.idea +.env +.mcp.json +.claude/ diff --git a/vendor/github.com/go-openapi/strfmt/.golangci.yml b/vendor/github.com/go-openapi/strfmt/.golangci.yml index 1ad5adf4..3c4cd489 100644 --- a/vendor/github.com/go-openapi/strfmt/.golangci.yml +++ b/vendor/github.com/go-openapi/strfmt/.golangci.yml @@ -2,25 +2,11 @@ version: "2" linters: default: all disable: - - cyclop - depguard - - errchkjson - - errorlint - - exhaustruct - - forcetypeassert - funlen - - gochecknoglobals - - gochecknoinits - - gocognit - - godot + - gomoddirectives - godox - - gosmopolitan - - inamedparam - - intrange - - ireturn - - lll - - musttag - - nestif + - exhaustruct - nlreturn - nonamedreturns - noinlineerr @@ -29,7 +15,6 @@ linters: - testpackage - thelper - tparallel - - unparam - varnamelen - whitespace - wrapcheck @@ -41,8 +26,15 @@ linters: goconst: min-len: 2 min-occurrences: 3 + cyclop: + max-complexity: 20 gocyclo: - min-complexity: 45 + min-complexity: 20 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 exclusions: generated: lax presets: @@ -58,6 +50,7 @@ formatters: enable: - gofmt - goimports + - gofumpt exclusions: generated: lax paths: diff --git a/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/strfmt/CONTRIBUTORS.md b/vendor/github.com/go-openapi/strfmt/CONTRIBUTORS.md new file mode 100644 index 00000000..e0a04712 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/CONTRIBUTORS.md @@ -0,0 +1,52 @@ +# Contributors + +- Repository: ['go-openapi/strfmt'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 40 | 217 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @casualjim | 88 | | +| @fredbi | 49 | | +| @youyuanwu | 13 | | +| @jlambatl | 9 | | +| @GlenDC | 5 | | +| @padamstx | 4 | | +| @dimovnike | 3 | | +| @carlv-stripe | 3 | | +| @Copilot | 3 | | +| @keramix | 3 | | +| @gregmarr | 2 | | +| @vadorovsky | 2 | | +| @Ompluscator | 2 | | +| @johnnyg | 2 | | +| @chakrit | 2 | | +| @bg451 | 2 | | +| @aleksandr-vin | 2 | | +| @ujjwalsh | 1 | | +| @kenjones-cisco | 1 | | +| @jwalter1-quest | 1 | | +| @ccoVeille | 1 | | +| @tylerb | 1 | | +| @tzneal | 1 | | +| @tklauser | 1 | | +| @SuperQ | 1 | | +| @srizzling | 1 | | +| @shawnps | 1 | | +| @prashantv | 1 | | +| @krnkl | 1 | | +| @mstoykov | 1 | | +| @maxatome | 1 | | +| @jerome-laforge | 1 | | +| @justincormack | 1 | | +| @elipavlov | 1 | | +| @gbjk | 1 | | +| @enesanbar | 1 | | +| @CodeLingoBot | 1 | | +| @Kunde21 | 1 | | +| @bvwells | 1 | | +| @ligustah | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/strfmt/README.md b/vendor/github.com/go-openapi/strfmt/README.md index de5afe13..0cab77b7 100644 --- a/vendor/github.com/go-openapi/strfmt/README.md +++ b/vendor/github.com/go-openapi/strfmt/README.md @@ -1,15 +1,61 @@ -# Strfmt [![Build Status](https://github.com/go-openapi/strfmt/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/strfmt/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/strfmt) -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/strfmt/master/LICENSE) -[![GoDoc](https://godoc.org/github.com/go-openapi/strfmt?status.svg)](http://godoc.org/github.com/go-openapi/strfmt) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/strfmt)](https://goreportcard.com/report/github.com/go-openapi/strfmt) +# strfmt + + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] + +--- + +Golang support for string formats defined by JSON Schema and OpenAPI. + +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + +* **2026-03-07** : v0.26.0 **dropped dependency to the mongodb driver** + * mongodb users can still use this package without any change + * however, we have frozen the back-compatible support for mongodb driver at v2.5.0 + * users who want to keep-up with future evolutions (possibly incompatible) of this driver + can do so by adding a blank import in their program: `import _ "github.com/go-openapi/strfmt/enable/mongodb"`. + This will switch the behavior to the actual driver, which remains regularly updated as an independent module. + +## Status + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/strfmt +``` + +## Contents This package exposes a registry of data types to support string formats in the go-openapi toolkit. -strfmt represents a well known string format such as credit card or email. The go toolkit for OpenAPI specifications knows how to deal with those. +`strfmt` represents a well known string format such as hostname or email. + +This package provides a few extra formats such as credit card (US), color, etc. + +Format types can serialize and deserialize JSON or from a SQL database. + +BSON is also supported (MongoDB). + +### Supported formats -## Supported data formats -go-openapi/strfmt follows the swagger 2.0 specification with the following formats +`go-openapi/strfmt` follows the swagger 2.0 specification with the following formats defined [here](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types). It also provides convenient extensions to go-openapi users. @@ -43,7 +89,7 @@ It also provides convenient extensions to go-openapi users. > It does not provide validation for numerical values with swagger format extension for JSON types "number" or > "integer" (e.g. float, double, int32...). -## Type conversion +### Type conversion All types defined here are stringers and may be converted to strings with `.String()`. Note that most types defined by this package may be converted directly to string like `string(Email{})`. @@ -51,13 +97,14 @@ Note that most types defined by this package may be converted directly to string `Date` and `DateTime` may be converted directly to `time.Time` like `time.Time(Time{})`. Similarly, you can convert `Duration` to `time.Duration` as in `time.Duration(Duration{})` -## Using pointers +### Using pointers The `conv` subpackage provides helpers to convert the types to and from pointers, just like `go-openapi/swag` does with primitive types. -## Format types -Types defined in strfmt expose marshaling and validation capabilities. +### Format types + +Types defined in `strfmt` expose marshaling and validation capabilities. List of defined types: - Base64 @@ -87,6 +134,97 @@ List of defined types: - [UUID7](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-7) - [ULID](https://github.com/ulid/spec) +### Database support + +All format types implement the `database/sql` interfaces `sql.Scanner` and `driver.Valuer`, +so they work out of the box with Go's standard `database/sql` package and any SQL driver. + +All format types also implement BSON marshaling/unmarshaling for use with MongoDB. +By default, a built-in minimal codec is used (compatible with mongo-driver v2.5.0). +For full driver support, add `import _ "github.com/go-openapi/strfmt/enable/mongodb"`. + +> **MySQL / MariaDB caveat for `DateTime`:** +> The `go-sql-driver/mysql` driver has hard-coded handling for `time.Time` but does not +> intercept type redefinitions like `strfmt.DateTime`. As a result, `DateTime.Value()` sends +> an RFC 3339 string (e.g. `"2024-06-15T12:30:45.123Z"`) that MySQL/MariaDB rejects for +> `DATETIME` columns. +> +> Workaround: set `strfmt.MarshalFormat` to a MySQL-compatible format such as +> `strfmt.ISO8601LocalTime` and normalize to UTC before marshaling: +> +> ```go +> strfmt.MarshalFormat = strfmt.ISO8601LocalTime +> strfmt.NormalizeTimeForMarshal = func(t time.Time) time.Time { return t.UTC() } +> ``` +> +> See [#174](https://github.com/go-openapi/strfmt/issues/174) for details. + +Integration tests for MongoDB, MariaDB, and PostgreSQL run in CI to verify database roundtrip +compatibility for all format types. See [`internal/testintegration/`](internal/testintegration/). + +## Change log + +See + +## References + + + ## Licensing This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/strfmt/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/strfmt/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/strfmt/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/strfmt +[vuln-scan-badge]: https://github.com/go-openapi/strfmt/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/strfmt/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/strfmt/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/strfmt/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fstrfmt.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fstrfmt +[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fstrfmt.svg +[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fstrfmt + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/strfmt +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/strfmt +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/strfmt +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/strfmt + +[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F +[doc-url]: https://goswagger.io/go-openapi +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/strfmt +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/strfmt +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/strfmt/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/strfmt +[goversion-url]: https://github.com/go-openapi/strfmt/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/strfmt +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/strfmt/latest diff --git a/vendor/github.com/go-openapi/strfmt/SECURITY.md b/vendor/github.com/go-openapi/strfmt/SECURITY.md new file mode 100644 index 00000000..6ceb159c --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/strfmt/bson.go b/vendor/github.com/go-openapi/strfmt/bson.go index 0eec8f64..16a83f64 100644 --- a/vendor/github.com/go-openapi/strfmt/bson.go +++ b/vendor/github.com/go-openapi/strfmt/bson.go @@ -5,62 +5,62 @@ package strfmt import ( "database/sql/driver" + "encoding/hex" + "encoding/json" "fmt" - - bsonprim "go.mongodb.org/mongo-driver/bson/primitive" ) -func init() { +func init() { //nolint:gochecknoinits // registers bsonobjectid format in the default registry var id ObjectId - // register this format in the default registry Default.Add("bsonobjectid", &id, IsBSONObjectID) } -// IsBSONObjectID returns true when the string is a valid BSON.ObjectId +// IsBSONObjectID returns true when the string is a valid BSON [ObjectId]. func IsBSONObjectID(str string) bool { - _, err := bsonprim.ObjectIDFromHex(str) + _, err := objectIDFromHex(str) return err == nil } -// ObjectId represents a BSON object ID (alias to go.mongodb.org/mongo-driver/bson/primitive.ObjectID) +// ObjectId represents a BSON object ID (a 12-byte unique identifier). // -// swagger:strfmt bsonobjectid -type ObjectId bsonprim.ObjectID //nolint:revive +// swagger:strfmt bsonobjectid. +type ObjectId [12]byte //nolint:revive + +// nilObjectID is the zero-value ObjectId. +var nilObjectID ObjectId //nolint:gochecknoglobals // package-level sentinel -// NewObjectId creates a ObjectId from a Hex String +// NewObjectId creates a [ObjectId] from a hexadecimal String. func NewObjectId(hex string) ObjectId { //nolint:revive - oid, err := bsonprim.ObjectIDFromHex(hex) + oid, err := objectIDFromHex(hex) if err != nil { panic(err) } - return ObjectId(oid) + return oid } -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (id ObjectId) MarshalText() ([]byte, error) { - oid := bsonprim.ObjectID(id) - if oid == bsonprim.NilObjectID { + if id == nilObjectID { return nil, nil } - return []byte(oid.Hex()), nil + return []byte(id.Hex()), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (id *ObjectId) UnmarshalText(data []byte) error { // validation is performed later on if len(data) == 0 { - *id = ObjectId(bsonprim.NilObjectID) + *id = nilObjectID return nil } - oidstr := string(data) - oid, err := bsonprim.ObjectIDFromHex(oidstr) + oid, err := objectIDFromHex(string(data)) if err != nil { return err } - *id = ObjectId(oid) + *id = oid return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (id *ObjectId) Scan(raw any) error { var data []byte switch v := raw.(type) { @@ -75,27 +75,36 @@ func (id *ObjectId) Scan(raw any) error { return id.UnmarshalText(data) } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (id ObjectId) Value() (driver.Value, error) { - return driver.Value(bsonprim.ObjectID(id).Hex()), nil + return driver.Value(id.Hex()), nil +} + +// Hex returns the hex string representation of the [ObjectId]. +func (id ObjectId) Hex() string { + return hex.EncodeToString(id[:]) } func (id ObjectId) String() string { - return bsonprim.ObjectID(id).Hex() + return id.Hex() } -// MarshalJSON returns the ObjectId as JSON +// MarshalJSON returns the [ObjectId] as JSON. func (id ObjectId) MarshalJSON() ([]byte, error) { - return bsonprim.ObjectID(id).MarshalJSON() + return json.Marshal(id.Hex()) } -// UnmarshalJSON sets the ObjectId from JSON +// UnmarshalJSON sets the [ObjectId] from JSON. func (id *ObjectId) UnmarshalJSON(data []byte) error { - var obj bsonprim.ObjectID - if err := obj.UnmarshalJSON(data); err != nil { + var hexStr string + if err := json.Unmarshal(data, &hexStr); err != nil { + return err + } + oid, err := objectIDFromHex(hexStr) + if err != nil { return err } - *id = ObjectId(obj) + *id = oid return nil } @@ -104,7 +113,7 @@ func (id *ObjectId) DeepCopyInto(out *ObjectId) { *out = *id } -// DeepCopy copies the receiver into a new ObjectId. +// DeepCopy copies the receiver into a new [ObjectId]. func (id *ObjectId) DeepCopy() *ObjectId { if id == nil { return nil @@ -113,3 +122,18 @@ func (id *ObjectId) DeepCopy() *ObjectId { id.DeepCopyInto(out) return out } + +// objectIDFromHex parses a 24-character hex string into an [ObjectId]. +func objectIDFromHex(s string) (ObjectId, error) { + const objectIDHexLen = 24 + if len(s) != objectIDHexLen { + return nilObjectID, fmt.Errorf("the provided hex string %q is not a valid ObjectID: %w", s, ErrFormat) + } + b, err := hex.DecodeString(s) + if err != nil { + return nilObjectID, fmt.Errorf("the provided hex string %q is not a valid ObjectID: %w", s, err) + } + var oid ObjectId + copy(oid[:], b) + return oid, nil +} diff --git a/vendor/github.com/go-openapi/strfmt/date.go b/vendor/github.com/go-openapi/strfmt/date.go index 8aa17b8e..d299f352 100644 --- a/vendor/github.com/go-openapi/strfmt/date.go +++ b/vendor/github.com/go-openapi/strfmt/date.go @@ -10,35 +10,34 @@ import ( "time" ) -func init() { +func init() { //nolint:gochecknoinits // registers date format in the default registry d := Date{} - // register this format in the default registry Default.Add("date", &d, IsDate) } -// IsDate returns true when the string is a valid date +// IsDate returns true when the string is a valid date. func IsDate(str string) bool { _, err := time.Parse(RFC3339FullDate, str) return err == nil } const ( - // RFC3339FullDate represents a full-date as specified by RFC3339 + // RFC3339FullDate represents a full-date as specified by RFC3339. // See: http://goo.gl/xXOvVd RFC3339FullDate = "2006-01-02" ) -// Date represents a date from the API +// Date represents a date from the API. // -// swagger:strfmt date +// swagger:[strfmt] date. type Date time.Time -// String converts this date into a string +// String converts this date into a string. func (d Date) String() string { return time.Time(d).Format(RFC3339FullDate) } -// UnmarshalText parses a text representation into a date type +// UnmarshalText parses a text representation into a date type. func (d *Date) UnmarshalText(text []byte) error { if len(text) == 0 { return nil @@ -51,7 +50,7 @@ func (d *Date) UnmarshalText(text []byte) error { return nil } -// MarshalText serializes this date type to string +// MarshalText serializes this date type to string. func (d Date) MarshalText() ([]byte, error) { return []byte(d.String()), nil } @@ -79,12 +78,12 @@ func (d Date) Value() (driver.Value, error) { return driver.Value(d.String()), nil } -// MarshalJSON returns the Date as JSON +// MarshalJSON returns the Date as JSON. func (d Date) MarshalJSON() ([]byte, error) { return json.Marshal(time.Time(d).Format(RFC3339FullDate)) } -// UnmarshalJSON sets the Date from JSON +// UnmarshalJSON sets the Date from JSON. func (d *Date) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -126,12 +125,12 @@ func (d *Date) GobDecode(data []byte) error { return d.UnmarshalBinary(data) } -// MarshalBinary implements the encoding.BinaryMarshaler interface. +// MarshalBinary implements the encoding.[encoding.BinaryMarshaler] interface. func (d Date) MarshalBinary() ([]byte, error) { return time.Time(d).MarshalBinary() } -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +// UnmarshalBinary implements the encoding.[encoding.BinaryUnmarshaler] interface. func (d *Date) UnmarshalBinary(data []byte) error { var original time.Time @@ -145,7 +144,7 @@ func (d *Date) UnmarshalBinary(data []byte) error { return nil } -// Equal checks if two Date instances are equal +// Equal checks if two Date instances are equal. func (d Date) Equal(d2 Date) bool { return time.Time(d).Equal(time.Time(d2)) } diff --git a/vendor/github.com/go-openapi/strfmt/default.go b/vendor/github.com/go-openapi/strfmt/default.go index 8a80cfbd..87d3856a 100644 --- a/vendor/github.com/go-openapi/strfmt/default.go +++ b/vendor/github.com/go-openapi/strfmt/default.go @@ -21,42 +21,48 @@ import ( ) const ( - // HostnamePattern http://json-schema.org/latest/json-schema-validation.html#anchor114. + // HostnamePattern http://[json]-schema.org/latest/[json]-schema-validation.html#anchor114. // // Deprecated: this package no longer uses regular expressions to validate hostnames. - HostnamePattern = `^([a-zA-Z0-9\p{S}\p{L}]((-?[a-zA-Z0-9\p{S}\p{L}]{0,62})?)|([a-zA-Z0-9\p{S}\p{L}](([a-zA-Z0-9-\p{S}\p{L}]{0,61}[a-zA-Z0-9\p{S}\p{L}])?)(\.)){1,}([a-zA-Z0-9-\p{L}]){2,63})$` + HostnamePattern = `^([a-zA-Z0-9\p{S}\p{L}]((-?[a-zA-Z0-9\p{S}\p{L}]{0,62})?)` + + `|([a-zA-Z0-9\p{S}\p{L}](([a-zA-Z0-9-\p{S}\p{L}]{0,61}[a-zA-Z0-9\p{S}\p{L}])?)(\.)){1,}([a-zA-Z0-9-\p{L}]){2,63})$` - // json null type + // json null type. jsonNull = "null" ) const ( - // UUIDPattern Regex for UUID that allows uppercase + // UUIDPattern Regex for [UUID] that allows uppercase // - // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + // Deprecated: [strfmt] no longer uses regular expressions to validate UUIDs. UUIDPattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$)|(^[0-9a-f]{32}$)` - // UUID3Pattern Regex for UUID3 that allows uppercase + // UUID3Pattern Regex for [UUID3] that allows uppercase // - // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + // Deprecated: [strfmt] no longer uses regular expressions to validate UUIDs. UUID3Pattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$)|(^[0-9a-f]{12}3[0-9a-f]{3}?[0-9a-f]{16}$)` - // UUID4Pattern Regex for UUID4 that allows uppercase + // UUID4Pattern Regex for [UUID4] that allows uppercase // - // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + // Deprecated: [strfmt] no longer uses regular expressions to validate UUIDs. UUID4Pattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$)|(^[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}$)` - // UUID5Pattern Regex for UUID5 that allows uppercase + // UUID5Pattern Regex for [UUID]5 that allows uppercase // - // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + // Deprecated: [strfmt] no longer uses regular expressions to validate UUIDs. UUID5Pattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$)|(^[0-9a-f]{12}5[0-9a-f]{3}[89ab][0-9a-f]{15}$)` - isbn10Pattern string = "^(?:[0-9]{9}X|[0-9]{10})$" - isbn13Pattern string = "^(?:[0-9]{13})$" - usCardPattern string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$" + isbn10Pattern string = "^(?:[0-9]{9}X|[0-9]{10})$" + isbn13Pattern string = "^(?:[0-9]{13})$" + usCardPattern string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}" + + "|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}" + + "|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}" + + "|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$" ssnPattern string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` hexColorPattern string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" - rgbColorPattern string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$" + rgbColorPattern string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*," + + "\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*," + + "\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$" ) const ( @@ -65,6 +71,7 @@ const ( decimalBase = 10 ) +//nolint:gochecknoglobals // package-level compiled patterns and validators var ( idnaHostChecker = idna.New( idna.ValidateForRegistration(), // shorthand for [idna.StrictDomainName], [idna.ValidateLabels], [idna.VerifyDNSLength], [idna.BidiRule] @@ -87,11 +94,12 @@ var ( // It supports IDNA rules regarding internationalized names with unicode. // // Besides: -// * the empty string is not a valid host name -// * a trailing dot is allowed in names and IPv4's (not IPv6) -// * a host name can be a valid IPv4 (with decimal, octal or hexadecimal numbers) or IPv6 address -// * IPv6 zones are disallowed -// * top-level domains can be unicode (cf. https://www.iana.org/domains/root/db). +// +// - the empty string is not a valid host name +// - a trailing dot is allowed in names and [IPv4]'s (not [IPv6]) +// - a host name can be a valid [IPv4] (with decimal, octal or hexadecimal numbers) or [IPv6] address +// - [IPv6] zones are disallowed +// - top-level domains can be unicode (cf. https://www.iana.org/domains/root/db). // // NOTE: this validator doesn't check top-level domains against the IANA root database. // It merely ensures that a top-level domain in a FQDN is at least 2 code points long. @@ -325,7 +333,7 @@ func isASCIIDigit(c byte) bool { return c >= '0' && c <= '9' } -// IsUUID returns true is the string matches a UUID (in any version, including v6 and v7), upper case is allowed +// IsUUID returns true if the string matches a [UUID] (in any version, including v6 and v7), upper case is allowed. func IsUUID(str string) bool { _, err := uuid.Parse(str) return err == nil @@ -338,25 +346,25 @@ const ( uuidV7 = 7 ) -// IsUUID3 returns true is the string matches a UUID v3, upper case is allowed +// IsUUID3 returns true if the string matches a [UUID] v3, upper case is allowed. func IsUUID3(str string) bool { id, err := uuid.Parse(str) return err == nil && id.Version() == uuid.Version(uuidV3) } -// IsUUID4 returns true is the string matches a UUID v4, upper case is allowed +// IsUUID4 returns true is the string matches a [UUID] v4, upper case is allowed. func IsUUID4(str string) bool { id, err := uuid.Parse(str) return err == nil && id.Version() == uuid.Version(uuidV4) } -// IsUUID5 returns true is the string matches a UUID v5, upper case is allowed +// IsUUID5 returns true if the string matches a [UUID] v5, upper case is allowed. func IsUUID5(str string) bool { id, err := uuid.Parse(str) return err == nil && id.Version() == uuid.Version(uuidV5) } -// IsUUID7 returns true is the string matches a UUID v7, upper case is allowed +// IsUUID7 returns true if the string matches a [UUID] v7, upper case is allowed. func IsUUID7(str string) bool { id, err := uuid.Parse(str) return err == nil && id.Version() == uuid.Version(uuidV7) @@ -368,7 +376,7 @@ func IsEmail(str string) bool { return e == nil && addr.Address != "" } -func init() { +func init() { //nolint:gochecknoinits // registers all default string formats in the registry // register formats in the default registry: // - byte // - creditcard @@ -455,12 +463,12 @@ func init() { Default.Add("password", &pw, func(_ string) bool { return true }) } -// Base64 represents a base64 encoded string, using URLEncoding alphabet +// Base64 represents a base64 encoded string, using URLEncoding alphabet. // -// swagger:strfmt byte +// swagger:strfmt byte. type Base64 []byte -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (b Base64) MarshalText() ([]byte, error) { enc := base64.URLEncoding src := []byte(b) @@ -469,7 +477,7 @@ func (b Base64) MarshalText() ([]byte, error) { return buf, nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (b *Base64) UnmarshalText(data []byte) error { // validation is performed later on enc := base64.URLEncoding dbuf := make([]byte, enc.DecodedLen(len(data))) @@ -483,7 +491,7 @@ func (b *Base64) UnmarshalText(data []byte) error { // validation is performed l return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (b *Base64) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -506,7 +514,7 @@ func (b *Base64) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (b Base64) Value() (driver.Value, error) { return driver.Value(b.String()), nil } @@ -515,12 +523,12 @@ func (b Base64) String() string { return base64.StdEncoding.EncodeToString([]byte(b)) } -// MarshalJSON returns the Base64 as JSON +// MarshalJSON returns the Base64 as JSON. func (b Base64) MarshalJSON() ([]byte, error) { return json.Marshal(b.String()) } -// UnmarshalJSON sets the Base64 from JSON +// UnmarshalJSON sets the Base64 from JSON. func (b *Base64) UnmarshalJSON(data []byte) error { var b64str string if err := json.Unmarshal(data, &b64str); err != nil { @@ -549,23 +557,23 @@ func (b *Base64) DeepCopy() *Base64 { return out } -// URI represents the uri string format as specified by the json schema spec +// URI represents the uri string format as specified by the [json] schema spec. // -// swagger:strfmt uri +// swagger:strfmt uri. type URI string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u URI) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *URI) UnmarshalText(data []byte) error { // validation is performed later on *u = URI(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *URI) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -579,7 +587,7 @@ func (u *URI) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u URI) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -588,12 +596,12 @@ func (u URI) String() string { return string(u) } -// MarshalJSON returns the URI as JSON +// MarshalJSON returns the [URI] as JSON. func (u URI) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the URI from JSON +// UnmarshalJSON sets the [URI] from JSON. func (u *URI) UnmarshalJSON(data []byte) error { var uristr string if err := json.Unmarshal(data, &uristr); err != nil { @@ -608,7 +616,7 @@ func (u *URI) DeepCopyInto(out *URI) { *out = *u } -// DeepCopy copies the receiver into a new URI. +// DeepCopy copies the receiver into a new [URI]. func (u *URI) DeepCopy() *URI { if u == nil { return nil @@ -618,23 +626,23 @@ func (u *URI) DeepCopy() *URI { return out } -// Email represents the email string format as specified by the json schema spec +// Email represents the email string format as specified by the [json] schema spec. // -// swagger:strfmt email +// swagger:strfmt email. type Email string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (e Email) MarshalText() ([]byte, error) { return []byte(string(e)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (e *Email) UnmarshalText(data []byte) error { // validation is performed later on *e = Email(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (e *Email) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -648,7 +656,7 @@ func (e *Email) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (e Email) Value() (driver.Value, error) { return driver.Value(string(e)), nil } @@ -657,12 +665,12 @@ func (e Email) String() string { return string(e) } -// MarshalJSON returns the Email as JSON +// MarshalJSON returns the Email as JSON. func (e Email) MarshalJSON() ([]byte, error) { return json.Marshal(string(e)) } -// UnmarshalJSON sets the Email from JSON +// UnmarshalJSON sets the Email from JSON. func (e *Email) UnmarshalJSON(data []byte) error { var estr string if err := json.Unmarshal(data, &estr); err != nil { @@ -687,23 +695,23 @@ func (e *Email) DeepCopy() *Email { return out } -// Hostname represents the hostname string format as specified by the json schema spec +// Hostname represents the hostname string format as specified by the [json] schema spec. // -// swagger:strfmt hostname +// swagger:strfmt hostname. type Hostname string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (h Hostname) MarshalText() ([]byte, error) { return []byte(string(h)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (h *Hostname) UnmarshalText(data []byte) error { // validation is performed later on *h = Hostname(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (h *Hostname) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -717,7 +725,7 @@ func (h *Hostname) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (h Hostname) Value() (driver.Value, error) { return driver.Value(string(h)), nil } @@ -726,12 +734,12 @@ func (h Hostname) String() string { return string(h) } -// MarshalJSON returns the Hostname as JSON +// MarshalJSON returns the [Hostname] as JSON. func (h Hostname) MarshalJSON() ([]byte, error) { return json.Marshal(string(h)) } -// UnmarshalJSON sets the Hostname from JSON +// UnmarshalJSON sets the [Hostname] from JSON. func (h *Hostname) UnmarshalJSON(data []byte) error { var hstr string if err := json.Unmarshal(data, &hstr); err != nil { @@ -746,7 +754,7 @@ func (h *Hostname) DeepCopyInto(out *Hostname) { *out = *h } -// DeepCopy copies the receiver into a new Hostname. +// DeepCopy copies the receiver into a new [Hostname]. func (h *Hostname) DeepCopy() *Hostname { if h == nil { return nil @@ -756,23 +764,23 @@ func (h *Hostname) DeepCopy() *Hostname { return out } -// IPv4 represents an IP v4 address +// IPv4 represents an IP v4 address. // -// swagger:strfmt ipv4 +// swagger:strfmt ipv4. type IPv4 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u IPv4) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *IPv4) UnmarshalText(data []byte) error { // validation is performed later on *u = IPv4(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *IPv4) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -786,7 +794,7 @@ func (u *IPv4) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u IPv4) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -795,12 +803,12 @@ func (u IPv4) String() string { return string(u) } -// MarshalJSON returns the IPv4 as JSON +// MarshalJSON returns the [IPv4] as JSON. func (u IPv4) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the IPv4 from JSON +// UnmarshalJSON sets the [IPv4] from JSON. func (u *IPv4) UnmarshalJSON(data []byte) error { var ustr string if err := json.Unmarshal(data, &ustr); err != nil { @@ -815,7 +823,7 @@ func (u *IPv4) DeepCopyInto(out *IPv4) { *out = *u } -// DeepCopy copies the receiver into a new IPv4. +// DeepCopy copies the receiver into a new [IPv4]. func (u *IPv4) DeepCopy() *IPv4 { if u == nil { return nil @@ -825,23 +833,23 @@ func (u *IPv4) DeepCopy() *IPv4 { return out } -// IPv6 represents an IP v6 address +// IPv6 represents an IP v6 address. // -// swagger:strfmt ipv6 +// swagger:strfmt ipv6. type IPv6 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u IPv6) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *IPv6) UnmarshalText(data []byte) error { // validation is performed later on *u = IPv6(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *IPv6) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -855,7 +863,7 @@ func (u *IPv6) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u IPv6) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -864,12 +872,12 @@ func (u IPv6) String() string { return string(u) } -// MarshalJSON returns the IPv6 as JSON +// MarshalJSON returns the [IPv6] as JSON. func (u IPv6) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the IPv6 from JSON +// UnmarshalJSON sets the [IPv6] from JSON. func (u *IPv6) UnmarshalJSON(data []byte) error { var ustr string if err := json.Unmarshal(data, &ustr); err != nil { @@ -884,7 +892,7 @@ func (u *IPv6) DeepCopyInto(out *IPv6) { *out = *u } -// DeepCopy copies the receiver into a new IPv6. +// DeepCopy copies the receiver into a new [IPv6]. func (u *IPv6) DeepCopy() *IPv6 { if u == nil { return nil @@ -894,23 +902,23 @@ func (u *IPv6) DeepCopy() *IPv6 { return out } -// CIDR represents a Classless Inter-Domain Routing notation +// CIDR represents a Classless Inter-Domain Routing notation. // -// swagger:strfmt cidr +// swagger:strfmt cidr. type CIDR string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u CIDR) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *CIDR) UnmarshalText(data []byte) error { // validation is performed later on *u = CIDR(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *CIDR) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -924,7 +932,7 @@ func (u *CIDR) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u CIDR) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -933,12 +941,12 @@ func (u CIDR) String() string { return string(u) } -// MarshalJSON returns the CIDR as JSON +// MarshalJSON returns the [CIDR] as JSON. func (u CIDR) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the CIDR from JSON +// UnmarshalJSON sets the [CIDR] from JSON. func (u *CIDR) UnmarshalJSON(data []byte) error { var ustr string if err := json.Unmarshal(data, &ustr); err != nil { @@ -953,7 +961,7 @@ func (u *CIDR) DeepCopyInto(out *CIDR) { *out = *u } -// DeepCopy copies the receiver into a new CIDR. +// DeepCopy copies the receiver into a new [CIDR]. func (u *CIDR) DeepCopy() *CIDR { if u == nil { return nil @@ -963,23 +971,23 @@ func (u *CIDR) DeepCopy() *CIDR { return out } -// MAC represents a 48 bit MAC address +// MAC represents a 48 bit MAC address. // -// swagger:strfmt mac +// swagger:strfmt mac. type MAC string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u MAC) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *MAC) UnmarshalText(data []byte) error { // validation is performed later on *u = MAC(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *MAC) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -993,7 +1001,7 @@ func (u *MAC) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u MAC) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1002,12 +1010,12 @@ func (u MAC) String() string { return string(u) } -// MarshalJSON returns the MAC as JSON +// MarshalJSON returns the [MAC] as JSON. func (u MAC) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the MAC from JSON +// UnmarshalJSON sets the [MAC] from JSON. func (u *MAC) UnmarshalJSON(data []byte) error { var ustr string if err := json.Unmarshal(data, &ustr); err != nil { @@ -1022,7 +1030,7 @@ func (u *MAC) DeepCopyInto(out *MAC) { *out = *u } -// DeepCopy copies the receiver into a new MAC. +// DeepCopy copies the receiver into a new [MAC]. func (u *MAC) DeepCopy() *MAC { if u == nil { return nil @@ -1032,23 +1040,23 @@ func (u *MAC) DeepCopy() *MAC { return out } -// UUID represents a uuid string format +// UUID represents a [uuid] string format // -// swagger:strfmt uuid +// swagger:strfmt uuid. type UUID string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u UUID) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *UUID) UnmarshalText(data []byte) error { // validation is performed later on *u = UUID(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *UUID) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1062,7 +1070,7 @@ func (u *UUID) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u UUID) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1071,12 +1079,12 @@ func (u UUID) String() string { return string(u) } -// MarshalJSON returns the UUID as JSON +// MarshalJSON returns the [UUID] as JSON. func (u UUID) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the UUID from JSON +// UnmarshalJSON sets the [UUID] from JSON. func (u *UUID) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1094,7 +1102,7 @@ func (u *UUID) DeepCopyInto(out *UUID) { *out = *u } -// DeepCopy copies the receiver into a new UUID. +// DeepCopy copies the receiver into a new [UUID]. func (u *UUID) DeepCopy() *UUID { if u == nil { return nil @@ -1104,23 +1112,23 @@ func (u *UUID) DeepCopy() *UUID { return out } -// UUID3 represents a uuid3 string format +// UUID3 represents a uuid3 string format. // -// swagger:strfmt uuid3 +// swagger:strfmt uuid3. type UUID3 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u UUID3) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *UUID3) UnmarshalText(data []byte) error { // validation is performed later on *u = UUID3(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *UUID3) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1134,7 +1142,7 @@ func (u *UUID3) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u UUID3) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1143,12 +1151,12 @@ func (u UUID3) String() string { return string(u) } -// MarshalJSON returns the UUID as JSON +// MarshalJSON returns the [UUID3] as JSON. func (u UUID3) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the UUID from JSON +// UnmarshalJSON sets the [UUID3] from JSON. func (u *UUID3) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1166,7 +1174,7 @@ func (u *UUID3) DeepCopyInto(out *UUID3) { *out = *u } -// DeepCopy copies the receiver into a new UUID3. +// DeepCopy copies the receiver into a new [UUID]3. func (u *UUID3) DeepCopy() *UUID3 { if u == nil { return nil @@ -1176,23 +1184,23 @@ func (u *UUID3) DeepCopy() *UUID3 { return out } -// UUID4 represents a uuid4 string format +// UUID4 represents a uuid4 string format. // -// swagger:strfmt uuid4 +// swagger:strfmt uuid4. type UUID4 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u UUID4) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *UUID4) UnmarshalText(data []byte) error { // validation is performed later on *u = UUID4(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *UUID4) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1206,7 +1214,7 @@ func (u *UUID4) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u UUID4) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1215,12 +1223,12 @@ func (u UUID4) String() string { return string(u) } -// MarshalJSON returns the UUID as JSON +// MarshalJSON returns the [UUID4] as JSON. func (u UUID4) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the UUID from JSON +// UnmarshalJSON sets the [UUID4] from JSON. func (u *UUID4) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1248,23 +1256,23 @@ func (u *UUID4) DeepCopy() *UUID4 { return out } -// UUID5 represents a uuid5 string format +// UUID5 represents a uuid5 string format. // -// swagger:strfmt uuid5 +// swagger:strfmt uuid5. type UUID5 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u UUID5) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *UUID5) UnmarshalText(data []byte) error { // validation is performed later on *u = UUID5(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *UUID5) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1278,7 +1286,7 @@ func (u *UUID5) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u UUID5) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1287,12 +1295,12 @@ func (u UUID5) String() string { return string(u) } -// MarshalJSON returns the UUID as JSON +// MarshalJSON returns the [UUID5] as JSON. func (u UUID5) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the UUID from JSON +// UnmarshalJSON sets the [UUID5] from JSON. func (u *UUID5) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1310,7 +1318,7 @@ func (u *UUID5) DeepCopyInto(out *UUID5) { *out = *u } -// DeepCopy copies the receiver into a new UUID5. +// DeepCopy copies the receiver into a new [UUID5]. func (u *UUID5) DeepCopy() *UUID5 { if u == nil { return nil @@ -1320,23 +1328,23 @@ func (u *UUID5) DeepCopy() *UUID5 { return out } -// UUID7 represents a uuid7 string format +// UUID7 represents a uuid7 string format. // -// swagger:strfmt uuid7 +// swagger:strfmt uuid7. type UUID7 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u UUID7) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *UUID7) UnmarshalText(data []byte) error { // validation is performed later on *u = UUID7(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *UUID7) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1350,7 +1358,7 @@ func (u *UUID7) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u UUID7) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1359,12 +1367,12 @@ func (u UUID7) String() string { return string(u) } -// MarshalJSON returns the UUID as JSON +// MarshalJSON returns the [UUID7] as JSON. func (u UUID7) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the UUID from JSON +// UnmarshalJSON sets the [UUID7] from JSON. func (u *UUID7) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1382,7 +1390,7 @@ func (u *UUID7) DeepCopyInto(out *UUID7) { *out = *u } -// DeepCopy copies the receiver into a new UUID7. +// DeepCopy copies the receiver into a new [UUID]7. func (u *UUID7) DeepCopy() *UUID7 { if u == nil { return nil @@ -1392,23 +1400,23 @@ func (u *UUID7) DeepCopy() *UUID7 { return out } -// ISBN represents an isbn string format +// ISBN represents an isbn string format. // -// swagger:strfmt isbn +// swagger:strfmt isbn. type ISBN string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u ISBN) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *ISBN) UnmarshalText(data []byte) error { // validation is performed later on *u = ISBN(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *ISBN) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1422,7 +1430,7 @@ func (u *ISBN) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u ISBN) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1431,12 +1439,12 @@ func (u ISBN) String() string { return string(u) } -// MarshalJSON returns the ISBN as JSON +// MarshalJSON returns the [ISBN] as JSON. func (u ISBN) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the ISBN from JSON +// UnmarshalJSON sets the [ISBN] from JSON. func (u *ISBN) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1454,7 +1462,7 @@ func (u *ISBN) DeepCopyInto(out *ISBN) { *out = *u } -// DeepCopy copies the receiver into a new ISBN. +// DeepCopy copies the receiver into a new [ISBN]. func (u *ISBN) DeepCopy() *ISBN { if u == nil { return nil @@ -1464,23 +1472,23 @@ func (u *ISBN) DeepCopy() *ISBN { return out } -// ISBN10 represents an isbn 10 string format +// ISBN10 represents an isbn 10 string format. // -// swagger:strfmt isbn10 +// swagger:strfmt isbn10. type ISBN10 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u ISBN10) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *ISBN10) UnmarshalText(data []byte) error { // validation is performed later on *u = ISBN10(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *ISBN10) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1494,7 +1502,7 @@ func (u *ISBN10) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u ISBN10) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1503,12 +1511,12 @@ func (u ISBN10) String() string { return string(u) } -// MarshalJSON returns the ISBN10 as JSON +// MarshalJSON returns the [ISBN10] as JSON. func (u ISBN10) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the ISBN10 from JSON +// UnmarshalJSON sets the [ISBN10] from JSON. func (u *ISBN10) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1526,7 +1534,7 @@ func (u *ISBN10) DeepCopyInto(out *ISBN10) { *out = *u } -// DeepCopy copies the receiver into a new ISBN10. +// DeepCopy copies the receiver into a new [ISBN10]. func (u *ISBN10) DeepCopy() *ISBN10 { if u == nil { return nil @@ -1536,23 +1544,23 @@ func (u *ISBN10) DeepCopy() *ISBN10 { return out } -// ISBN13 represents an isbn 13 string format +// ISBN13 represents an isbn 13 string format. // -// swagger:strfmt isbn13 +// swagger:strfmt isbn13. type ISBN13 string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u ISBN13) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *ISBN13) UnmarshalText(data []byte) error { // validation is performed later on *u = ISBN13(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *ISBN13) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1566,7 +1574,7 @@ func (u *ISBN13) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u ISBN13) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1575,12 +1583,12 @@ func (u ISBN13) String() string { return string(u) } -// MarshalJSON returns the ISBN13 as JSON +// MarshalJSON returns the [ISBN13] as JSON. func (u ISBN13) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the ISBN13 from JSON +// UnmarshalJSON sets the [ISBN13] from JSON. func (u *ISBN13) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1598,7 +1606,7 @@ func (u *ISBN13) DeepCopyInto(out *ISBN13) { *out = *u } -// DeepCopy copies the receiver into a new ISBN13. +// DeepCopy copies the receiver into a new [ISBN13]. func (u *ISBN13) DeepCopy() *ISBN13 { if u == nil { return nil @@ -1608,23 +1616,23 @@ func (u *ISBN13) DeepCopy() *ISBN13 { return out } -// CreditCard represents a credit card string format +// CreditCard represents a credit card string format. // -// swagger:strfmt creditcard +// swagger:strfmt creditcard. type CreditCard string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u CreditCard) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *CreditCard) UnmarshalText(data []byte) error { // validation is performed later on *u = CreditCard(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *CreditCard) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1638,7 +1646,7 @@ func (u *CreditCard) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u CreditCard) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1647,12 +1655,12 @@ func (u CreditCard) String() string { return string(u) } -// MarshalJSON returns the CreditCard as JSON +// MarshalJSON returns the [CreditCard] as JSON. func (u CreditCard) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the CreditCard from JSON +// UnmarshalJSON sets the [CreditCard] from JSON. func (u *CreditCard) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1670,7 +1678,7 @@ func (u *CreditCard) DeepCopyInto(out *CreditCard) { *out = *u } -// DeepCopy copies the receiver into a new CreditCard. +// DeepCopy copies the receiver into a new [CreditCard]. func (u *CreditCard) DeepCopy() *CreditCard { if u == nil { return nil @@ -1680,23 +1688,23 @@ func (u *CreditCard) DeepCopy() *CreditCard { return out } -// SSN represents a social security string format +// SSN represents a social security string format. // -// swagger:strfmt ssn +// swagger:strfmt ssn. type SSN string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (u SSN) MarshalText() ([]byte, error) { return []byte(string(u)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *SSN) UnmarshalText(data []byte) error { // validation is performed later on *u = SSN(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (u *SSN) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1710,7 +1718,7 @@ func (u *SSN) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u SSN) Value() (driver.Value, error) { return driver.Value(string(u)), nil } @@ -1719,12 +1727,12 @@ func (u SSN) String() string { return string(u) } -// MarshalJSON returns the SSN as JSON +// MarshalJSON returns the [SSN] as JSON. func (u SSN) MarshalJSON() ([]byte, error) { return json.Marshal(string(u)) } -// UnmarshalJSON sets the SSN from JSON +// UnmarshalJSON sets the [SSN] from JSON. func (u *SSN) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1742,7 +1750,7 @@ func (u *SSN) DeepCopyInto(out *SSN) { *out = *u } -// DeepCopy copies the receiver into a new SSN. +// DeepCopy copies the receiver into a new [SSN]. func (u *SSN) DeepCopy() *SSN { if u == nil { return nil @@ -1752,23 +1760,23 @@ func (u *SSN) DeepCopy() *SSN { return out } -// HexColor represents a hex color string format +// HexColor represents a hex color string format. // -// swagger:strfmt hexcolor +// swagger:strfmt hexcolor. type HexColor string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (h HexColor) MarshalText() ([]byte, error) { return []byte(string(h)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (h *HexColor) UnmarshalText(data []byte) error { // validation is performed later on *h = HexColor(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (h *HexColor) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1782,7 +1790,7 @@ func (h *HexColor) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (h HexColor) Value() (driver.Value, error) { return driver.Value(string(h)), nil } @@ -1791,12 +1799,12 @@ func (h HexColor) String() string { return string(h) } -// MarshalJSON returns the HexColor as JSON +// MarshalJSON returns the [HexColor] as JSON. func (h HexColor) MarshalJSON() ([]byte, error) { return json.Marshal(string(h)) } -// UnmarshalJSON sets the HexColor from JSON +// UnmarshalJSON sets the [HexColor] from JSON. func (h *HexColor) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1814,7 +1822,7 @@ func (h *HexColor) DeepCopyInto(out *HexColor) { *out = *h } -// DeepCopy copies the receiver into a new HexColor. +// DeepCopy copies the receiver into a new [HexColor]. func (h *HexColor) DeepCopy() *HexColor { if h == nil { return nil @@ -1824,23 +1832,23 @@ func (h *HexColor) DeepCopy() *HexColor { return out } -// RGBColor represents a RGB color string format +// RGBColor represents a RGB color string format. // -// swagger:strfmt rgbcolor +// swagger:strfmt rgbcolor. type RGBColor string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (r RGBColor) MarshalText() ([]byte, error) { return []byte(string(r)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (r *RGBColor) UnmarshalText(data []byte) error { // validation is performed later on *r = RGBColor(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (r *RGBColor) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1854,7 +1862,7 @@ func (r *RGBColor) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (r RGBColor) Value() (driver.Value, error) { return driver.Value(string(r)), nil } @@ -1863,12 +1871,12 @@ func (r RGBColor) String() string { return string(r) } -// MarshalJSON returns the RGBColor as JSON +// MarshalJSON returns the [RGBColor] as JSON. func (r RGBColor) MarshalJSON() ([]byte, error) { return json.Marshal(string(r)) } -// UnmarshalJSON sets the RGBColor from JSON +// UnmarshalJSON sets the [RGBColor] from JSON. func (r *RGBColor) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1886,7 +1894,7 @@ func (r *RGBColor) DeepCopyInto(out *RGBColor) { *out = *r } -// DeepCopy copies the receiver into a new RGBColor. +// DeepCopy copies the receiver into a new [RGBColor]. func (r *RGBColor) DeepCopy() *RGBColor { if r == nil { return nil @@ -1899,21 +1907,21 @@ func (r *RGBColor) DeepCopy() *RGBColor { // Password represents a password. // This has no validations and is mainly used as a marker for UI components. // -// swagger:strfmt password +// swagger:strfmt password. type Password string -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (r Password) MarshalText() ([]byte, error) { return []byte(string(r)), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (r *Password) UnmarshalText(data []byte) error { // validation is performed later on *r = Password(string(data)) return nil } -// Scan read a value from a database driver +// Scan read a value from a database driver. func (r *Password) Scan(raw any) error { switch v := raw.(type) { case []byte: @@ -1927,7 +1935,7 @@ func (r *Password) Scan(raw any) error { return nil } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (r Password) Value() (driver.Value, error) { return driver.Value(string(r)), nil } @@ -1936,12 +1944,12 @@ func (r Password) String() string { return string(r) } -// MarshalJSON returns the Password as JSON +// MarshalJSON returns the Password as JSON. func (r Password) MarshalJSON() ([]byte, error) { return json.Marshal(string(r)) } -// UnmarshalJSON sets the Password from JSON +// UnmarshalJSON sets the Password from JSON. func (r *Password) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -1986,7 +1994,7 @@ func isIPv6(str string) bool { return ip != nil && strings.Contains(str, ":") } -// isCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6) +// isCIDR checks if the string is a valid CIDR notation (IPV4 & IPV6). func isCIDR(str string) bool { _, _, err := net.ParseCIDR(str) return err == nil @@ -1999,7 +2007,7 @@ func isCIDR(str string) bool { // 01-23-45-67-89-ab // 01-23-45-67-89-ab-cd-ef // 0123.4567.89ab -// 0123.4567.89ab.cdef +// 0123.4567.89ab.cdef. func isMAC(str string) bool { _, err := net.ParseMAC(str) return err == nil @@ -2084,7 +2092,7 @@ func isCreditCard(str string) bool { return (sum+lastDigit)%decimalBase == 0 } -// isSSN will validate the given string as a U.S. Social Security Number +// isSSN will validate the given string as a U.S. Social Security Number. func isSSN(str string) bool { if str == "" || len(str) != 11 { return false diff --git a/vendor/github.com/go-openapi/strfmt/doc.go b/vendor/github.com/go-openapi/strfmt/doc.go index 5825b721..6652521c 100644 --- a/vendor/github.com/go-openapi/strfmt/doc.go +++ b/vendor/github.com/go-openapi/strfmt/doc.go @@ -1,7 +1,5 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 -// Package strfmt contains custom string formats -// -// TODO: add info on how to define and register a custom format +// Package strfmt contains custom string formats. package strfmt diff --git a/vendor/github.com/go-openapi/strfmt/duration.go b/vendor/github.com/go-openapi/strfmt/duration.go index 908c1b02..229aa75e 100644 --- a/vendor/github.com/go-openapi/strfmt/duration.go +++ b/vendor/github.com/go-openapi/strfmt/duration.go @@ -14,9 +14,8 @@ import ( "time" ) -func init() { +func init() { //nolint:gochecknoinits // registers duration format in the default registry d := Duration(0) - // register this format in the default registry Default.Add("duration", &d, IsDuration) } @@ -25,6 +24,7 @@ const ( daysInWeek = 7 ) +//nolint:gochecknoglobals // package-level lookup tables for duration parsing var ( timeUnits = [][]string{ {"ns", "nano"}, @@ -51,7 +51,7 @@ var ( durationMatcher = regexp.MustCompile(`^(((?:-\s?)?\d+)(\.\d+)?\s*([A-Za-zµ]+))`) ) -// IsDuration returns true if the provided string is a valid duration +// IsDuration returns true if the provided string is a valid duration. func IsDuration(str string) bool { _, err := ParseDuration(str) return err == nil @@ -60,17 +60,17 @@ func IsDuration(str string) bool { // Duration represents a duration // // Duration stores a period of time as a nanosecond count, with the largest -// repesentable duration being approximately 290 years. +// representable duration being approximately 290 years. // -// swagger:strfmt duration +// swagger:[strfmt] duration. type Duration time.Duration -// MarshalText turns this instance into text +// MarshalText turns this instance into text. func (d Duration) MarshalText() ([]byte, error) { return []byte(time.Duration(d).String()), nil } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (d *Duration) UnmarshalText(data []byte) error { // validation is performed later on dd, err := ParseDuration(string(data)) if err != nil { @@ -80,7 +80,7 @@ func (d *Duration) UnmarshalText(data []byte) error { // validation is performed return nil } -// ParseDuration parses a duration from a string, compatible with scala duration syntax +// ParseDuration parses a duration from a string, compatible with scala duration syntax. func ParseDuration(cand string) (time.Duration, error) { if dur, err := time.ParseDuration(cand); err == nil { return dur, nil @@ -143,7 +143,7 @@ func ParseDuration(cand string) (time.Duration, error) { // Scan reads a Duration value from database driver type. func (d *Duration) Scan(raw any) error { switch v := raw.(type) { - // TODO: case []byte: // ? + // Proposal for enhancement: case []byte: // ? case int64: *d = Duration(v) case float64: @@ -162,17 +162,17 @@ func (d Duration) Value() (driver.Value, error) { return driver.Value(int64(d)), nil } -// String converts this duration to a string +// String converts this duration to a string. func (d Duration) String() string { return time.Duration(d).String() } -// MarshalJSON returns the Duration as JSON +// MarshalJSON returns the Duration as JSON. func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(time.Duration(d).String()) } -// UnmarshalJSON sets the Duration from JSON +// UnmarshalJSON sets the Duration from JSON. func (d *Duration) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil diff --git a/vendor/github.com/go-openapi/strfmt/errors.go b/vendor/github.com/go-openapi/strfmt/errors.go index 9faa37cf..5ed519d2 100644 --- a/vendor/github.com/go-openapi/strfmt/errors.go +++ b/vendor/github.com/go-openapi/strfmt/errors.go @@ -5,7 +5,7 @@ package strfmt type strfmtError string -// ErrFormat is an error raised by the strfmt package +// ErrFormat is an error raised by the [strfmt] package. const ErrFormat strfmtError = "format error" func (e strfmtError) Error() string { diff --git a/vendor/github.com/go-openapi/strfmt/format.go b/vendor/github.com/go-openapi/strfmt/format.go index d9d9e04c..e494dd7b 100644 --- a/vendor/github.com/go-openapi/strfmt/format.go +++ b/vendor/github.com/go-openapi/strfmt/format.go @@ -16,20 +16,20 @@ import ( "github.com/go-viper/mapstructure/v2" ) -// Default is the default formats registry -var Default = NewSeededFormats(nil, nil) +// Default is the default formats registry. +var Default = NewSeededFormats(nil, nil) //nolint:gochecknoglobals // package-level default registry, by design // Validator represents a validator for a string format. type Validator func(string) bool -// NewFormats creates a new formats registry seeded with the values from the default -func NewFormats() Registry { +// NewFormats creates a new formats registry seeded with the values from the default. +func NewFormats() Registry { //nolint:ireturn // factory function returns the Registry interface by design //nolint:forcetypeassert return NewSeededFormats(Default.(*defaultFormats).data, nil) } -// NewSeededFormats creates a new formats registry -func NewSeededFormats(seeds []knownFormat, normalizer NameNormalizer) Registry { +// NewSeededFormats creates a new formats registry. +func NewSeededFormats(seeds []knownFormat, normalizer NameNormalizer) Registry { //nolint:ireturn // factory function returns the Registry interface by design if normalizer == nil { normalizer = DefaultNameNormalizer } @@ -50,7 +50,7 @@ type knownFormat struct { // NameNormalizer is a function that normalizes a format name. type NameNormalizer func(string) string -// DefaultNameNormalizer removes all dashes +// DefaultNameNormalizer removes all dashes. func DefaultNameNormalizer(name string) string { return strings.ReplaceAll(name, "-", "") } @@ -62,8 +62,8 @@ type defaultFormats struct { normalizeName NameNormalizer } -// MapStructureHookFunc is a decode hook function for mapstructure -func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { +// MapStructureHookFunc is a decode hook function for mapstructure. +func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { //nolint:ireturn // returns interface required by mapstructure return func(from reflect.Type, to reflect.Type, obj any) (any, error) { if from.Kind() != reflect.String { return obj, nil @@ -76,83 +76,87 @@ func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { for _, v := range f.data { tpe, _ := f.GetType(v.Name) if to == tpe { - switch v.Name { - case "date": - d, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) - if err != nil { - return nil, err - } - return Date(d), nil - case "datetime": - input := data - if len(input) == 0 { - return nil, fmt.Errorf("empty string is an invalid datetime format: %w", ErrFormat) - } - return ParseDateTime(input) - case "duration": - dur, err := ParseDuration(data) - if err != nil { - return nil, err - } - return Duration(dur), nil - case "uri": - return URI(data), nil - case "email": - return Email(data), nil - case "uuid": - return UUID(data), nil - case "uuid3": - return UUID3(data), nil - case "uuid4": - return UUID4(data), nil - case "uuid5": - return UUID5(data), nil - case "uuid7": - return UUID7(data), nil - case "hostname": - return Hostname(data), nil - case "ipv4": - return IPv4(data), nil - case "ipv6": - return IPv6(data), nil - case "cidr": - return CIDR(data), nil - case "mac": - return MAC(data), nil - case "isbn": - return ISBN(data), nil - case "isbn10": - return ISBN10(data), nil - case "isbn13": - return ISBN13(data), nil - case "creditcard": - return CreditCard(data), nil - case "ssn": - return SSN(data), nil - case "hexcolor": - return HexColor(data), nil - case "rgbcolor": - return RGBColor(data), nil - case "byte": - return Base64(data), nil - case "password": - return Password(data), nil - case "ulid": - ulid, err := ParseULID(data) - if err != nil { - return nil, err - } - return ulid, nil - default: - return nil, errors.InvalidTypeName(v.Name) - } + return decodeFormatFromString(v.Name, data) } } return data, nil } } -// Add adds a new format, return true if this was a new item instead of a replacement +// decodeFormatFromString decodes a string into the appropriate format type by name. +func decodeFormatFromString(name, data string) (any, error) { //nolint:gocyclo,cyclop // flat switch over format names, no real complexity + switch name { + case "date": + d, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) + if err != nil { + return nil, err + } + return Date(d), nil + case "datetime": + if len(data) == 0 { + return nil, fmt.Errorf("empty string is an invalid datetime format: %w", ErrFormat) + } + return ParseDateTime(data) + case "duration": + dur, err := ParseDuration(data) + if err != nil { + return nil, err + } + return Duration(dur), nil + case "uri": + return URI(data), nil + case "email": + return Email(data), nil + case "uuid": + return UUID(data), nil + case "uuid3": + return UUID3(data), nil + case "uuid4": + return UUID4(data), nil + case "uuid5": + return UUID5(data), nil + case "uuid7": + return UUID7(data), nil + case "hostname": + return Hostname(data), nil + case "ipv4": + return IPv4(data), nil + case "ipv6": + return IPv6(data), nil + case "cidr": + return CIDR(data), nil + case "mac": + return MAC(data), nil + case "isbn": + return ISBN(data), nil + case "isbn10": + return ISBN10(data), nil + case "isbn13": + return ISBN13(data), nil + case "creditcard": + return CreditCard(data), nil + case "ssn": + return SSN(data), nil + case "hexcolor": + return HexColor(data), nil + case "rgbcolor": + return RGBColor(data), nil + case "byte": + return Base64(data), nil + case "password": + return Password(data), nil + case "ulid": + ulid, err := ParseULID(data) + if err != nil { + return nil, err + } + return ulid, nil + default: + return nil, errors.InvalidTypeName(name) + } +} + +// Add adds a new format, return true if this was a new item instead of a replacement. func (f *defaultFormats) Add(name string, strfmt Format, validator Validator) bool { f.Lock() defer f.Unlock() @@ -178,7 +182,7 @@ func (f *defaultFormats) Add(name string, strfmt Format, validator Validator) bo return true } -// GetType gets the type for the specified name +// GetType gets the type for the specified name. func (f *defaultFormats) GetType(name string) (reflect.Type, bool) { f.Lock() defer f.Unlock() @@ -191,7 +195,7 @@ func (f *defaultFormats) GetType(name string) (reflect.Type, bool) { return nil, false } -// DelByName removes the format by the specified name, returns true when an item was actually removed +// DelByName removes the format by the specified name, returns true when an item was actually removed. func (f *defaultFormats) DelByName(name string) bool { f.Lock() defer f.Unlock() @@ -208,7 +212,7 @@ func (f *defaultFormats) DelByName(name string) bool { return false } -// DelByFormat removes the specified format, returns true when an item was actually removed +// DelByFormat removes the specified format, returns true when an item was actually removed. func (f *defaultFormats) DelByFormat(strfmt Format) bool { f.Lock() defer f.Unlock() @@ -228,7 +232,7 @@ func (f *defaultFormats) DelByFormat(strfmt Format) bool { return false } -// ContainsName returns true if this registry contains the specified name +// ContainsName returns true if this registry contains the specified name. func (f *defaultFormats) ContainsName(name string) bool { f.Lock() defer f.Unlock() @@ -241,7 +245,7 @@ func (f *defaultFormats) ContainsName(name string) bool { return false } -// ContainsFormat returns true if this registry contains the specified format +// ContainsFormat returns true if this registry contains the specified format. func (f *defaultFormats) ContainsFormat(strfmt Format) bool { f.Lock() defer f.Unlock() diff --git a/vendor/github.com/go-openapi/strfmt/go.work b/vendor/github.com/go-openapi/strfmt/go.work new file mode 100644 index 00000000..288e7655 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/go.work @@ -0,0 +1,7 @@ +use ( + . + ./enable/mongodb + ./internal/testintegration +) + +go 1.24.0 diff --git a/vendor/github.com/go-openapi/strfmt/go.work.sum b/vendor/github.com/go-openapi/strfmt/go.work.sum new file mode 100644 index 00000000..33dac969 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/go.work.sum @@ -0,0 +1,16 @@ +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30 h1:BHT1/DKsYDGkUgQ2jmMaozVcdk+sVfz0+1ZJq4zkWgw= +github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= +github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= +golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= +golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= +golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/vendor/github.com/go-openapi/strfmt/ifaces.go b/vendor/github.com/go-openapi/strfmt/ifaces.go index 1b9e72c6..6252ae98 100644 --- a/vendor/github.com/go-openapi/strfmt/ifaces.go +++ b/vendor/github.com/go-openapi/strfmt/ifaces.go @@ -13,7 +13,7 @@ import ( // Format represents a string format. // // All implementations of Format provide a string representation and text -// marshaling/unmarshaling interface to be used by encoders (e.g. encoding/json). +// marshaling/unmarshaling interface to be used by encoders (e.g. encoding/[json]). type Format interface { String() string encoding.TextMarshaler @@ -22,11 +22,11 @@ type Format interface { // Registry is a registry of string formats, with a validation method. type Registry interface { - Add(string, Format, Validator) bool - DelByName(string) bool - GetType(string) (reflect.Type, bool) - ContainsName(string) bool - Validates(string, string) bool - Parse(string, string) (any, error) + Add(name string, strfmt Format, validator Validator) bool + DelByName(name string) bool + GetType(name string) (reflect.Type, bool) + ContainsName(name string) bool + Validates(name, data string) bool + Parse(name, data string) (any, error) MapStructureHookFunc() mapstructure.DecodeHookFunc } diff --git a/vendor/github.com/go-openapi/strfmt/internal/bsonlite/codec.go b/vendor/github.com/go-openapi/strfmt/internal/bsonlite/codec.go new file mode 100644 index 00000000..424f4546 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/internal/bsonlite/codec.go @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package bsonlite provides a minimal BSON codec for strfmt types. +// +// This codec produces BSON output compatible with go.mongodb.org/mongo-driver/v2 +// (v2.5.0). It handles only the exact BSON patterns used by strfmt: +// single-key {"data": value} documents with string, DateTime, or ObjectID values. +// +// This package is intended to provide a backward-compatible API to users of +// go-openapi/strfmt. It is not intended to be maintained or to follow the +// evolutions of the official MongoDB drivers. For up-to-date MongoDB support, +// import "github.com/go-openapi/strfmt/enable/mongodb" to replace this codec +// with one backed by the real driver. +package bsonlite + +import "time" + +// Codec provides BSON document marshal/unmarshal for strfmt types. +// +// MarshalDoc encodes a single-key BSON document {"data": value}. +// The value must be one of: string, time.Time, or [12]byte (ObjectID). +// +// UnmarshalDoc decodes a BSON document and returns the "data" field's value. +// Returns one of: string, time.Time, or [12]byte depending on the BSON type. +type Codec interface { + MarshalDoc(value any) ([]byte, error) + UnmarshalDoc(data []byte) (any, error) +} + +// C is the active BSON codec. +// +//nolint:gochecknoglobals // replaceable codec, by design +var C Codec = liteCodec{} + +// Replace swaps the active BSON codec with the provided implementation. +// This is intended to be called from enable/mongodb's init(). +// +// Since [Replace] affects the global state of the package, it is not intended for concurrent use. +func Replace(c Codec) { + C = c +} + +// BSON type tags (from the BSON specification). +const ( + TypeString byte = 0x02 + TypeObjectID byte = 0x07 + TypeDateTime byte = 0x09 + TypeNull byte = 0x0A +) + +// ObjectIDSize is the size of a BSON ObjectID in bytes. +const ObjectIDSize = 12 + +// DateTimeToMillis converts a time.Time to BSON DateTime milliseconds. +func DateTimeToMillis(t time.Time) int64 { + const ( + millisec = 1000 + microsec = 1_000_000 + ) + return t.Unix()*millisec + int64(t.Nanosecond())/microsec +} + +// MillisToTime converts BSON DateTime milliseconds to time.Time. +func MillisToTime(millis int64) time.Time { + const ( + millisec = 1000 + nanosPerMs = 1_000_000 + ) + return time.Unix(millis/millisec, millis%millisec*nanosPerMs) +} diff --git a/vendor/github.com/go-openapi/strfmt/internal/bsonlite/lite.go b/vendor/github.com/go-openapi/strfmt/internal/bsonlite/lite.go new file mode 100644 index 00000000..6b0e0e1c --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/internal/bsonlite/lite.go @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package bsonlite + +import ( + "encoding/binary" + "errors" + "fmt" + "time" +) + +// liteCodec is a minimal BSON codec that handles only the patterns used by strfmt: +// single-key documents of the form {"data": } where value is a string, +// BSON DateTime (time.Time), or BSON ObjectID ([12]byte). +type liteCodec struct{} + +var _ Codec = liteCodec{} + +func (liteCodec) MarshalDoc(value any) ([]byte, error) { + switch v := value.(type) { + case string: + return marshalStringDoc(v), nil + case time.Time: + return marshalDateTimeDoc(v), nil + case [ObjectIDSize]byte: + return marshalObjectIDDoc(v), nil + default: + return nil, fmt.Errorf("bsonlite: unsupported value type %T: %w", value, errUnsupportedType) + } +} + +func (liteCodec) UnmarshalDoc(data []byte) (any, error) { + return unmarshalDoc(data) +} + +// BSON wire format helpers. +// +// Document: int32(size) + elements + 0x00 +// Element: byte(type) + cstring(key) + value +// String: int32(len+1) + bytes + 0x00 +// DateTime: int64 (LE, millis since epoch) +// ObjectID: [12]byte + +const dataKey = "data\x00" + +func marshalStringDoc(s string) []byte { + sBytes := []byte(s) + // doc_size(4) + type(1) + key("data\0"=5) + strlen(4) + string + \0(1) + doc_term(1) + docSize := 4 + 1 + len(dataKey) + 4 + len(sBytes) + 1 + 1 + + buf := make([]byte, docSize) + pos := 0 + + binary.LittleEndian.PutUint32(buf[pos:], uint32(docSize)) //nolint:gosec // size is computed from input, cannot overflow + pos += 4 + + buf[pos] = TypeString + pos++ + + pos += copy(buf[pos:], dataKey) + + binary.LittleEndian.PutUint32(buf[pos:], uint32(len(sBytes)+1)) //nolint:gosec // string length cannot overflow uint32 + pos += 4 + + pos += copy(buf[pos:], sBytes) + buf[pos] = 0 // string null terminator + pos++ + + buf[pos] = 0 // document terminator + + return buf +} + +func marshalDateTimeDoc(t time.Time) []byte { + // doc_size(4) + type(1) + key("data\0"=5) + int64(8) + doc_term(1) + const docSize = 4 + 1 + 5 + 8 + 1 + + buf := make([]byte, docSize) + pos := 0 + + binary.LittleEndian.PutUint32(buf[pos:], docSize) + pos += 4 + + buf[pos] = TypeDateTime + pos++ + + pos += copy(buf[pos:], dataKey) + + millis := DateTimeToMillis(t) + binary.LittleEndian.PutUint64(buf[pos:], uint64(millis)) //nolint:gosec // negative datetime millis are valid + // pos += 8 + + buf[docSize-1] = 0 // document terminator + + return buf +} + +func marshalObjectIDDoc(oid [ObjectIDSize]byte) []byte { + // doc_size(4) + type(1) + key("data\0"=5) + objectid(12) + doc_term(1) + const docSize = 4 + 1 + 5 + ObjectIDSize + 1 + + buf := make([]byte, docSize) + pos := 0 + + binary.LittleEndian.PutUint32(buf[pos:], docSize) + pos += 4 + + buf[pos] = TypeObjectID + pos++ + + pos += copy(buf[pos:], dataKey) + + copy(buf[pos:], oid[:]) + // pos += ObjectIDSize + + buf[docSize-1] = 0 // document terminator + + return buf +} + +var ( + errUnsupportedType = errors.New("bsonlite: unsupported type") + errDocTooShort = errors.New("bsonlite: document too short") + errDocSize = errors.New("bsonlite: document size mismatch") + errNoTerminator = errors.New("bsonlite: missing key terminator") + errTruncated = errors.New("bsonlite: truncated value") + errDataNotFound = errors.New("bsonlite: \"data\" field not found") +) + +func unmarshalDoc(raw []byte) (any, error) { + const minDocSize = 5 // int32(size) + terminator + + if len(raw) < minDocSize { + return nil, errDocTooShort + } + + docSize := int(binary.LittleEndian.Uint32(raw[:4])) + if docSize != len(raw) { + return nil, errDocSize + } + + pos := 4 + + for pos < docSize-1 { + if pos >= len(raw) { + return nil, errTruncated + } + typeByte := raw[pos] + pos++ + + // Read key (cstring: bytes until 0x00). + keyStart := pos + for pos < len(raw) && raw[pos] != 0 { + pos++ + } + if pos >= len(raw) { + return nil, errNoTerminator + } + key := string(raw[keyStart:pos]) + pos++ // skip null terminator + + val, newPos, err := readValue(typeByte, raw, pos) + if err != nil { + return nil, err + } + pos = newPos + + if key == "data" { + return val, nil + } + } + + return nil, errDataNotFound +} + +func readValue(typeByte byte, raw []byte, pos int) (any, int, error) { + switch typeByte { + case TypeString: + if pos+4 > len(raw) { + return nil, 0, errTruncated + } + strLen := int(binary.LittleEndian.Uint32(raw[pos:])) + pos += 4 + if pos+strLen > len(raw) || strLen < 1 { + return nil, 0, errTruncated + } + s := string(raw[pos : pos+strLen-1]) // exclude null terminator + return s, pos + strLen, nil + + case TypeObjectID: + if pos+ObjectIDSize > len(raw) { + return nil, 0, errTruncated + } + var oid [ObjectIDSize]byte + copy(oid[:], raw[pos:pos+ObjectIDSize]) + return oid, pos + ObjectIDSize, nil + + case TypeDateTime: + const dateTimeSize = 8 + if pos+dateTimeSize > len(raw) { + return nil, 0, errTruncated + } + millis := int64(binary.LittleEndian.Uint64(raw[pos:])) //nolint:gosec // negative datetime millis are valid + return MillisToTime(millis), pos + dateTimeSize, nil + + case TypeNull: + return nil, pos, nil + + default: + return nil, 0, fmt.Errorf("bsonlite: unsupported BSON type 0x%02x: %w", typeByte, errUnsupportedType) + } +} diff --git a/vendor/github.com/go-openapi/strfmt/mongo.go b/vendor/github.com/go-openapi/strfmt/mongo.go index 641fed9b..be904ffa 100644 --- a/vendor/github.com/go-openapi/strfmt/mongo.go +++ b/vendor/github.com/go-openapi/strfmt/mongo.go @@ -9,70 +9,89 @@ import ( "fmt" "time" - "github.com/oklog/ulid" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/bsontype" - bsonprim "go.mongodb.org/mongo-driver/bson/primitive" + "github.com/go-openapi/strfmt/internal/bsonlite" + "github.com/oklog/ulid/v2" ) +// bsonMarshaler is satisfied by types implementing MarshalBSON. +type bsonMarshaler interface { + MarshalBSON() ([]byte, error) +} + +// bsonUnmarshaler is satisfied by types implementing UnmarshalBSON. +type bsonUnmarshaler interface { + UnmarshalBSON(data []byte) error +} + +// bsonValueMarshaler is satisfied by types implementing MarshalBSONValue. +type bsonValueMarshaler interface { + MarshalBSONValue() (byte, []byte, error) +} + +// bsonValueUnmarshaler is satisfied by types implementing UnmarshalBSONValue. +type bsonValueUnmarshaler interface { + UnmarshalBSONValue(tpe byte, data []byte) error +} + +// Compile-time interface checks. var ( - _ bson.Marshaler = Date{} - _ bson.Unmarshaler = &Date{} - _ bson.Marshaler = Base64{} - _ bson.Unmarshaler = &Base64{} - _ bson.Marshaler = Duration(0) - _ bson.Unmarshaler = (*Duration)(nil) - _ bson.Marshaler = DateTime{} - _ bson.Unmarshaler = &DateTime{} - _ bson.Marshaler = ULID{} - _ bson.Unmarshaler = &ULID{} - _ bson.Marshaler = URI("") - _ bson.Unmarshaler = (*URI)(nil) - _ bson.Marshaler = Email("") - _ bson.Unmarshaler = (*Email)(nil) - _ bson.Marshaler = Hostname("") - _ bson.Unmarshaler = (*Hostname)(nil) - _ bson.Marshaler = IPv4("") - _ bson.Unmarshaler = (*IPv4)(nil) - _ bson.Marshaler = IPv6("") - _ bson.Unmarshaler = (*IPv6)(nil) - _ bson.Marshaler = CIDR("") - _ bson.Unmarshaler = (*CIDR)(nil) - _ bson.Marshaler = MAC("") - _ bson.Unmarshaler = (*MAC)(nil) - _ bson.Marshaler = Password("") - _ bson.Unmarshaler = (*Password)(nil) - _ bson.Marshaler = UUID("") - _ bson.Unmarshaler = (*UUID)(nil) - _ bson.Marshaler = UUID3("") - _ bson.Unmarshaler = (*UUID3)(nil) - _ bson.Marshaler = UUID4("") - _ bson.Unmarshaler = (*UUID4)(nil) - _ bson.Marshaler = UUID5("") - _ bson.Unmarshaler = (*UUID5)(nil) - _ bson.Marshaler = UUID7("") - _ bson.Unmarshaler = (*UUID7)(nil) - _ bson.Marshaler = ISBN("") - _ bson.Unmarshaler = (*ISBN)(nil) - _ bson.Marshaler = ISBN10("") - _ bson.Unmarshaler = (*ISBN10)(nil) - _ bson.Marshaler = ISBN13("") - _ bson.Unmarshaler = (*ISBN13)(nil) - _ bson.Marshaler = CreditCard("") - _ bson.Unmarshaler = (*CreditCard)(nil) - _ bson.Marshaler = SSN("") - _ bson.Unmarshaler = (*SSN)(nil) - _ bson.Marshaler = HexColor("") - _ bson.Unmarshaler = (*HexColor)(nil) - _ bson.Marshaler = RGBColor("") - _ bson.Unmarshaler = (*RGBColor)(nil) - _ bson.Marshaler = ObjectId{} - _ bson.Unmarshaler = &ObjectId{} - - _ bson.ValueMarshaler = DateTime{} - _ bson.ValueUnmarshaler = &DateTime{} - _ bson.ValueMarshaler = ObjectId{} - _ bson.ValueUnmarshaler = &ObjectId{} + _ bsonMarshaler = Date{} + _ bsonUnmarshaler = &Date{} + _ bsonMarshaler = Base64{} + _ bsonUnmarshaler = &Base64{} + _ bsonMarshaler = Duration(0) + _ bsonUnmarshaler = (*Duration)(nil) + _ bsonMarshaler = DateTime{} + _ bsonUnmarshaler = &DateTime{} + _ bsonMarshaler = ULID{} + _ bsonUnmarshaler = &ULID{} + _ bsonMarshaler = URI("") + _ bsonUnmarshaler = (*URI)(nil) + _ bsonMarshaler = Email("") + _ bsonUnmarshaler = (*Email)(nil) + _ bsonMarshaler = Hostname("") + _ bsonUnmarshaler = (*Hostname)(nil) + _ bsonMarshaler = IPv4("") + _ bsonUnmarshaler = (*IPv4)(nil) + _ bsonMarshaler = IPv6("") + _ bsonUnmarshaler = (*IPv6)(nil) + _ bsonMarshaler = CIDR("") + _ bsonUnmarshaler = (*CIDR)(nil) + _ bsonMarshaler = MAC("") + _ bsonUnmarshaler = (*MAC)(nil) + _ bsonMarshaler = Password("") + _ bsonUnmarshaler = (*Password)(nil) + _ bsonMarshaler = UUID("") + _ bsonUnmarshaler = (*UUID)(nil) + _ bsonMarshaler = UUID3("") + _ bsonUnmarshaler = (*UUID3)(nil) + _ bsonMarshaler = UUID4("") + _ bsonUnmarshaler = (*UUID4)(nil) + _ bsonMarshaler = UUID5("") + _ bsonUnmarshaler = (*UUID5)(nil) + _ bsonMarshaler = UUID7("") + _ bsonUnmarshaler = (*UUID7)(nil) + _ bsonMarshaler = ISBN("") + _ bsonUnmarshaler = (*ISBN)(nil) + _ bsonMarshaler = ISBN10("") + _ bsonUnmarshaler = (*ISBN10)(nil) + _ bsonMarshaler = ISBN13("") + _ bsonUnmarshaler = (*ISBN13)(nil) + _ bsonMarshaler = CreditCard("") + _ bsonUnmarshaler = (*CreditCard)(nil) + _ bsonMarshaler = SSN("") + _ bsonUnmarshaler = (*SSN)(nil) + _ bsonMarshaler = HexColor("") + _ bsonUnmarshaler = (*HexColor)(nil) + _ bsonMarshaler = RGBColor("") + _ bsonUnmarshaler = (*RGBColor)(nil) + _ bsonMarshaler = ObjectId{} + _ bsonUnmarshaler = &ObjectId{} + + _ bsonValueMarshaler = DateTime{} + _ bsonValueUnmarshaler = &DateTime{} + _ bsonValueMarshaler = ObjectId{} + _ bsonValueUnmarshaler = &ObjectId{} ) const ( @@ -82,99 +101,105 @@ const ( ) func (d Date) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": d.String()}) + return bsonlite.C.MarshalDoc(d.String()) } func (d *Date) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + v, err := bsonlite.C.UnmarshalDoc(data) + if err != nil { return err } - if data, ok := m["data"].(string); ok { - rd, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) - if err != nil { - return err - } - *d = Date(rd) - return nil + s, ok := v.(string) + if !ok { + return fmt.Errorf("couldn't unmarshal bson bytes value as Date: %w", ErrFormat) } - return fmt.Errorf("couldn't unmarshal bson bytes value as Date: %w", ErrFormat) + rd, err := time.ParseInLocation(RFC3339FullDate, s, DefaultTimeLocation) + if err != nil { + return err + } + *d = Date(rd) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (b Base64) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": b.String()}) + return bsonlite.C.MarshalDoc(b.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (b *Base64) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + v, err := bsonlite.C.UnmarshalDoc(data) + if err != nil { return err } - if bd, ok := m["data"].(string); ok { - vb, err := base64.StdEncoding.DecodeString(bd) - if err != nil { - return err - } - *b = Base64(vb) - return nil + s, ok := v.(string) + if !ok { + return fmt.Errorf("couldn't unmarshal bson bytes as base64: %w", ErrFormat) + } + + vb, err := base64.StdEncoding.DecodeString(s) + if err != nil { + return err } - return fmt.Errorf("couldn't unmarshal bson bytes as base64: %w", ErrFormat) + *b = Base64(vb) + return nil } func (d Duration) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": d.String()}) + return bsonlite.C.MarshalDoc(d.String()) } func (d *Duration) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + v, err := bsonlite.C.UnmarshalDoc(data) + if err != nil { return err } - if data, ok := m["data"].(string); ok { - rd, err := ParseDuration(data) - if err != nil { - return err - } - *d = Duration(rd) - return nil + s, ok := v.(string) + if !ok { + return fmt.Errorf("couldn't unmarshal bson bytes value as Duration: %w", ErrFormat) } - return fmt.Errorf("couldn't unmarshal bson bytes value as Date: %w", ErrFormat) + rd, err := ParseDuration(s) + if err != nil { + return err + } + *d = Duration(rd) + return nil } -// MarshalBSON renders the DateTime as a BSON document +// MarshalBSON renders the [DateTime] as a BSON document. func (t DateTime) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": t}) + tNorm := NormalizeTimeForMarshal(time.Time(t)) + return bsonlite.C.MarshalDoc(tNorm) } -// UnmarshalBSON reads the DateTime from a BSON document +// UnmarshalBSON reads the [DateTime] from a BSON document. func (t *DateTime) UnmarshalBSON(data []byte) error { - var obj struct { - Data DateTime - } - - if err := bson.Unmarshal(data, &obj); err != nil { + v, err := bsonlite.C.UnmarshalDoc(data) + if err != nil { return err } - *t = obj.Data - + tv, ok := v.(time.Time) + if !ok { + return fmt.Errorf("couldn't unmarshal bson bytes value as DateTime: %w", ErrFormat) + } + *t = DateTime(tv) return nil } +// MarshalBSONValue marshals a [DateTime] as a BSON DateTime value (type 0x09), +// an int64 representing milliseconds since epoch. +// // MarshalBSONValue 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. +// into a BSON document represented as bytes. // -// Marshals a DateTime as a bson.TypeDateTime, an int64 representing -// milliseconds since epoch. -func (t DateTime) MarshalBSONValue() (bsontype.Type, []byte, error) { +// The bytes returned must be a valid BSON document if the error is nil. +func (t DateTime) MarshalBSONValue() (byte, []byte, error) { // UnixNano cannot be used directly, the result of calling UnixNano on the zero // Time is undefined. Thats why we use time.Nanosecond() instead. @@ -183,15 +208,12 @@ func (t DateTime) MarshalBSONValue() (bsontype.Type, []byte, error) { buf := make([]byte, bsonDateTimeSize) binary.LittleEndian.PutUint64(buf, uint64(i64)) //nolint:gosec // it's okay to handle negative int64 this way - return bson.TypeDateTime, buf, nil + return bsonlite.TypeDateTime, buf, nil } -// UnmarshalBSONValue is an interface implemented by types that can unmarshal a -// BSON value representation 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. -func (t *DateTime) UnmarshalBSONValue(tpe bsontype.Type, data []byte) error { - if tpe == bson.TypeNull { +// UnmarshalBSONValue unmarshals a BSON DateTime value into this [DateTime]. +func (t *DateTime) UnmarshalBSONValue(tpe byte, data []byte) error { + if tpe == bsonlite.TypeNull { *t = DateTime{} return nil } @@ -206,440 +228,373 @@ func (t *DateTime) UnmarshalBSONValue(tpe bsontype.Type, data []byte) error { return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u ULID) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *ULID) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + v, err := bsonlite.C.UnmarshalDoc(data) + if err != nil { return err } - if ud, ok := m["data"].(string); ok { - id, err := ulid.ParseStrict(ud) - if err != nil { - return fmt.Errorf("couldn't parse bson bytes as ULID: %w: %w", err, ErrFormat) - } - u.ULID = id - return nil + s, ok := v.(string) + if !ok { + return fmt.Errorf("couldn't unmarshal bson bytes as ULID: %w", ErrFormat) } - return fmt.Errorf("couldn't unmarshal bson bytes as ULID: %w", ErrFormat) + + id, err := ulid.ParseStrict(s) + if err != nil { + return fmt.Errorf("couldn't parse bson bytes as ULID: %w: %w", err, ErrFormat) + } + u.ULID = id + return nil } -// MarshalBSON document from this value +// unmarshalBSONString is a helper for string-based strfmt types. +func unmarshalBSONString(data []byte, typeName string) (string, error) { + v, err := bsonlite.C.UnmarshalDoc(data) + if err != nil { + return "", err + } + s, ok := v.(string) + if !ok { + return "", fmt.Errorf("couldn't unmarshal bson bytes as %s: %w", typeName, ErrFormat) + } + return s, nil +} + +// MarshalBSON document from this value. func (u URI) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *URI) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "uri") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = URI(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as uri: %w", ErrFormat) + *u = URI(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (e Email) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": e.String()}) + return bsonlite.C.MarshalDoc(e.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (e *Email) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "email") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *e = Email(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as email: %w", ErrFormat) + *e = Email(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (h Hostname) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": h.String()}) + return bsonlite.C.MarshalDoc(h.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (h *Hostname) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "hostname") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *h = Hostname(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as hostname: %w", ErrFormat) + *h = Hostname(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u IPv4) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *IPv4) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "ipv4") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = IPv4(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ipv4: %w", ErrFormat) + *u = IPv4(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u IPv6) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *IPv6) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "ipv6") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = IPv6(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ipv6: %w", ErrFormat) + *u = IPv6(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u CIDR) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *CIDR) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "CIDR") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = CIDR(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as CIDR: %w", ErrFormat) + *u = CIDR(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u MAC) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *MAC) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "MAC") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = MAC(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as MAC: %w", ErrFormat) + *u = MAC(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (r Password) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": r.String()}) + return bsonlite.C.MarshalDoc(r.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (r *Password) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "Password") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *r = Password(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as Password: %w", ErrFormat) + *r = Password(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u UUID) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *UUID) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "UUID") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = UUID(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID: %w", ErrFormat) + *u = UUID(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u UUID3) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *UUID3) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "UUID3") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = UUID3(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID3: %w", ErrFormat) + *u = UUID3(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u UUID4) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *UUID4) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "UUID4") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = UUID4(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID4: %w", ErrFormat) + *u = UUID4(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u UUID5) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *UUID5) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "UUID5") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = UUID5(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID5: %w", ErrFormat) + *u = UUID5(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u UUID7) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *UUID7) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "UUID7") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = UUID7(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID7: %w", ErrFormat) + *u = UUID7(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u ISBN) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *ISBN) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "ISBN") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = ISBN(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ISBN: %w", ErrFormat) + *u = ISBN(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u ISBN10) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *ISBN10) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "ISBN10") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = ISBN10(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ISBN10: %w", ErrFormat) + *u = ISBN10(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u ISBN13) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *ISBN13) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "ISBN13") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = ISBN13(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ISBN13: %w", ErrFormat) + *u = ISBN13(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u CreditCard) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *CreditCard) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "CreditCard") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = CreditCard(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as CreditCard: %w", ErrFormat) + *u = CreditCard(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (u SSN) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) + return bsonlite.C.MarshalDoc(u.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (u *SSN) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "SSN") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *u = SSN(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as SSN: %w", ErrFormat) + *u = SSN(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (h HexColor) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": h.String()}) + return bsonlite.C.MarshalDoc(h.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (h *HexColor) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "HexColor") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *h = HexColor(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as HexColor: %w", ErrFormat) + *h = HexColor(s) + return nil } -// MarshalBSON document from this value +// MarshalBSON document from this value. func (r RGBColor) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": r.String()}) + return bsonlite.C.MarshalDoc(r.String()) } -// UnmarshalBSON document into this value +// UnmarshalBSON document into this value. func (r *RGBColor) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { + s, err := unmarshalBSONString(data, "RGBColor") + if err != nil { return err } - - if ud, ok := m["data"].(string); ok { - *r = RGBColor(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as RGBColor: %w", ErrFormat) + *r = RGBColor(s) + return nil } -// MarshalBSON renders the object id as a BSON document +// MarshalBSON renders the object id as a BSON document. func (id ObjectId) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": bsonprim.ObjectID(id)}) + return bsonlite.C.MarshalDoc([12]byte(id)) } -// UnmarshalBSON reads the objectId from a BSON document +// UnmarshalBSON reads the objectId from a BSON document. func (id *ObjectId) UnmarshalBSON(data []byte) error { - var obj struct { - Data bsonprim.ObjectID - } - if err := bson.Unmarshal(data, &obj); err != nil { + v, err := bsonlite.C.UnmarshalDoc(data) + if err != nil { return err } - *id = ObjectId(obj.Data) + + oid, ok := v.([12]byte) + if !ok { + return fmt.Errorf("couldn't unmarshal bson bytes as ObjectId: %w", ErrFormat) + } + *id = ObjectId(oid) return nil } -// MarshalBSONValue 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. -func (id ObjectId) MarshalBSONValue() (bsontype.Type, []byte, error) { - oid := bsonprim.ObjectID(id) - return bson.TypeObjectID, oid[:], nil -} - -// UnmarshalBSONValue is an interface implemented by types that can unmarshal a -// BSON value representation 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. -func (id *ObjectId) UnmarshalBSONValue(_ bsontype.Type, data []byte) error { - var oid bsonprim.ObjectID +// MarshalBSONValue marshals the [ObjectId] as a raw BSON ObjectID value. +func (id ObjectId) MarshalBSONValue() (byte, []byte, error) { + oid := [12]byte(id) + return bsonlite.TypeObjectID, oid[:], nil +} + +// UnmarshalBSONValue unmarshals a raw BSON ObjectID value into this [ObjectId]. +func (id *ObjectId) UnmarshalBSONValue(_ byte, data []byte) error { + var oid [12]byte copy(oid[:], data) *id = ObjectId(oid) return nil diff --git a/vendor/github.com/go-openapi/strfmt/time.go b/vendor/github.com/go-openapi/strfmt/time.go index 8085aaf6..c07ae049 100644 --- a/vendor/github.com/go-openapi/strfmt/time.go +++ b/vendor/github.com/go-openapi/strfmt/time.go @@ -12,14 +12,12 @@ import ( "time" ) -var ( - // UnixZero sets the zero unix UTC timestamp we want to compare against. - // - // Unix 0 for an EST timezone is not equivalent to a UTC timezone. - UnixZero = time.Unix(0, 0).UTC() -) +// UnixZero sets the zero unix UTC timestamp we want to compare against. +// +// Unix 0 for an EST timezone is not equivalent to a UTC timezone. +var UnixZero = time.Unix(0, 0).UTC() //nolint:gochecknoglobals // package-level sentinel value for unix epoch -func init() { +func init() { //nolint:gochecknoinits // registers datetime format in the default registry dt := DateTime{} Default.Add("datetime", &dt, IsDateTime) } @@ -50,38 +48,48 @@ func IsDateTime(str string) bool { } const ( - // RFC3339Millis represents a ISO8601 format to millis instead of to nanos + // RFC3339Millis represents a ISO8601 format to millis instead of to nanos. RFC3339Millis = "2006-01-02T15:04:05.000Z07:00" - // RFC3339MillisNoColon represents a ISO8601 format to millis instead of to nanos + // RFC3339MillisNoColon represents a ISO8601 format to millis instead of to nanos. RFC3339MillisNoColon = "2006-01-02T15:04:05.000Z0700" - // RFC3339Micro represents a ISO8601 format to micro instead of to nano + // RFC3339Micro represents a ISO8601 format to micro instead of to nano. RFC3339Micro = "2006-01-02T15:04:05.000000Z07:00" - // RFC3339MicroNoColon represents a ISO8601 format to micro instead of to nano + // RFC3339MicroNoColon represents a ISO8601 format to micro instead of to nano. RFC3339MicroNoColon = "2006-01-02T15:04:05.000000Z0700" - // ISO8601LocalTime represents a ISO8601 format to ISO8601 in local time (no timezone) + // ISO8601LocalTime represents a ISO8601 format to ISO8601 in local time (no timezone). ISO8601LocalTime = "2006-01-02T15:04:05" - // ISO8601TimeWithReducedPrecision represents a ISO8601 format with reduced precision (dropped secs) + // ISO8601TimeWithReducedPrecision represents a ISO8601 format with reduced precision (dropped secs). ISO8601TimeWithReducedPrecision = "2006-01-02T15:04Z" - // ISO8601TimeWithReducedPrecisionLocaltime represents a ISO8601 format with reduced precision and no timezone (dropped seconds + no timezone) + // ISO8601TimeWithReducedPrecisionLocaltime represents a ISO8601 format with reduced precision and no timezone (dropped seconds + no timezone). ISO8601TimeWithReducedPrecisionLocaltime = "2006-01-02T15:04" // ISO8601TimeUniversalSortableDateTimePattern represents a ISO8601 universal sortable date time pattern. ISO8601TimeUniversalSortableDateTimePattern = "2006-01-02 15:04:05" - // ISO8601TimeUniversalSortableDateTimePatternShortForm is the short form of ISO8601TimeUniversalSortableDateTimePattern + // ISO8601TimeUniversalSortableDateTimePatternShortForm is the short form of [ISO8601TimeUniversalSortableDateTimePattern]. ISO8601TimeUniversalSortableDateTimePatternShortForm = "2006-01-02" // DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6 DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$` ) +//nolint:gochecknoglobals // package-level configuration for datetime parsing and marshaling var ( rxDateTime = regexp.MustCompile(DateTimePattern) - // DateTimeFormats is the collection of formats used by ParseDateTime() - DateTimeFormats = []string{RFC3339Micro, RFC3339MicroNoColon, RFC3339Millis, RFC3339MillisNoColon, time.RFC3339, time.RFC3339Nano, ISO8601LocalTime, ISO8601TimeWithReducedPrecision, ISO8601TimeWithReducedPrecisionLocaltime, ISO8601TimeUniversalSortableDateTimePattern, ISO8601TimeUniversalSortableDateTimePatternShortForm} + // DateTimeFormats is the collection of formats used by [ParseDateTime](). + DateTimeFormats = []string{ + RFC3339Micro, RFC3339MicroNoColon, + RFC3339Millis, RFC3339MillisNoColon, + time.RFC3339, time.RFC3339Nano, + ISO8601LocalTime, + ISO8601TimeWithReducedPrecision, + ISO8601TimeWithReducedPrecisionLocaltime, + ISO8601TimeUniversalSortableDateTimePattern, + ISO8601TimeUniversalSortableDateTimePatternShortForm, + } - // MarshalFormat sets the time resolution format used for marshaling time (set to milliseconds) + // MarshalFormat sets the time resolution format used for marshaling time (set to milliseconds). MarshalFormat = RFC3339Millis - // NormalizeTimeForMarshal provides a normalization function on time before marshalling (e.g. time.UTC). + // NormalizeTimeForMarshal provides a normalization function on time before marshaling (e.g. [time.UTC]). // By default, the time value is not changed. NormalizeTimeForMarshal = func(t time.Time) time.Time { return t } @@ -89,7 +97,7 @@ var ( DefaultTimeLocation = time.UTC ) -// ParseDateTime parses a string that represents an ISO8601 time or a unix epoch +// ParseDateTime parses a string that represents an ISO8601 time or a unix epoch. func ParseDateTime(data string) (DateTime, error) { if data == "" { return NewDateTime(), nil @@ -111,47 +119,45 @@ func ParseDateTime(data string) (DateTime, error) { // It knows how to read 3 different variations of a RFC3339 date time. // Most APIs we encounter want either millisecond or second precision times. // This just tries to make it worry-free. -// -// swagger:strfmt date-time type DateTime time.Time // NewDateTime is a representation of the UNIX epoch (January 1, 1970 00:00:00 UTC) for the [DateTime] type. // // Notice that this is not the zero value of the [DateTime] type. // -// You may use [DateTime.IsUNIXZero] to check against this value. +// You may use [DateTime.IsUnixZero] to check against this value. func NewDateTime() DateTime { return DateTime(time.Unix(0, 0).UTC()) } // MakeDateTime is a representation of the zero value of the [DateTime] type (January 1, year 1, 00:00:00 UTC). // -// You may use [Datetime.IsZero] to check against this value. +// You may use [DateTime.IsZero] to check against this value. func MakeDateTime() DateTime { return DateTime(time.Time{}) } -// String converts this time to a string +// String converts this time to a string. func (t DateTime) String() string { return NormalizeTimeForMarshal(time.Time(t)).Format(MarshalFormat) } -// IsZero returns whether the date time is a zero value +// IsZero returns whether the date time is a zero value. func (t DateTime) IsZero() bool { return time.Time(t).IsZero() } -// IsUnixZero returns whether the date time is equivalent to time.Unix(0, 0).UTC(). +// IsUnixZero returns whether the date time is equivalent to [time.Unix](0, 0).UTC(). func (t DateTime) IsUnixZero() bool { return time.Time(t).Equal(UnixZero) } -// MarshalText implements the text marshaller interface +// MarshalText implements the text marshaler interface. func (t DateTime) MarshalText() ([]byte, error) { return []byte(t.String()), nil } -// UnmarshalText implements the text unmarshaller interface +// UnmarshalText implements the text unmarshaler interface. func (t *DateTime) UnmarshalText(text []byte) error { tt, err := ParseDateTime(string(text)) if err != nil { @@ -161,9 +167,9 @@ func (t *DateTime) UnmarshalText(text []byte) error { return nil } -// Scan scans a DateTime value from database driver type. +// Scan scans a [DateTime] value from database driver type. func (t *DateTime) Scan(raw any) error { - // TODO: case int64: and case float64: ? + // Proposal for enhancement: case int64: and case float64: ? switch v := raw.(type) { case []byte: return t.UnmarshalText(v) @@ -180,17 +186,17 @@ func (t *DateTime) Scan(raw any) error { return nil } -// Value converts DateTime to a primitive value ready to written to a database. +// Value converts [DateTime] to a primitive value ready to written to a database. func (t DateTime) Value() (driver.Value, error) { return driver.Value(t.String()), nil } -// MarshalJSON returns the DateTime as JSON +// MarshalJSON returns the [DateTime] as JSON. func (t DateTime) MarshalJSON() ([]byte, error) { return json.Marshal(NormalizeTimeForMarshal(time.Time(t)).Format(MarshalFormat)) } -// UnmarshalJSON sets the DateTime from JSON +// UnmarshalJSON sets the [DateTime] from JSON. func (t *DateTime) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -213,7 +219,7 @@ func (t *DateTime) DeepCopyInto(out *DateTime) { *out = *t } -// DeepCopy copies the receiver into a new DateTime. +// DeepCopy copies the receiver into a new [DateTime]. func (t *DateTime) DeepCopy() *DateTime { if t == nil { return nil @@ -233,12 +239,12 @@ func (t *DateTime) GobDecode(data []byte) error { return t.UnmarshalBinary(data) } -// MarshalBinary implements the encoding.BinaryMarshaler interface. +// MarshalBinary implements the encoding.[encoding.BinaryMarshaler] interface. func (t DateTime) MarshalBinary() ([]byte, error) { return NormalizeTimeForMarshal(time.Time(t)).MarshalBinary() } -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +// UnmarshalBinary implements the encoding.[encoding.BinaryUnmarshaler] interface. func (t *DateTime) UnmarshalBinary(data []byte) error { var original time.Time @@ -252,7 +258,7 @@ func (t *DateTime) UnmarshalBinary(data []byte) error { return nil } -// Equal checks if two DateTime instances are equal using time.Time's Equal method +// Equal checks if two [DateTime] instances are equal using [time.Time]'s Equal method. func (t DateTime) Equal(t2 DateTime) bool { return time.Time(t).Equal(time.Time(t2)) } diff --git a/vendor/github.com/go-openapi/strfmt/ulid.go b/vendor/github.com/go-openapi/strfmt/ulid.go index 85c5b53e..193988d3 100644 --- a/vendor/github.com/go-openapi/strfmt/ulid.go +++ b/vendor/github.com/go-openapi/strfmt/ulid.go @@ -11,10 +11,10 @@ import ( "io" "sync" - "github.com/oklog/ulid" + "github.com/oklog/ulid/v2" ) -// ULID represents a ulid string format +// ULID represents a [ulid] string format // ref: // // https://github.com/ulid/spec @@ -23,11 +23,12 @@ import ( // // https://github.com/oklog/ulid // -// swagger:strfmt ulid +// swagger:[strfmt] [ulid] type ULID struct { ulid.ULID } +//nolint:gochecknoglobals // package-level ULID configuration and overridable scan/value functions var ( ulidEntropyPool = sync.Pool{ New: func() any { @@ -35,6 +36,7 @@ var ( }, } + // ULIDScanDefaultFunc is the default implementation for scanning a [ULID] from a database driver value. ULIDScanDefaultFunc = func(raw any) (ULID, error) { u := NewULIDZero() switch x := raw.(type) { @@ -54,45 +56,44 @@ var ( return u, fmt.Errorf("cannot sql.Scan() strfmt.ULID from: %#v: %w", raw, ulid.ErrScanValue) } - // ULIDScanOverrideFunc allows you to override the Scan method of the ULID type + // ULIDScanOverrideFunc allows you to override the Scan method of the [ULID] type. ULIDScanOverrideFunc = ULIDScanDefaultFunc + // ULIDValueDefaultFunc is the default implementation for converting a [ULID] to a database driver value. ULIDValueDefaultFunc = func(u ULID) (driver.Value, error) { return driver.Value(u.String()), nil } - // ULIDValueOverrideFunc allows you to override the Value method of the ULID type + // ULIDValueOverrideFunc allows you to override the Value method of the [ULID] type. ULIDValueOverrideFunc = ULIDValueDefaultFunc ) -func init() { - // register formats in the default registry: - // - ulid +func init() { //nolint:gochecknoinits // registers ulid format in the default registry ulid := ULID{} Default.Add("ulid", &ulid, IsULID) } -// IsULID checks if provided string is ULID format -// Be noticed that this function considers overflowed ULID as non-ulid. -// For more details see https://github.com/ulid/spec +// IsULID checks if provided string is [ULID] format +// Be noticed that this function considers overflowed [ULID] as non-[ulid]. +// For more details see https://github.com/[ulid]/spec func IsULID(str string) bool { _, err := ulid.ParseStrict(str) return err == nil } -// ParseULID parses a string that represents an valid ULID +// ParseULID parses a string that represents an valid [ULID]. func ParseULID(str string) (ULID, error) { var u ULID return u, u.UnmarshalText([]byte(str)) } -// NewULIDZero returns a zero valued ULID type +// NewULIDZero returns a zero valued [ULID] type. func NewULIDZero() ULID { return ULID{} } -// NewULID generates new unique ULID value and a error if any +// NewULID generates new unique [ULID] value and a error if any. func NewULID() (ULID, error) { var u ULID @@ -112,22 +113,22 @@ func NewULID() (ULID, error) { return u, nil } -// GetULID returns underlying instance of ULID +// GetULID returns underlying instance of [ULID]. func (u *ULID) GetULID() any { return u.ULID } -// MarshalText returns this instance into text +// MarshalText returns this instance into text. func (u ULID) MarshalText() ([]byte, error) { return u.ULID.MarshalText() } -// UnmarshalText hydrates this instance from text +// UnmarshalText hydrates this instance from text. func (u *ULID) UnmarshalText(data []byte) error { // validation is performed later on return u.ULID.UnmarshalText(data) } -// Scan reads a value from a database driver +// Scan reads a value from a database driver. func (u *ULID) Scan(raw any) error { ul, err := ULIDScanOverrideFunc(raw) if err == nil { @@ -136,7 +137,7 @@ func (u *ULID) Scan(raw any) error { return err } -// Value converts a value to a database driver value +// Value converts a value to a database driver value. func (u ULID) Value() (driver.Value, error) { return ULIDValueOverrideFunc(u) } @@ -145,12 +146,12 @@ func (u ULID) String() string { return u.ULID.String() } -// MarshalJSON returns the ULID as JSON +// MarshalJSON returns the [ULID] as JSON. func (u ULID) MarshalJSON() ([]byte, error) { return json.Marshal(u.String()) } -// UnmarshalJSON sets the ULID from JSON +// UnmarshalJSON sets the [ULID] from JSON. func (u *ULID) UnmarshalJSON(data []byte) error { if string(data) == jsonNull { return nil @@ -172,7 +173,7 @@ func (u *ULID) DeepCopyInto(out *ULID) { *out = *u } -// DeepCopy copies the receiver into a new ULID. +// DeepCopy copies the receiver into a new [ULID]. func (u *ULID) DeepCopy() *ULID { if u == nil { return nil @@ -192,17 +193,17 @@ func (u *ULID) GobDecode(data []byte) error { return u.ULID.UnmarshalBinary(data) } -// MarshalBinary implements the encoding.BinaryMarshaler interface. +// MarshalBinary implements the encoding.[encoding.BinaryMarshaler] interface. func (u ULID) MarshalBinary() ([]byte, error) { return u.ULID.MarshalBinary() } -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +// UnmarshalBinary implements the encoding.[encoding.BinaryUnmarshaler] interface. func (u *ULID) UnmarshalBinary(data []byte) error { return u.ULID.UnmarshalBinary(data) } -// Equal checks if two ULID instances are equal by their underlying type +// Equal checks if two [ULID] instances are equal by their underlying type. func (u ULID) Equal(other ULID) bool { return u.ULID == other.ULID } diff --git a/vendor/github.com/go-openapi/swag/.gitignore b/vendor/github.com/go-openapi/swag/.gitignore index c4b1b64f..a0a95a96 100644 --- a/vendor/github.com/go-openapi/swag/.gitignore +++ b/vendor/github.com/go-openapi/swag/.gitignore @@ -3,3 +3,5 @@ vendor Godeps .idea *.out +.mcp.json +.claude/ diff --git a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md b/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md new file mode 100644 index 00000000..bc76fe82 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md @@ -0,0 +1,36 @@ +# Contributors + +- Repository: ['go-openapi/swag'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 24 | 235 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 105 | | +| @casualjim | 98 | | +| @alexandear | 4 | | +| @orisano | 3 | | +| @reinerRubin | 2 | | +| @n-inja | 2 | | +| @nitinmohan87 | 2 | | +| @Neo2308 | 2 | | +| @michaelbowler-form3 | 2 | | +| @ujjwalsh | 1 | | +| @griffin-stewie | 1 | | +| @POD666 | 1 | | +| @pytlesk4 | 1 | | +| @shirou | 1 | | +| @seanprince | 1 | | +| @petrkotas | 1 | | +| @mszczygiel | 1 | | +| @sosiska | 1 | | +| @kzys | 1 | | +| @faguirre1 | 1 | | +| @posener | 1 | | +| @diego-fu-hs | 1 | | +| @davidalpert | 1 | | +| @Xe | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md index 371fd55f..834eb2ff 100644 --- a/vendor/github.com/go-openapi/swag/README.md +++ b/vendor/github.com/go-openapi/swag/README.md @@ -1,26 +1,60 @@ -# Swag [![Build Status](https://github.com/go-openapi/swag/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/swag/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) +# Swag + + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](https://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/swag.svg)](https://pkg.go.dev/github.com/go-openapi/swag) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/swag)](https://goreportcard.com/report/github.com/go-openapi/swag) +--- -Package `swag` contains a bunch of helper functions for go-openapi and go-swagger projects. +A bunch of helper functions for go-openapi and go-swagger projects. You may also use it standalone for your projects. > **NOTE** > `swag` is one of the foundational building blocks of the go-openapi initiative. +> > Most repositories in `github.com/go-openapi/...` depend on it in some way. > And so does our CLI tool `github.com/go-swagger/go-swagger`, > as well as the code generated by this tool. * [Contents](#contents) * [Dependencies](#dependencies) -* [Release Notes](#release-notes) +* [Change log](#change-log) * [Licensing](#licensing) * [Note to contributors](#note-to-contributors) -* [TODOs, suggestions and plans](#todos-suggestions-and-plans) +* [Roadmap](#roadmap) + +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + +## Status + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/swag/{module} +``` + +Or for backward compatibility: + +```cmd +go get github.com/go-openapi/swag +``` ## Contents @@ -36,7 +70,7 @@ Child modules will continue to evolve and some new ones may be added in the futu | `cmdutils` | utilities to work with CLIs || | `conv` | type conversion utilities | convert between values and pointers for any types
convert from string to builtin types (wraps `strconv`)
require `./typeutils` (test dependency)
| | `fileutils` | file utilities | | -| `jsonname` | JSON utilities | infer JSON names from `go` properties
| +| `jsonname` | JSON utilities | infer JSON names from `go` properties
| | `jsonutils` | JSON utilities | fast json concatenation
read and write JSON from and to dynamic `go` data structures
~require `github.com/mailru/easyjson`~
| | `loading` | file loading | load from file or http
require `./yamlutils`
| | `mangling` | safe name generation | name mangling for `go`
| @@ -49,84 +83,19 @@ Child modules will continue to evolve and some new ones may be added in the futu ## Dependencies -The root module `github.com/go-openapi/swag` at the repo level maintains a few +The root module `github.com/go-openapi/swag` at the repo level maintains a few dependencies outside of the standard library. * YAML utilities depend on `go.yaml.in/yaml/v3` * JSON utilities depend on their registered adapter module: - * by default, only the standard library is used - * `github.com/mailru/easyjson` is now only a dependency for module - `github.com/go-openapi/swag/jsonutils/adapters/easyjson/json`, - for users willing to import that module. - * integration tests and benchmarks use all the dependencies are published as their own module + * by default, only the standard library is used + * `github.com/mailru/easyjson` is now only a dependency for module + `github.com/go-openapi/swag/jsonutils/adapters/easyjson/json`, + for users willing to import that module. + * integration tests and benchmarks use all the dependencies are published as their own module * other dependencies are test dependencies drawn from `github.com/stretchr/testify` -## Release notes - -### v0.25.4 - -** mangling** - -Bug fix - -* [x] mangler may panic with pluralized overlapping initialisms - -Tests - -* [x] introduced fuzz tests - -### v0.25.3 - -** mangling** - -Bug fix - -* [x] mangler may panic with pluralized initialisms - -### v0.25.2 - -Minor changes due to internal maintenance that don't affect the behavior of the library. - -* [x] removed indirect test dependencies by switching all tests to `go-openapi/testify`, - a fork of `stretch/testify` with zero-dependencies. -* [x] improvements to CI to catch test reports. -* [x] modernized licensing annotations in source code, using the more compact SPDX annotations - rather than the full license terms. -* [x] simplified a bit JSON & YAML testing by using newly available assertions -* started the journey to an OpenSSF score card badge: - * [x] explicited permissions in CI workflows - * [x] published security policy - * pinned dependencies to github actions - * introduced fuzzing in tests - -### v0.25.1 - -* fixes a data race that could occur when using the standard library implementation of a JSON ordered map - -### v0.25.0 - -**New with this release**: - -* requires `go1.24`, as iterators are being introduced -* removes the dependency to `mailru/easyjson` by default (#68) - * functionality remains the same, but performance may somewhat degrade for applications - that relied on `easyjson` - * users of the JSON or YAML utilities who want to use `easyjson` as their preferred JSON serializer library - will be able to do so by registering this the corresponding JSON adapter at runtime. See below. - * ordered keys in JSON and YAML objects: this feature used to rely solely on `easyjson`. - With this release, an implementation relying on the standard `encoding/json` is provided. - * an independent [benchmark](./jsonutils/adapters/testintegration/benchmarks/README.md) to compare the different adapters -* improves the "float is integer" check (`conv.IsFloat64AJSONInteger`) (#59) -* removes the _direct_ dependency to `gopkg.in/yaml.v3` (indirect dependency is still incurred through `stretchr/testify`) (#127) -* exposed `conv.IsNil()` (previously kept private): a safe nil check (accounting for the "non-nil interface with nil value" nonsensical go trick) - -**What coming next?** - -Moving forward, we want to : -* provide an implementation of the JSON adapter based on `encoding/json/v2`, for `go1.25` builds. -* provide similar implementations for `goccy/go-json` and `jsoniterator/go`, and perhaps some other - similar libraries may be interesting too. - +## Usage **How to explicitly register a dependency at runtime**? @@ -150,90 +119,106 @@ or fallback to the standard library. For more details, you may also look at our [integration tests](jsonutils/adapters/testintegration/integration_suite_test.go#29). -### v0.24.0 +--- -With this release, we have largely modernized the API of `swag`: +## Note to contributors -* The traditional `swag` API is still supported: code that imports `swag` will still - compile and work the same. -* A deprecation notice is published to encourage consumers of this library to adopt - the newer API -* **Deprecation notice** - * configuration through global variables is now deprecated, in favor of options passed as parameters - * all helper functions are moved to more specialized packages, which are exposed as - go modules. Importing such a module would reduce the footprint of dependencies. - * _all_ functions, variables, constants exposed by the deprecated API have now moved, so - that consumers of the new API no longer need to import github.com/go-openapi/swag, but - should import the desired sub-module(s). +All kinds of contributions are welcome. -**New with this release**: +This repo is a go mono-repo. See [docs](docs/MAINTAINERS.md). -* [x] type converters and pointer to value helpers now support generic types -* [x] name mangling now support pluralized initialisms (issue #46) - Strings like "contact IDs" are now recognized as such a plural form and mangled as a linter would expect. -* [x] performance: small improvements to reduce the overhead of convert/format wrappers (see issues #110, or PR #108) -* [x] performance: name mangling utilities run ~ 10% faster (PR #115) +More general guidelines are available [here](.github/CONTRIBUTING.md). ---- +## Roadmap -## Licensing +See the current [TODO list](docs/TODOS.md) -This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). +## Change log -## Note to contributors +See -A mono-repo structure comes with some unavoidable extra pains... +For pre-v0.26.0 releases, see [release notes](./docs/NOTES.md). -* Testing +**What coming next?** -> The usual `go test ./...` command, run from the root of this repo won't work any longer to test all submodules. -> -> Each module constitutes an independant unit of test. So you have to run `go test` inside each module. -> Or you may take a look at how this is achieved by CI -> [here] https://github.com/go-openapi/swag/blob/master/.github/workflows/go-test.yml). -> -> There are also some alternative tricks using `go work`, for local development, if you feel comfortable with -> go workspaces. Perhaps some day, we'll have a `go work test` to run all tests without any hack. +Moving forward, we want to : -* Releasing +* provide an implementation of the JSON adapter based on `encoding/json/v2`, for `go1.25` builds. +* provide similar implementations for `goccy/go-json` and `jsoniterator/go`, and perhaps some other + similar libraries may be interesting too. -> Each module follows its own independant module versioning. -> -> So you have tags like `mangling/v0.24.0`, `fileutils/v0.24.0` etc that are used by `go mod` and `go get` -> to refer to the tagged version of each module specifically. -> -> This means we may release patches etc to each module independently. -> -> We'd like to adopt the rule that modules in this repo would only differ by a patch version -> (e.g. `v0.24.5` vs `v0.24.3`), and we'll level all modules whenever a minor version is introduced. -> -> A script in `./hack` is provided to tag all modules with the same version in one go. + -## Todos, suggestions and plans +## Licensing -All kinds of contributions are welcome. +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). -A few ideas: - -* [x] Complete the split of dependencies to isolate easyjson from the rest -* [x] Improve CI to reduce needed tests -* [x] Replace dependency to `gopkg.in/yaml.v3` (`yamlutil`) -* [ ] Improve mangling utilities (improve readability, support for capitalized words, - better word substitution for non-letter symbols...) -* [ ] Move back to this common shared pot a few of the technical features introduced by go-swagger independently - (e.g. mangle go package names, search package with go modules support, ...) -* [ ] Apply a similar mono-repo approach to go-openapi/strfmt which suffer from similar woes: bloated API, - imposed dependency to some database driver. -* [ ] Adapt `go-swagger` (incl. generated code) to the new `swag` API. -* [ ] Factorize some tests, as there is a lot of redundant testing code in `jsonutils` -* [ ] Benchmark & profiling: publish independently the tool built to analyze and chart benchmarks (e.g. similar to `benchvisual`) -* [ ] more thorough testing for nil / null case -* [ ] ci pipeline to manage releases -* [ ] cleaner mockery generation (doesn't work out of the box for all sub-modules) + + + + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/swag/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/swag/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/swag/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/swag +[vuln-scan-badge]: https://github.com/go-openapi/swag/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/swag/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/swag/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/swag/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fswag.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fswag +[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fswag.svg +[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fswag + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/swag +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/swag +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/swag +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/swag + +[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F +[doc-url]: https://goswagger.io/go-openapi +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/swag +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/swag +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/swag/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/swag +[goversion-url]: https://github.com/go-openapi/swag/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/swag +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/swag/latest diff --git a/vendor/github.com/go-openapi/swag/jsonutils/README.md b/vendor/github.com/go-openapi/swag/jsonutils/README.md index d745cdb4..07a2ca1d 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/README.md +++ b/vendor/github.com/go-openapi/swag/jsonutils/README.md @@ -1,11 +1,11 @@ - # jsonutils +# jsonutils `jsonutils` exposes a few tools to work with JSON: - a fast, simple `Concat` to concatenate (not merge) JSON objects and arrays - `FromDynamicJSON` to convert a data structure into a "dynamic JSON" data structure - `ReadJSON` and `WriteJSON` behave like `json.Unmarshal` and `json.Marshal`, - with the ability to use another underlying serialization library through an `Adapter` + with the ability to use another underlying serialization library through an `Adapter` configured at runtime - a `JSONMapSlice` structure that may be used to store JSON objects with the order of keys maintained @@ -64,7 +64,7 @@ find a registered implementation that support ordered keys in objects. Our standard library implementation supports this. As of `v0.25.0`, we support through such an adapter the popular `mailru/easyjson` -library, which kicks in when the passed values support the `easyjson.Unmarshaler` +library, which kicks in when the passed values support the `easyjson.Unmarshaler` or `easyjson.Marshaler` interfaces. In the future, we plan to add more similar libraries that compete on the go JSON @@ -77,8 +77,9 @@ In package `github.com/go-openapi/swag/easyjson/adapters`, several adapters are Each adapter is an independent go module. Hence you'll pick its dependencies only if you import it. At this moment we provide: -* `stdlib`: JSON adapter based on the standard library -* `easyjson`: JSON adapter based on the `github.com/mailru/easyjson` + +- `stdlib`: JSON adapter based on the standard library +- `easyjson`: JSON adapter based on the `github.com/mailru/easyjson` The adapters provide the basic `Marshal` and `Unmarshal` capabilities, plus an implementation of the `MapSlice` pattern. diff --git a/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md b/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md index 6674c63b..abe6e953 100644 --- a/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md +++ b/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md @@ -4,7 +4,7 @@ go test -bench XXX -run XXX -benchtime 30s ``` -## Benchmarks at b3e7a5386f996177e4808f11acb2aa93a0f660df +## Benchmarks at `b3e7a5386f996177e4808f11acb2aa93a0f660df` ``` goos: linux @@ -49,7 +49,7 @@ BenchmarkToXXXName/ToHumanNameLower-16 18599661 1946 ns/op 92 B/op BenchmarkToXXXName/ToHumanNameTitle-16 17581353 2054 ns/op 105 B/op 6 allocs/op ``` -## Benchmarks at d7d2d1b895f5b6747afaff312dd2a402e69e818b +## Benchmarks at `d7d2d1b895f5b6747afaff312dd2a402e69e818b` go1.24 diff --git a/vendor/github.com/go-openapi/validate/.gitignore b/vendor/github.com/go-openapi/validate/.gitignore index fea8b84e..d8f4186f 100644 --- a/vendor/github.com/go-openapi/validate/.gitignore +++ b/vendor/github.com/go-openapi/validate/.gitignore @@ -1,5 +1,5 @@ -secrets.yml -coverage.out -*.cov *.out -playground +*.cov +.idea +.env +.mcp.json diff --git a/vendor/github.com/go-openapi/validate/.golangci.yml b/vendor/github.com/go-openapi/validate/.golangci.yml index 10c51334..4d6b36e4 100644 --- a/vendor/github.com/go-openapi/validate/.golangci.yml +++ b/vendor/github.com/go-openapi/validate/.golangci.yml @@ -2,27 +2,15 @@ version: "2" linters: default: all disable: - - cyclop - depguard - - errchkjson - - errorlint - - exhaustruct - - forcetypeassert - funlen - gochecknoglobals - gochecknoinits - - gocognit - - godot - godox - - gomoddirectives - - gosmopolitan - - inamedparam - - intrange + - exhaustruct - ireturn - - lll - - musttag - - nestif - nlreturn + - nestif - nonamedreturns - noinlineerr - paralleltest @@ -30,7 +18,6 @@ linters: - testpackage - thelper - tparallel - - unparam - varnamelen - whitespace - wrapcheck @@ -42,8 +29,17 @@ linters: goconst: min-len: 2 min-occurrences: 3 + cyclop: + max-complexity: 40 gocyclo: - min-complexity: 45 + min-complexity: 40 + gocognit: + min-complexity: 40 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 exclusions: generated: lax presets: @@ -59,6 +55,7 @@ formatters: enable: - gofmt - goimports + - gofumpt exclusions: generated: lax paths: diff --git a/vendor/github.com/go-openapi/validate/BENCHMARK.md b/vendor/github.com/go-openapi/validate/BENCHMARK.md index 79cf6a07..0353eae5 100644 --- a/vendor/github.com/go-openapi/validate/BENCHMARK.md +++ b/vendor/github.com/go-openapi/validate/BENCHMARK.md @@ -3,6 +3,7 @@ Validating the Kubernetes Swagger API ## v0.22.6: 60,000,000 allocs + ``` goos: linux goarch: amd64 @@ -11,7 +12,8 @@ cpu: AMD Ryzen 7 5800X 8-Core Processor Benchmark_KubernetesSpec/validating_kubernetes_API-16 1 8549863982 ns/op 7067424936 B/op 59583275 allocs/op ``` -## After refact PR: minor but noticable improvements: 25,000,000 allocs +## After refact PR: minor but noticeable improvements: 25,000,000 allocs + ``` go test -bench Spec goos: linux @@ -22,6 +24,7 @@ Benchmark_KubernetesSpec/validating_kubernetes_API-16 1 40645355 ``` ## After reduce GC pressure PR: 17,000,000 allocs + ``` goos: linux goarch: amd64 diff --git a/vendor/github.com/go-openapi/validate/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/validate/CODE_OF_CONDUCT.md index 9322b065..bac878f2 100644 --- a/vendor/github.com/go-openapi/validate/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/validate/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/validate/CONTRIBUTORS.md b/vendor/github.com/go-openapi/validate/CONTRIBUTORS.md new file mode 100644 index 00000000..7b79b765 --- /dev/null +++ b/vendor/github.com/go-openapi/validate/CONTRIBUTORS.md @@ -0,0 +1,43 @@ +# Contributors + +- Repository: ['go-openapi/validate'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 31 | 295 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @casualjim | 169 | | +| @fredbi | 58 | | +| @sttts | 11 | | +| @youyuanwu | 9 | | +| @keramix | 8 | | +| @jerome-laforge | 4 | | +| @GlenDC | 4 | | +| @galaxie | 3 | | +| @tossmilestone | 2 | | +| @EleanorRigby | 2 | | +| @jiuker | 2 | | +| @pytlesk4 | 2 | | +| @dimovnike | 2 | | +| @gbjk | 2 | | +| @ujjwalsh | 1 | | +| @key-amb | 1 | | +| @caglar10ur | 1 | | +| @petrkotas | 1 | | +| @dolmen | 1 | | +| @nikhita | 1 | | +| @koron | 1 | | +| @liggitt | 1 | | +| @ilyakaznacheev | 1 | | +| @hypnoglow | 1 | | +| @gautierdelorme | 1 | | +| @flavioribeiro | 1 | | +| @pheepi | 1 | | +| @carvind | 1 | | +| @artemseleznev | 1 | | +| @dadgar | 1 | | +| @elakito | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/validate/README.md b/vendor/github.com/go-openapi/validate/README.md index 73d87ce4..fec42b7c 100644 --- a/vendor/github.com/go-openapi/validate/README.md +++ b/vendor/github.com/go-openapi/validate/README.md @@ -1,15 +1,42 @@ -# Validation helpers [![Build Status](https://github.com/go-openapi/validate/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/validate/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/validate/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/validate) +# validate -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/validate/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/validate.svg)](https://pkg.go.dev/github.com/go-openapi/validate) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/validate)](https://goreportcard.com/report/github.com/go-openapi/validate) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -This package provides helpers to validate Swagger 2.0. specification (aka OpenAPI 2.0). +--- + +A validator for OpenAPI v2 specifications and JSON schema draft 4. + +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] + +## Status + +API is stable. -Reference can be found here: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md. +## Import this library in your project -## What's inside? +```cmd +go get github.com/go-openapi/validate +``` + +## Contents + +This package provides helpers to validate Swagger 2.0. specification (aka OpenAPI 2.0). * A validator for Swagger specifications * A validator for JSON schemas draft4 @@ -22,13 +49,7 @@ Reference can be found here: https://github.com/OAI/OpenAPI-Specification/blob/m * Minimum, Maximum, MultipleOf * FormatOf -[Documentation](https://pkg.go.dev/github.com/go-openapi/validate) - -## Licensing - -This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). - -## FAQ +### FAQ * Does this library support OpenAPI 3? @@ -37,4 +58,67 @@ This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). > There is no plan to make it evolve toward supporting OpenAPI 3.x. > This [discussion thread](https://github.com/go-openapi/spec/issues/21) relates the full story. > -> An early attempt to support Swagger 3 may be found at: https://github.com/go-openapi/spec3 +> An early attempt to support Swagger 3 may be found at: + +## Change log + +See + +## References + + + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/validate/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/validate/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/validate/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/validate/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/validate +[vuln-scan-badge]: https://github.com/go-openapi/validate/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/validate/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/validate/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/validate/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fvalidate.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fvalidate + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/validate +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/validate +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/validate +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/validate + +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/validate +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/validate +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/validate/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/validate +[goversion-url]: https://github.com/go-openapi/validate/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/validate +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/validate/latest diff --git a/vendor/github.com/go-openapi/validate/SECURITY.md b/vendor/github.com/go-openapi/validate/SECURITY.md new file mode 100644 index 00000000..6ceb159c --- /dev/null +++ b/vendor/github.com/go-openapi/validate/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/validate/context.go b/vendor/github.com/go-openapi/validate/context.go index b4587dcd..7f295f97 100644 --- a/vendor/github.com/go-openapi/validate/context.go +++ b/vendor/github.com/go-openapi/validate/context.go @@ -7,7 +7,7 @@ import ( "context" ) -// validateCtxKey is the key type of context key in this pkg +// validateCtxKey is the key type of context key in this pkg. type validateCtxKey string const ( @@ -25,13 +25,13 @@ const ( var operationTypeEnum = []operationType{request, response, none} // WithOperationRequest returns a new context with operationType request -// in context value +// in context value. func WithOperationRequest(ctx context.Context) context.Context { return withOperation(ctx, request) } // WithOperationResponse returns a new context with operationType response -// in context value +// in context value. func WithOperationResponse(ctx context.Context) context.Context { return withOperation(ctx, response) } @@ -41,7 +41,7 @@ func withOperation(ctx context.Context, operation operationType) context.Context } // extractOperationType extracts the operation type from ctx -// if not specified or of unknown value, return none operation type +// if not specified or of unknown value, return none operation type. func extractOperationType(ctx context.Context) operationType { v := ctx.Value(operationTypeKey) if v == nil { diff --git a/vendor/github.com/go-openapi/validate/debug.go b/vendor/github.com/go-openapi/validate/debug.go index 79145a44..c890d128 100644 --- a/vendor/github.com/go-openapi/validate/debug.go +++ b/vendor/github.com/go-openapi/validate/debug.go @@ -15,7 +15,7 @@ var ( // Debug is true when the SWAGGER_DEBUG env var is not empty. // It enables a more verbose logging of validators. Debug = os.Getenv("SWAGGER_DEBUG") != "" - // validateLogger is a debug logger for this package + // validateLogger is a debug logger for this package. validateLogger *log.Logger ) diff --git a/vendor/github.com/go-openapi/validate/default_validator.go b/vendor/github.com/go-openapi/validate/default_validator.go index 79a43167..ebcd8071 100644 --- a/vendor/github.com/go-openapi/validate/default_validator.go +++ b/vendor/github.com/go-openapi/validate/default_validator.go @@ -18,7 +18,7 @@ type defaultValidator struct { schemaOptions *SchemaValidatorOptions } -// Validate validates the default values declared in the swagger spec +// Validate validates the default values declared in the swagger spec. func (d *defaultValidator) Validate() *Result { errs := pools.poolOfResults.BorrowResult() // will redeem when merged @@ -30,7 +30,7 @@ func (d *defaultValidator) Validate() *Result { return errs } -// resetVisited resets the internal state of visited schemas +// resetVisited resets the internal state of visited schemas. func (d *defaultValidator) resetVisited() { if d.visitedSchemas == nil { d.visitedSchemas = make(map[string]struct{}) @@ -38,7 +38,7 @@ func (d *defaultValidator) resetVisited() { return } - // TODO(go1.21): clear(ex.visitedSchemas) + // NOTE(go1.21): clear(ex.visitedSchemas) for k := range d.visitedSchemas { delete(d.visitedSchemas, k) } @@ -73,16 +73,17 @@ func isVisited(path string, visitedSchemas map[string]struct{}) bool { return false } -// beingVisited asserts a schema is being visited +// beingVisited asserts a schema is being visited. func (d *defaultValidator) beingVisited(path string) { d.visitedSchemas[path] = struct{}{} } -// isVisited tells if a path has already been visited +// isVisited tells if a path has already been visited. func (d *defaultValidator) isVisited(path string) bool { return isVisited(path, d.visitedSchemas) } +//nolint:gocognit // refactor in a forthcoming PR func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result { // every default value that is specified must validate against the schema for that property // headers, items, parameters, schema @@ -272,7 +273,7 @@ func (d *defaultValidator) validateDefaultValueSchemaAgainstSchema(path, in stri return res } -// TODO: Temporary duplicated code. Need to refactor with examples +// NOTE: Temporary duplicated code. Need to refactor with examples func (d *defaultValidator) validateDefaultValueItemsAgainstSchema(path, in string, root any, items *spec.Items) *Result { res := pools.poolOfResults.BorrowResult() diff --git a/vendor/github.com/go-openapi/validate/doc.go b/vendor/github.com/go-openapi/validate/doc.go index a99893e1..5218ec85 100644 --- a/vendor/github.com/go-openapi/validate/doc.go +++ b/vendor/github.com/go-openapi/validate/doc.go @@ -1,76 +1,76 @@ // SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers // SPDX-License-Identifier: Apache-2.0 -/* -Package validate provides methods to validate a swagger specification, -as well as tools to validate data against their schema. - -This package follows Swagger 2.0. specification (aka OpenAPI 2.0). Reference -can be found here: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md. - -# Validating a specification - -Validates a spec document (from JSON or YAML) against the JSON schema for swagger, -then checks a number of extra rules that can't be expressed in JSON schema. - -Entry points: - - Spec() - - NewSpecValidator() - - SpecValidator.Validate() - -Reported as errors: - - [x] definition can't declare a property that's already defined by one of its ancestors - [x] definition's ancestor can't be a descendant of the same model - [x] path uniqueness: each api path should be non-verbatim (account for path param names) unique per method. Validation can be laxed by disabling StrictPathParamUniqueness. - [x] each security reference should contain only unique scopes - [x] each security scope in a security definition should be unique - [x] parameters in path must be unique - [x] each path parameter must correspond to a parameter placeholder and vice versa - [x] each referenceable definition must have references - [x] each definition property listed in the required array must be defined in the properties of the model - [x] each parameter should have a unique `name` and `type` combination - [x] each operation should have only 1 parameter of type body - [x] each reference must point to a valid object - [x] every default value that is specified must validate against the schema for that property - [x] items property is required for all schemas/definitions of type `array` - [x] path parameters must be declared a required - [x] headers must not contain $ref - [x] schema and property examples provided must validate against their respective object's schema - [x] examples provided must validate their schema - -Reported as warnings: - - [x] path parameters should not contain any of [{,},\w] - [x] empty path - [x] unused definitions - [x] unsupported validation of examples on non-JSON media types - [x] examples in response without schema - [x] readOnly properties should not be required - -# Validating a schema - -The schema validation toolkit validates data against JSON-schema-draft 04 schema. - -It is tested against the full json-schema-testing-suite (https://github.com/json-schema-org/JSON-Schema-Test-Suite), -except for the optional part (bignum, ECMA regexp, ...). - -It supports the complete JSON-schema vocabulary, including keywords not supported by Swagger (e.g. additionalItems, ...) - -Entry points: - - AgainstSchema() - - ... - -# Known limitations - -With the current version of this package, the following aspects of swagger are not yet supported: - - [ ] errors and warnings are not reported with key/line number in spec - [ ] default values and examples on responses only support application/json producer type - [ ] invalid numeric constraints (such as Minimum, etc..) are not checked except for default and example values - [ ] rules for collectionFormat are not implemented - [ ] no validation rule for polymorphism support (discriminator) [not done here] - [ ] valid js ECMA regexp not supported by Go regexp engine are considered invalid - [ ] arbitrary large numbers are not supported: max is math.MaxFloat64 -*/ +// Package validate provides methods to validate a swagger specification, +// as well as tools to validate data against their schema. +// +// This package follows Swagger 2.0. specification (aka OpenAPI 2.0). Reference. +// can be found here: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md. +// +// # Validating a specification +// +// Validates a spec document (from JSON or YAML) against the JSON schema for swagger, +// then checks a number of extra rules that can't be expressed in JSON schema. +// +// Entry points: +// +// - Spec() +// - [NewSpecValidator]() +// - [SpecValidator].Validate() +// +// Reported as errors: +// +// [x] definition can't declare a property that's already defined by one of its ancestors +// [x] definition's ancestor can't be a descendant of the same model +// [x] path uniqueness: each api path should be non-verbatim (account for path param names) unique per method. Validation can be laxed by disabling StrictPathParamUniqueness. +// [x] each security reference should contain only unique scopes +// [x] each security scope in a security definition should be unique +// [x] parameters in path must be unique +// [x] each path parameter must correspond to a parameter placeholder and vice versa +// [x] each referenceable definition must have references +// [x] each definition property listed in the required array must be defined in the properties of the model +// [x] each parameter should have a unique `name` and `type` combination +// [x] each operation should have only 1 parameter of type body +// [x] each reference must point to a valid object +// [x] every default value that is specified must validate against the schema for that property +// [x] items property is required for all schemas/definitions of type `array` +// [x] path parameters must be declared a required +// [x] headers must not contain $ref +// [x] schema and property examples provided must validate against their respective object's schema +// [x] examples provided must validate their schema +// +// Reported as warnings: +// +// [x] path parameters should not contain any of [{,},\w] +// [x] empty path +// [x] unused definitions +// [x] unsupported validation of examples on non-JSON media types +// [x] examples in response without schema +// [x] readOnly properties should not be required +// +// # Validating a schema +// +// The schema validation toolkit validates data against JSON-schema-draft 04 schema. +// +// It is tested against the full json-schema-testing-suite (https://github.com/json-schema-org/JSON-Schema-Test-Suite), +// except for the optional part (bignum, ECMA regexp, ...). +// +// It supports the complete JSON-schema vocabulary, including keywords not supported by Swagger (e.g. additionalItems, ...) +// +// Entry points: +// +// - [AgainstSchema]() +// - ... +// +// # Known limitations +// +// With the current version of this package, the following aspects of swagger are not yet supported: +// +// [ ] errors and warnings are not reported with key/line number in spec +// [ ] default values and examples on responses only support application/json producer type +// [ ] invalid numeric constraints (such as Minimum, etc..) are not checked except for default and example values +// [ ] rules for collectionFormat are not implemented +// [ ] no validation rule for polymorphism support (discriminator) [not done here] +// [ ] valid js ECMA regexp not supported by Go regexp engine are considered invalid +// [ ] arbitrary large numbers are not supported: max is math.MaxFloat64 package validate diff --git a/vendor/github.com/go-openapi/validate/example_validator.go b/vendor/github.com/go-openapi/validate/example_validator.go index e4ef52c6..eb6b5ee5 100644 --- a/vendor/github.com/go-openapi/validate/example_validator.go +++ b/vendor/github.com/go-openapi/validate/example_validator.go @@ -9,7 +9,7 @@ import ( "github.com/go-openapi/spec" ) -// ExampleValidator validates example values defined in a spec +// ExampleValidator validates example values defined in a spec. type exampleValidator struct { SpecValidator *SpecValidator visitedSchemas map[string]struct{} @@ -35,7 +35,7 @@ func (ex *exampleValidator) Validate() *Result { return errs } -// resetVisited resets the internal state of visited schemas +// resetVisited resets the internal state of visited schemas. func (ex *exampleValidator) resetVisited() { if ex.visitedSchemas == nil { ex.visitedSchemas = make(map[string]struct{}) @@ -43,22 +43,23 @@ func (ex *exampleValidator) resetVisited() { return } - // TODO(go1.21): clear(ex.visitedSchemas) + // NOTE(go1.21): clear(ex.visitedSchemas) for k := range ex.visitedSchemas { delete(ex.visitedSchemas, k) } } -// beingVisited asserts a schema is being visited +// beingVisited asserts a schema is being visited. func (ex *exampleValidator) beingVisited(path string) { ex.visitedSchemas[path] = struct{}{} } -// isVisited tells if a path has already been visited +// isVisited tells if a path has already been visited. func (ex *exampleValidator) isVisited(path string) bool { return isVisited(path, ex.visitedSchemas) } +//nolint:gocognit // refactor in a forthcoming PR func (ex *exampleValidator) validateExampleValueValidAgainstSchema() *Result { // every example value that is specified must validate against the schema for that property // in: schemas, properties, object, items @@ -205,7 +206,7 @@ func (ex *exampleValidator) validateExampleInResponse(resp *spec.Response, respo newSchemaValidator(response.Schema, s.spec.Spec(), path+".examples", s.KnownFormats, s.schemaOptions).Validate(example), ) } else { - // TODO: validate other media types too + // Proposal for enhancement: validate other media types too res.AddWarnings(examplesMimeNotSupportedMsg(operationID, responseName)) } } else { @@ -264,7 +265,7 @@ func (ex *exampleValidator) validateExampleValueSchemaAgainstSchema(path, in str return res } -// TODO: Temporary duplicated code. Need to refactor with examples +// NOTE: Temporary duplicated code. Need to refactor with examples // func (ex *exampleValidator) validateExampleValueItemsAgainstSchema(path, in string, root any, items *spec.Items) *Result { diff --git a/vendor/github.com/go-openapi/validate/formats.go b/vendor/github.com/go-openapi/validate/formats.go index 85ee6349..eab26153 100644 --- a/vendor/github.com/go-openapi/validate/formats.go +++ b/vendor/github.com/go-openapi/validate/formats.go @@ -76,7 +76,12 @@ func (f *formatValidator) Validate(val any) *Result { result = new(Result) } - if err := FormatOf(f.Path, f.In, f.Format, val.(string), f.KnownFormats); err != nil { + str, ok := val.(string) + if !ok { + return result + } + + if err := FormatOf(f.Path, f.In, f.Format, str, f.KnownFormats); err != nil { result.AddErrors(err) } diff --git a/vendor/github.com/go-openapi/validate/helpers.go b/vendor/github.com/go-openapi/validate/helpers.go index 49b13047..8a1a2312 100644 --- a/vendor/github.com/go-openapi/validate/helpers.go +++ b/vendor/github.com/go-openapi/validate/helpers.go @@ -3,7 +3,7 @@ package validate -// TODO: define this as package validate/internal +// Proposal for enhancement: define this as package validate/internal // This must be done while keeping CI intact with all tests and test coverage import ( @@ -36,7 +36,7 @@ const ( jsonProperties = "properties" jsonItems = "items" jsonType = "type" - // jsonSchema = "schema" + // jsonSchema = "schema". jsonDefault = "default" ) @@ -45,7 +45,7 @@ const ( stringFormatDateTime = "date-time" stringFormatPassword = "password" stringFormatByte = "byte" - // stringFormatBinary = "binary" + // stringFormatBinary = "binary". stringFormatCreditCard = "creditcard" stringFormatDuration = "duration" stringFormatEmail = "email" @@ -77,7 +77,7 @@ const ( numberFormatDouble = "double" ) -// Helpers available at the package level +// Helpers available at the package level. var ( pathHelp *pathHelper valueHelp *valueHelper @@ -126,10 +126,11 @@ func (h *pathHelper) stripParametersInPath(path string) string { // Regexp to extract parameters from path, with surrounding {}. // NOTE: important non-greedy modifier rexParsePathParam := mustCompileRegexp(`{[^{}]+?}`) - strippedSegments := []string{} + segments := strings.Split(path, "/") + strippedSegments := make([]string, len(segments)) - for segment := range strings.SplitSeq(path, "/") { - strippedSegments = append(strippedSegments, rexParsePathParam.ReplaceAllString(segment, "X")) + for i, segment := range segments { + strippedSegments[i] = rexParsePathParam.ReplaceAllString(segment, "X") } return strings.Join(strippedSegments, "/") } @@ -154,7 +155,7 @@ func (h *valueHelper) asInt64(val any) int64 { // Number conversion function for int64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) - switch v.Kind() { //nolint:exhaustive + switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: @@ -171,7 +172,7 @@ func (h *valueHelper) asUint64(val any) uint64 { // Number conversion function for uint64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) - switch v.Kind() { //nolint:exhaustive + switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return uint64(v.Int()) //nolint:gosec case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: @@ -184,12 +185,12 @@ func (h *valueHelper) asUint64(val any) uint64 { } } -// Same for unsigned floats +// Same for unsigned floats. func (h *valueHelper) asFloat64(val any) float64 { // Number conversion function for float64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) - switch v.Kind() { //nolint:exhaustive + switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return float64(v.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: @@ -244,7 +245,6 @@ func (h *paramHelper) resolveParam(path, method, operationID string, param *spec err = spec.ExpandParameterWithRoot(param, s.spec.Spec(), nil) } else { err = spec.ExpandParameter(param, s.spec.SpecFilePath()) - } if err != nil { // Safeguard // NOTE: we may enter here when the whole parameter is an unresolved $ref @@ -288,7 +288,8 @@ type responseHelper struct { func (r *responseHelper) expandResponseRef( response *spec.Response, - path string, s *SpecValidator) (*spec.Response, *Result) { + path string, s *SpecValidator, +) (*spec.Response, *Result) { // Ensure response is expanded var err error res := new(Result) @@ -309,7 +310,8 @@ func (r *responseHelper) expandResponseRef( func (r *responseHelper) responseMsgVariants( responseType string, - responseCode int) (responseName, responseCodeAsStr string) { + responseCode int, +) (responseName, responseCodeAsStr string) { // Path variants for messages if responseType == jsonDefault { responseCodeAsStr = jsonDefault diff --git a/vendor/github.com/go-openapi/validate/object_validator.go b/vendor/github.com/go-openapi/validate/object_validator.go index cf98ed37..e651b3f7 100644 --- a/vendor/github.com/go-openapi/validate/object_validator.go +++ b/vendor/github.com/go-openapi/validate/object_validator.go @@ -31,7 +31,8 @@ type objectValidator struct { func newObjectValidator(path, in string, maxProperties, minProperties *int64, required []string, properties spec.SchemaProperties, additionalProperties *spec.SchemaOrBool, patternProperties spec.SchemaProperties, - root any, formats strfmt.Registry, opts *SchemaValidatorOptions) *objectValidator { + root any, formats strfmt.Registry, opts *SchemaValidatorOptions, +) *objectValidator { if opts == nil { opts = new(SchemaValidatorOptions) } @@ -104,7 +105,7 @@ func (o *objectValidator) Validate(data any) *Result { o.validatePropertiesSchema(val, res) // Check patternProperties - // TODO: it looks like we have done that twice in many cases + // NOTE: it looks like we have done that twice in many cases for key, value := range val { _, regularProperty := o.Properties[key] matched, _, patterns := o.validatePatternProperty(key, value, res) // applies to regular properties as well @@ -115,7 +116,7 @@ func (o *objectValidator) Validate(data any) *Result { for _, pName := range patterns { if v, ok := o.PatternProperties[pName]; ok { r := newSchemaValidator(&v, o.Root, o.Path+"."+key, o.KnownFormats, o.Options).Validate(value) - res.mergeForField(data.(map[string]any), key, r) + res.mergeForField(data.(map[string]any), key, r) //nolint:forcetypeassert // data is always map[string]any at this point } } } @@ -129,7 +130,7 @@ func (o *objectValidator) SetPath(path string) { } func (o *objectValidator) Applies(source any, kind reflect.Kind) bool { - // TODO: this should also work for structs + // NOTE: this should also work for structs // there is a problem in the type validator where it will be unhappy about null values // so that requires more testing _, isSchema := source.(*spec.Schema) @@ -285,7 +286,7 @@ func (o *objectValidator) validateNoAdditionalProperties(val map[string]any, res /* case "$ref": if val[k] != nil { - // TODO: check context of that ref: warn about siblings, check against invalid context + // Proposal for enhancement: check context of that ref: warn about siblings, check against invalid context } */ } @@ -377,7 +378,7 @@ func (o *objectValidator) validatePropertiesSchema(val map[string]any, res *Resu } } -// TODO: succeededOnce is not used anywhere +// NOTE: succeededOnce is not used anywhere. func (o *objectValidator) validatePatternProperty(key string, value any, result *Result) (bool, bool, []string) { if len(o.PatternProperties) == 0 { return false, false, nil diff --git a/vendor/github.com/go-openapi/validate/options.go b/vendor/github.com/go-openapi/validate/options.go index f5e7f713..6a6891a6 100644 --- a/vendor/github.com/go-openapi/validate/options.go +++ b/vendor/github.com/go-openapi/validate/options.go @@ -5,7 +5,7 @@ package validate import "sync" -// Opts specifies validation options for a SpecValidator. +// Opts specifies validation options for a [SpecValidator]. // // NOTE: other options might be needed, for example a go-swagger specific mode. type Opts struct { diff --git a/vendor/github.com/go-openapi/validate/pools.go b/vendor/github.com/go-openapi/validate/pools.go index 1e734be4..c8936bd1 100644 --- a/vendor/github.com/go-openapi/validate/pools.go +++ b/vendor/github.com/go-openapi/validate/pools.go @@ -245,7 +245,7 @@ type ( ) func (p schemaValidatorsPool) BorrowValidator() *SchemaValidator { - return p.Get().(*SchemaValidator) + return p.Get().(*SchemaValidator) //nolint:forcetypeassert // pool New always returns this type } func (p schemaValidatorsPool) RedeemValidator(s *SchemaValidator) { @@ -254,7 +254,7 @@ func (p schemaValidatorsPool) RedeemValidator(s *SchemaValidator) { } func (p objectValidatorsPool) BorrowValidator() *objectValidator { - return p.Get().(*objectValidator) + return p.Get().(*objectValidator) //nolint:forcetypeassert // pool New always returns this type } func (p objectValidatorsPool) RedeemValidator(s *objectValidator) { @@ -262,7 +262,7 @@ func (p objectValidatorsPool) RedeemValidator(s *objectValidator) { } func (p sliceValidatorsPool) BorrowValidator() *schemaSliceValidator { - return p.Get().(*schemaSliceValidator) + return p.Get().(*schemaSliceValidator) //nolint:forcetypeassert // pool New always returns this type } func (p sliceValidatorsPool) RedeemValidator(s *schemaSliceValidator) { @@ -270,7 +270,7 @@ func (p sliceValidatorsPool) RedeemValidator(s *schemaSliceValidator) { } func (p itemsValidatorsPool) BorrowValidator() *itemsValidator { - return p.Get().(*itemsValidator) + return p.Get().(*itemsValidator) //nolint:forcetypeassert // pool New always returns this type } func (p itemsValidatorsPool) RedeemValidator(s *itemsValidator) { @@ -278,7 +278,7 @@ func (p itemsValidatorsPool) RedeemValidator(s *itemsValidator) { } func (p basicCommonValidatorsPool) BorrowValidator() *basicCommonValidator { - return p.Get().(*basicCommonValidator) + return p.Get().(*basicCommonValidator) //nolint:forcetypeassert // pool New always returns this type } func (p basicCommonValidatorsPool) RedeemValidator(s *basicCommonValidator) { @@ -286,7 +286,7 @@ func (p basicCommonValidatorsPool) RedeemValidator(s *basicCommonValidator) { } func (p headerValidatorsPool) BorrowValidator() *HeaderValidator { - return p.Get().(*HeaderValidator) + return p.Get().(*HeaderValidator) //nolint:forcetypeassert // pool New always returns this type } func (p headerValidatorsPool) RedeemValidator(s *HeaderValidator) { @@ -294,7 +294,7 @@ func (p headerValidatorsPool) RedeemValidator(s *HeaderValidator) { } func (p paramValidatorsPool) BorrowValidator() *ParamValidator { - return p.Get().(*ParamValidator) + return p.Get().(*ParamValidator) //nolint:forcetypeassert // pool New always returns this type } func (p paramValidatorsPool) RedeemValidator(s *ParamValidator) { @@ -302,7 +302,7 @@ func (p paramValidatorsPool) RedeemValidator(s *ParamValidator) { } func (p basicSliceValidatorsPool) BorrowValidator() *basicSliceValidator { - return p.Get().(*basicSliceValidator) + return p.Get().(*basicSliceValidator) //nolint:forcetypeassert // pool New always returns this type } func (p basicSliceValidatorsPool) RedeemValidator(s *basicSliceValidator) { @@ -310,7 +310,7 @@ func (p basicSliceValidatorsPool) RedeemValidator(s *basicSliceValidator) { } func (p numberValidatorsPool) BorrowValidator() *numberValidator { - return p.Get().(*numberValidator) + return p.Get().(*numberValidator) //nolint:forcetypeassert // pool New always returns this type } func (p numberValidatorsPool) RedeemValidator(s *numberValidator) { @@ -318,7 +318,7 @@ func (p numberValidatorsPool) RedeemValidator(s *numberValidator) { } func (p stringValidatorsPool) BorrowValidator() *stringValidator { - return p.Get().(*stringValidator) + return p.Get().(*stringValidator) //nolint:forcetypeassert // pool New always returns this type } func (p stringValidatorsPool) RedeemValidator(s *stringValidator) { @@ -326,7 +326,7 @@ func (p stringValidatorsPool) RedeemValidator(s *stringValidator) { } func (p schemaPropsValidatorsPool) BorrowValidator() *schemaPropsValidator { - return p.Get().(*schemaPropsValidator) + return p.Get().(*schemaPropsValidator) //nolint:forcetypeassert // pool New always returns this type } func (p schemaPropsValidatorsPool) RedeemValidator(s *schemaPropsValidator) { @@ -334,7 +334,7 @@ func (p schemaPropsValidatorsPool) RedeemValidator(s *schemaPropsValidator) { } func (p formatValidatorsPool) BorrowValidator() *formatValidator { - return p.Get().(*formatValidator) + return p.Get().(*formatValidator) //nolint:forcetypeassert // pool New always returns this type } func (p formatValidatorsPool) RedeemValidator(s *formatValidator) { @@ -342,7 +342,7 @@ func (p formatValidatorsPool) RedeemValidator(s *formatValidator) { } func (p typeValidatorsPool) BorrowValidator() *typeValidator { - return p.Get().(*typeValidator) + return p.Get().(*typeValidator) //nolint:forcetypeassert // pool New always returns this type } func (p typeValidatorsPool) RedeemValidator(s *typeValidator) { @@ -350,7 +350,7 @@ func (p typeValidatorsPool) RedeemValidator(s *typeValidator) { } func (p schemasPool) BorrowSchema() *spec.Schema { - return p.Get().(*spec.Schema) + return p.Get().(*spec.Schema) //nolint:forcetypeassert // pool New always returns this type } func (p schemasPool) RedeemSchema(s *spec.Schema) { @@ -358,7 +358,7 @@ func (p schemasPool) RedeemSchema(s *spec.Schema) { } func (p resultsPool) BorrowResult() *Result { - return p.Get().(*Result).cleared() + return p.Get().(*Result).cleared() //nolint:forcetypeassert // pool New always returns *Result } func (p resultsPool) RedeemResult(s *Result) { diff --git a/vendor/github.com/go-openapi/validate/result.go b/vendor/github.com/go-openapi/validate/result.go index 69219e99..ede94550 100644 --- a/vendor/github.com/go-openapi/validate/result.go +++ b/vendor/github.com/go-openapi/validate/result.go @@ -25,7 +25,7 @@ var emptyResult = &Result{MatchCount: 1} // schema validation. Results from the validation branch // with most matches get eventually selected. // -// TODO: keep path of key originating the error +// Proposal for enhancement: keep path of key originating the error. type Result struct { Errors []error Warnings []error @@ -66,7 +66,7 @@ func NewFieldKey(obj map[string]any, field string) FieldKey { // Object returns the underlying object of this key. func (fk *FieldKey) Object() map[string]any { - return fk.object.Interface().(map[string]any) + return fk.object.Interface().(map[string]any) //nolint:forcetypeassert // object is always map[string]any } // Field returns the underlying field of this key. @@ -81,7 +81,7 @@ func NewItemKey(slice any, i int) ItemKey { // Slice returns the underlying slice of this key. func (ik *ItemKey) Slice() []any { - return ik.slice.Interface().([]any) + return ik.slice.Interface().([]any) //nolint:forcetypeassert // slice is always []any } // Index returns the underlying index of this key. @@ -283,14 +283,14 @@ func (r *Result) HasErrorsOrWarnings() bool { return len(r.Errors) > 0 || len(r.Warnings) > 0 } -// Inc increments the match count +// Inc increments the match count. func (r *Result) Inc() { r.MatchCount++ } -// AsError renders this result as an error interface +// AsError renders this result as an error interface. // -// TODO: reporting / pretty print with path ordered and indented +// Proposal for enhancement: reporting / pretty print with path ordered and indented. func (r *Result) AsError() error { if r.IsValid() { return nil @@ -425,7 +425,7 @@ func stripImportantTag(err error) error { } func (r *Result) keepRelevantErrors() *Result { - // TODO: this one is going to disapear... + // NOTE: this one is going to disapear... // keepRelevantErrors strips a result from standard errors and keeps // the ones which are supposedly more accurate. // diff --git a/vendor/github.com/go-openapi/validate/rexp.go b/vendor/github.com/go-openapi/validate/rexp.go index 795f148d..478036c0 100644 --- a/vendor/github.com/go-openapi/validate/rexp.go +++ b/vendor/github.com/go-openapi/validate/rexp.go @@ -10,7 +10,7 @@ import ( "sync/atomic" ) -// Cache for compiled regular expressions +// Cache for compiled regular expressions. var ( cacheMutex = &sync.Mutex{} reDict = atomic.Value{} // map[string]*re.Regexp diff --git a/vendor/github.com/go-openapi/validate/schema.go b/vendor/github.com/go-openapi/validate/schema.go index 375a9876..b72a47bc 100644 --- a/vendor/github.com/go-openapi/validate/schema.go +++ b/vendor/github.com/go-openapi/validate/schema.go @@ -13,7 +13,7 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -// SchemaValidator validates data against a JSON schema +// SchemaValidator validates data against a JSON schema. type SchemaValidator struct { Path string in string @@ -26,7 +26,7 @@ type SchemaValidator struct { // AgainstSchema validates the specified data against the provided schema, using a registry of supported formats. // -// When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example. +// When no pre-parsed *[spec.Schema] structure is provided, it uses a JSON schema as default. See example. func AgainstSchema(schema *spec.Schema, data any, formats strfmt.Registry, options ...Option) error { res := NewSchemaValidator(schema, nil, "", formats, append(options, WithRecycleValidators(true), withRecycleResults(true))..., @@ -103,18 +103,20 @@ func newSchemaValidator(schema *spec.Schema, rootSchema any, root string, format return s } -// SetPath sets the path for this schema valdiator +// SetPath sets the path for this schema validator. func (s *SchemaValidator) SetPath(path string) { s.Path = path } -// Applies returns true when this schema validator applies +// Applies returns true when this schema validator applies. func (s *SchemaValidator) Applies(source any, _ reflect.Kind) bool { _, ok := source.(*spec.Schema) return ok } -// Validate validates the data against the schema +// Validate validates the data against the schema. +// +//nolint:gocognit // refactor in a forthcoming PR func (s *SchemaValidator) Validate(data any) *Result { if s == nil { return emptyResult @@ -176,7 +178,7 @@ func (s *SchemaValidator) Validate(data any) *Result { d = dd } - // TODO: this part should be handed over to type validator + // Proposal for enhancement: this part should be handed over to type validator // Handle special case of json.Number data (number marshalled as string) isnumber := s.Schema != nil && (s.Schema.Type.Contains(numberType) || s.Schema.Type.Contains(integerType)) if num, ok := data.(json.Number); ok && isnumber { diff --git a/vendor/github.com/go-openapi/validate/schema_messages.go b/vendor/github.com/go-openapi/validate/schema_messages.go index e8c7c48a..e0f1801e 100644 --- a/vendor/github.com/go-openapi/validate/schema_messages.go +++ b/vendor/github.com/go-openapi/validate/schema_messages.go @@ -11,57 +11,64 @@ import ( const ( // ArrayDoesNotAllowAdditionalItemsError when an additionalItems construct is not verified by the array values provided. // - // TODO: should move to package go-openapi/errors + // Proposal for enhancement: should move to package go-openapi/errors. ArrayDoesNotAllowAdditionalItemsError = "array doesn't allow for additional items" - // HasDependencyError indicates that a dependencies construct was not verified + // HasDependencyError indicates that a dependencies construct was not verified. HasDependencyError = "%q has a dependency on %s" - // InvalidSchemaProvidedError indicates that the schema provided to validate a value cannot be properly compiled + // InvalidSchemaProvidedError indicates that the schema provided to validate a value cannot be properly compiled. InvalidSchemaProvidedError = "Invalid schema provided to SchemaValidator: %v" - // InvalidTypeConversionError indicates that a numerical conversion for the given type could not be carried on + // InvalidTypeConversionError indicates that a numerical conversion for the given type could not be carried on. InvalidTypeConversionError = "invalid type conversion in %s: %v " - // MustValidateAtLeastOneSchemaError indicates that in a AnyOf construct, none of the schema constraints specified were verified + // MustValidateAtLeastOneSchemaError indicates that in a AnyOf construct, none of the schema constraints specified were verified. MustValidateAtLeastOneSchemaError = "%q must validate at least one schema (anyOf)" - // MustValidateOnlyOneSchemaError indicates that in a OneOf construct, either none of the schema constraints specified were verified, or several were + // MustValidateOnlyOneSchemaError indicates that in a OneOf construct, either none of the schema constraints specified were verified, or several were. MustValidateOnlyOneSchemaError = "%q must validate one and only one schema (oneOf). %s" - // MustValidateAllSchemasError indicates that in a AllOf construct, at least one of the schema constraints specified were not verified + // MustValidateAllSchemasError indicates that in a AllOf construct, at least one of the schema constraints specified were not verified. // - // TODO: punctuation in message + // NOTE: punctuation in message. MustValidateAllSchemasError = "%q must validate all the schemas (allOf)%s" - // MustNotValidateSchemaError indicates that in a Not construct, the schema constraint specified was verified + // MustNotValidateSchemaError indicates that in a Not construct, the schema constraint specified was verified. MustNotValidateSchemaError = "%q must not validate the schema (not)" ) -// Warning messages related to schema validation and returned as results +// Warning messages related to schema validation and returned as results. const () func invalidSchemaProvidedMsg(err error) errors.Error { return errors.New(InternalErrorCode, InvalidSchemaProvidedError, err) } + func invalidTypeConversionMsg(path string, err error) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidTypeConversionError, path, err) } + func mustValidateOnlyOneSchemaMsg(path, additionalMsg string) errors.Error { return errors.New(errors.CompositeErrorCode, MustValidateOnlyOneSchemaError, path, additionalMsg) } + func mustValidateAtLeastOneSchemaMsg(path string) errors.Error { return errors.New(errors.CompositeErrorCode, MustValidateAtLeastOneSchemaError, path) } + func mustValidateAllSchemasMsg(path, additionalMsg string) errors.Error { return errors.New(errors.CompositeErrorCode, MustValidateAllSchemasError, path, additionalMsg) } + func mustNotValidatechemaMsg(path string) errors.Error { return errors.New(errors.CompositeErrorCode, MustNotValidateSchemaError, path) } + func hasADependencyMsg(path, depkey string) errors.Error { return errors.New(errors.CompositeErrorCode, HasDependencyError, path, depkey) } + func arrayDoesNotAllowAdditionalItemsMsg() errors.Error { return errors.New(errors.CompositeErrorCode, ArrayDoesNotAllowAdditionalItemsError) } diff --git a/vendor/github.com/go-openapi/validate/schema_option.go b/vendor/github.com/go-openapi/validate/schema_option.go index d9fd21a7..3e1b882e 100644 --- a/vendor/github.com/go-openapi/validate/schema_option.go +++ b/vendor/github.com/go-openapi/validate/schema_option.go @@ -3,7 +3,7 @@ package validate -// SchemaValidatorOptions defines optional rules for schema validation +// SchemaValidatorOptions defines optional rules for schema validation. type SchemaValidatorOptions struct { EnableObjectArrayTypeCheck bool EnableArrayMustHaveItemsCheck bool @@ -12,24 +12,24 @@ type SchemaValidatorOptions struct { skipSchemataResult bool } -// Option sets optional rules for schema validation +// Option sets optional rules for schema validation. type Option func(*SchemaValidatorOptions) -// EnableObjectArrayTypeCheck activates the swagger rule: an items must be in type: array +// EnableObjectArrayTypeCheck activates the swagger rule: an items must be in type: array. func EnableObjectArrayTypeCheck(enable bool) Option { return func(svo *SchemaValidatorOptions) { svo.EnableObjectArrayTypeCheck = enable } } -// EnableArrayMustHaveItemsCheck activates the swagger rule: an array must have items defined +// EnableArrayMustHaveItemsCheck activates the swagger rule: an array must have items defined. func EnableArrayMustHaveItemsCheck(enable bool) Option { return func(svo *SchemaValidatorOptions) { svo.EnableArrayMustHaveItemsCheck = enable } } -// SwaggerSchema activates swagger schema validation rules +// SwaggerSchema activates swagger schema validation rules. func SwaggerSchema(enable bool) Option { return func(svo *SchemaValidatorOptions) { svo.EnableObjectArrayTypeCheck = enable @@ -53,14 +53,14 @@ func withRecycleResults(enable bool) Option { } } -// WithSkipSchemataResult skips the deep audit payload stored in validation Result +// WithSkipSchemataResult skips the deep audit payload stored in validation Result. func WithSkipSchemataResult(enable bool) Option { return func(svo *SchemaValidatorOptions) { svo.skipSchemataResult = enable } } -// Options returns the current set of options +// Options returns the current set of options. func (svo SchemaValidatorOptions) Options() []Option { return []Option{ EnableObjectArrayTypeCheck(svo.EnableObjectArrayTypeCheck), diff --git a/vendor/github.com/go-openapi/validate/schema_props.go b/vendor/github.com/go-openapi/validate/schema_props.go index 485f536a..2c4354d0 100644 --- a/vendor/github.com/go-openapi/validate/schema_props.go +++ b/vendor/github.com/go-openapi/validate/schema_props.go @@ -34,7 +34,8 @@ func (s *schemaPropsValidator) SetPath(path string) { func newSchemaPropsValidator( path string, in string, allOf, oneOf, anyOf []spec.Schema, not *spec.Schema, deps spec.Dependencies, root any, formats strfmt.Registry, - opts *SchemaValidatorOptions) *schemaPropsValidator { + opts *SchemaValidatorOptions, +) *schemaPropsValidator { if opts == nil { opts = new(SchemaValidatorOptions) } @@ -281,7 +282,7 @@ func (s *schemaPropsValidator) validateNot(data any, mainResult *Result) { } func (s *schemaPropsValidator) validateDependencies(data any, mainResult *Result) { - val := data.(map[string]any) + val := data.(map[string]any) //nolint:forcetypeassert // caller guarantees map[string]any for key := range val { dep, ok := s.Dependencies[key] if !ok { diff --git a/vendor/github.com/go-openapi/validate/slice_validator.go b/vendor/github.com/go-openapi/validate/slice_validator.go index 4a5a2089..8f49d137 100644 --- a/vendor/github.com/go-openapi/validate/slice_validator.go +++ b/vendor/github.com/go-openapi/validate/slice_validator.go @@ -27,7 +27,8 @@ type schemaSliceValidator struct { func newSliceValidator(path, in string, maxItems, minItems *int64, uniqueItems bool, additionalItems *spec.SchemaOrBool, items *spec.SchemaOrArray, - root any, formats strfmt.Registry, opts *SchemaValidatorOptions) *schemaSliceValidator { + root any, formats strfmt.Registry, opts *SchemaValidatorOptions, +) *schemaSliceValidator { if opts == nil { opts = new(SchemaValidatorOptions) } diff --git a/vendor/github.com/go-openapi/validate/spec.go b/vendor/github.com/go-openapi/validate/spec.go index 8616a861..b85432f9 100644 --- a/vendor/github.com/go-openapi/validate/spec.go +++ b/vendor/github.com/go-openapi/validate/spec.go @@ -25,16 +25,16 @@ import ( // // Returns an error flattening in a single standard error, all validation messages. // -// - TODO: $ref should not have siblings -// - TODO: make sure documentation reflects all checks and warnings -// - TODO: check on discriminators -// - TODO: explicit message on unsupported keywords (better than "forbidden property"...) -// - TODO: full list of unresolved refs -// - TODO: validate numeric constraints (issue#581): this should be handled like defaults and examples -// - TODO: option to determine if we validate for go-swagger or in a more general context -// - TODO: check on required properties to support anyOf, allOf, oneOf +// - Proposal for enhancement: $ref should not have siblings +// - Proposal for enhancement: make sure documentation reflects all checks and warnings +// - Proposal for enhancement: check on discriminators +// - Proposal for enhancement: explicit message on unsupported keywords (better than "forbidden property"...) +// - Proposal for enhancement: full list of unresolved refs +// - Proposal for enhancement: validate numeric constraints (issue#581): this should be handled like defaults and examples +// - Proposal for enhancement: option to determine if we validate for go-swagger or in a more general context +// - Proposal for enhancement: check on required properties to support anyOf, allOf, oneOf // -// NOTE: SecurityScopes are maps: no need to check uniqueness +// NOTE: SecurityScopes are maps: no need to check uniqueness. func Spec(doc *loads.Document, formats strfmt.Registry) error { errs, _ /*warns*/ := NewSpecValidator(doc.Schema(), formats).Validate(doc) if errs.HasErrors() { @@ -43,7 +43,7 @@ func Spec(doc *loads.Document, formats strfmt.Registry) error { return nil } -// SpecValidator validates a swagger 2.0 spec +// SpecValidator validates a swagger 2.0 spec. type SpecValidator struct { schema *spec.Schema // swagger 2.0 schema spec *loads.Document @@ -54,7 +54,7 @@ type SpecValidator struct { schemaOptions *SchemaValidatorOptions } -// NewSpecValidator creates a new swagger spec validator instance +// NewSpecValidator creates a new swagger spec validator instance. func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidator { // schema options that apply to all called validators schemaOptions := new(SchemaValidatorOptions) @@ -74,7 +74,7 @@ func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidat } } -// Validate validates the swagger spec +// Validate validates the swagger spec. func (s *SpecValidator) Validate(data any) (*Result, *Result) { s.schemaOptions.skipSchemataResult = s.Options.SkipSchemataResult var sd *loads.Document @@ -347,6 +347,7 @@ func (s *SpecValidator) validateCircularAncestry(nm string, sch spec.Schema, kno return ancs, res } +//nolint:gocognit // refactor in a forthcoming PR func (s *SpecValidator) validateItems() *Result { // validate parameter, items, schema and response objects for presence of item if type is array res := pools.poolOfResults.BorrowResult() @@ -406,7 +407,7 @@ func (s *SpecValidator) validateItems() *Result { return res } -// Verifies constraints on array type +// Verifies constraints on array type. func (s *SpecValidator) validateSchemaItems(schema spec.Schema, prefix, opID string) *Result { res := pools.poolOfResults.BorrowResult() if !schema.Type.Contains(arrayType) { @@ -597,7 +598,7 @@ func (s *SpecValidator) validateRequiredProperties(path, in string, v *spec.Sche } else if v.AdditionalProperties.Schema != nil { // additionalProperties as schema are upported in swagger // recursively validates additionalProperties schema - // TODO : anyOf, allOf, oneOf like in schemaPropsValidator + // Proposal for enhancement: anyOf, allOf, oneOf like in schemaPropsValidator red := s.validateRequiredProperties(path, in, v.AdditionalProperties.Schema) if red.IsValid() { additionalPropertiesMatch = true @@ -620,6 +621,7 @@ func (s *SpecValidator) validateRequiredProperties(path, in string, v *spec.Sche return res } +//nolint:gocognit // refactor in a forthcoming PR func (s *SpecValidator) validateParameters() *Result { // - for each method, path is unique, regardless of path parameters // e.g. GET:/petstore/{id}, GET:/petstore/{pet}, GET:/petstore are @@ -645,7 +647,6 @@ func (s *SpecValidator) validateParameters() *Result { // Check uniqueness of stripped paths if _, found := methodPaths[method][pathToAdd]; found { - // Sort names for stable, testable output if strings.Compare(path, methodPaths[method][pathToAdd]) < 0 { res.AddErrors(pathOverlapMsg(path, methodPaths[method][pathToAdd])) @@ -666,7 +667,7 @@ func (s *SpecValidator) validateParameters() *Result { var hasForm, hasBody bool // Check parameters names uniqueness for operation - // TODO: should be done after param expansion + // NOTE: should be done after param expansion res.Merge(s.checkUniqueParams(path, method, op)) // pick the root schema from the swagger specification which describes a parameter diff --git a/vendor/github.com/go-openapi/validate/spec_messages.go b/vendor/github.com/go-openapi/validate/spec_messages.go index 9b079af6..42ce3602 100644 --- a/vendor/github.com/go-openapi/validate/spec_messages.go +++ b/vendor/github.com/go-openapi/validate/spec_messages.go @@ -20,25 +20,25 @@ const ( // ArrayInHeaderRequiresItemsError ... ArrayInHeaderRequiresItemsError = "header %q for %q is a collection without an element type (array requires items definition)" - // BothFormDataAndBodyError indicates that an operation specifies both a body and a formData parameter, which is forbidden + // BothFormDataAndBodyError indicates that an operation specifies both a body and a formData parameter, which is forbidden. BothFormDataAndBodyError = "operation %q has both formData and body parameters. Only one such In: type may be used for a given operation" - // CannotResolveReferenceError when a $ref could not be resolved + // CannotResolveReferenceError when a $ref could not be resolved. CannotResolveReferenceError = "could not resolve reference in %s to $ref %s: %v" // CircularAncestryDefinitionError ... CircularAncestryDefinitionError = "definition %q has circular ancestry: %v" - // DefaultValueDoesNotValidateError results from an invalid default value provided + // DefaultValueDoesNotValidateError results from an invalid default value provided. DefaultValueDoesNotValidateError = "default value for %s in %s does not validate its schema" - // DefaultValueItemsDoesNotValidateError results from an invalid default value provided for Items + // DefaultValueItemsDoesNotValidateError results from an invalid default value provided for Items. DefaultValueItemsDoesNotValidateError = "default value for %s.items in %s does not validate its schema" - // DefaultValueHeaderDoesNotValidateError results from an invalid default value provided in header + // DefaultValueHeaderDoesNotValidateError results from an invalid default value provided in header. DefaultValueHeaderDoesNotValidateError = "in operation %q, default value in header %s for %s does not validate its schema" - // DefaultValueHeaderItemsDoesNotValidateError results from an invalid default value provided in header.items + // DefaultValueHeaderItemsDoesNotValidateError results from an invalid default value provided in header.items. DefaultValueHeaderItemsDoesNotValidateError = "in operation %q, default value in header.items %s for %s does not validate its schema" // DefaultValueInDoesNotValidateError ... @@ -50,31 +50,31 @@ const ( // DuplicatePropertiesError ... DuplicatePropertiesError = "definition %q contains duplicate properties: %v" - // ExampleValueDoesNotValidateError results from an invalid example value provided + // ExampleValueDoesNotValidateError results from an invalid example value provided. ExampleValueDoesNotValidateError = "example value for %s in %s does not validate its schema" - // ExampleValueItemsDoesNotValidateError results from an invalid example value provided for Items + // ExampleValueItemsDoesNotValidateError results from an invalid example value provided for Items. ExampleValueItemsDoesNotValidateError = "example value for %s.items in %s does not validate its schema" - // ExampleValueHeaderDoesNotValidateError results from an invalid example value provided in header + // ExampleValueHeaderDoesNotValidateError results from an invalid example value provided in header. ExampleValueHeaderDoesNotValidateError = "in operation %q, example value in header %s for %s does not validate its schema" - // ExampleValueHeaderItemsDoesNotValidateError results from an invalid example value provided in header.items + // ExampleValueHeaderItemsDoesNotValidateError results from an invalid example value provided in header.items. ExampleValueHeaderItemsDoesNotValidateError = "in operation %q, example value in header.items %s for %s does not validate its schema" // ExampleValueInDoesNotValidateError ... ExampleValueInDoesNotValidateError = "in operation %q, example value in %s does not validate its schema" - // EmptyPathParameterError means that a path parameter was found empty (e.g. "{}") + // EmptyPathParameterError means that a path parameter was found empty (e.g. "{}"). EmptyPathParameterError = "%q contains an empty path parameter" - // InvalidDocumentError states that spec validation only processes spec.Document objects + // InvalidDocumentError states that spec validation only processes spec.Document objects. InvalidDocumentError = "spec validator can only validate spec.Document objects" - // InvalidItemsPatternError indicates an Items definition with invalid pattern + // InvalidItemsPatternError indicates an Items definition with invalid pattern. InvalidItemsPatternError = "%s for %q has invalid items pattern: %q" - // InvalidParameterDefinitionError indicates an error detected on a parameter definition + // InvalidParameterDefinitionError indicates an error detected on a parameter definition. InvalidParameterDefinitionError = "invalid definition for parameter %s in %s in operation %q" // InvalidParameterDefinitionAsSchemaError indicates an error detected on a parameter definition, which was mistaken with a schema definition. @@ -84,41 +84,41 @@ const ( // InvalidPatternError ... InvalidPatternError = "pattern %q is invalid in %s" - // InvalidPatternInError indicates an invalid pattern in a schema or items definition + // InvalidPatternInError indicates an invalid pattern in a schema or items definition. InvalidPatternInError = "%s in %s has invalid pattern: %q" - // InvalidPatternInHeaderError indicates a header definition with an invalid pattern + // InvalidPatternInHeaderError indicates a header definition with an invalid pattern. InvalidPatternInHeaderError = "in operation %q, header %s for %s has invalid pattern %q: %v" // InvalidPatternInParamError ... InvalidPatternInParamError = "operation %q has invalid pattern in param %q: %q" - // InvalidReferenceError indicates that a $ref property could not be resolved + // InvalidReferenceError indicates that a $ref property could not be resolved. InvalidReferenceError = "invalid ref %q" // InvalidResponseDefinitionAsSchemaError indicates an error detected on a response definition, which was mistaken with a schema definition. // Most likely, this situation is encountered whenever a $ref has been added as a sibling of the response definition. InvalidResponseDefinitionAsSchemaError = "invalid definition as Schema for response %s in %s" - // MultipleBodyParamError indicates that an operation specifies multiple parameter with in: body + // MultipleBodyParamError indicates that an operation specifies multiple parameter with in: body. MultipleBodyParamError = "operation %q has more than 1 body param: %v" - // NonUniqueOperationIDError indicates that the same operationId has been specified several times + // NonUniqueOperationIDError indicates that the same operationId has been specified several times. NonUniqueOperationIDError = "%q is defined %d times" - // NoParameterInPathError indicates that a path was found without any parameter + // NoParameterInPathError indicates that a path was found without any parameter. NoParameterInPathError = "path param %q has no parameter definition" // NoValidPathErrorOrWarning indicates that no single path could be validated. If Paths is empty, this message is only a warning. NoValidPathErrorOrWarning = "spec has no valid path defined" - // NoValidResponseError indicates that no valid response description could be found for an operation + // NoValidResponseError indicates that no valid response description could be found for an operation. NoValidResponseError = "operation %q has no valid response" // PathOverlapError ... PathOverlapError = "path %s overlaps with %s" - // PathParamNotInPathError indicates that a parameter specified with in: path was not found in the path specification + // PathParamNotInPathError indicates that a parameter specified with in: path was not found in the path specification. PathParamNotInPathError = "path param %q is not present in path %q" // PathParamNotUniqueError ... @@ -127,32 +127,32 @@ const ( // PathParamRequiredError ... PathParamRequiredError = "in operation %q,path param %q must be declared as required" - // RefNotAllowedInHeaderError indicates a $ref was found in a header definition, which is not allowed by Swagger + // RefNotAllowedInHeaderError indicates a $ref was found in a header definition, which is not allowed by Swagger. RefNotAllowedInHeaderError = "IMPORTANT!in %q: $ref are not allowed in headers. In context for header %q%s" // RequiredButNotDefinedError ... RequiredButNotDefinedError = "%q is present in required but not defined as property in definition %q" - // SomeParametersBrokenError indicates that some parameters could not be resolved, which might result in partial checks to be carried on + // SomeParametersBrokenError indicates that some parameters could not be resolved, which might result in partial checks to be carried on. SomeParametersBrokenError = "some parameters definitions are broken in %q.%s. Cannot carry on full checks on parameters for operation %s" - // UnresolvedReferencesError indicates that at least one $ref could not be resolved + // UnresolvedReferencesError indicates that at least one $ref could not be resolved. UnresolvedReferencesError = "some references could not be resolved in spec. First found: %v" ) -// Warning messages related to spec validation and returned as results +// Warning messages related to spec validation and returned as results. const ( - // ExamplesWithoutSchemaWarning indicates that examples are provided for a response,but not schema to validate the example against + // ExamplesWithoutSchemaWarning indicates that examples are provided for a response,but not schema to validate the example against. ExamplesWithoutSchemaWarning = "Examples provided without schema in operation %q, %s" // ExamplesMimeNotSupportedWarning indicates that examples are provided with a mime type different than application/json, which - // the validator dos not support yetl + // the validator dos not support yetl. ExamplesMimeNotSupportedWarning = "No validation attempt for examples for media types other than application/json, in operation %q, %s" // PathParamGarbledWarning ... PathParamGarbledWarning = "in path %q, param %q contains {,} or white space. Albeit not stricly illegal, this is probably no what you want" - // ParamValidationTypeMismatch indicates that parameter has validation which does not match its type + // ParamValidationTypeMismatch indicates that parameter has validation which does not match its type. ParamValidationTypeMismatch = "validation keywords of parameter %q in path %q don't match its type %s" // PathStrippedParamGarbledWarning ... @@ -165,7 +165,7 @@ const ( // which is most likely not wanted. RefShouldNotHaveSiblingsWarning = "$ref property should have no sibling in %q.%s" - // RequiredHasDefaultWarning indicates that a required parameter property should not have a default + // RequiredHasDefaultWarning indicates that a required parameter property should not have a default. RequiredHasDefaultWarning = "%s in %s has a default value and is required as parameter" // UnusedDefinitionWarning ... @@ -180,164 +180,214 @@ const ( InvalidObject = "expected an object in %q.%s" ) -// Additional error codes +// Additional error codes. const ( - // InternalErrorCode reports an internal technical error + // InternalErrorCode reports an internal technical error. InternalErrorCode = http.StatusInternalServerError - // NotFoundErrorCode indicates that a resource (e.g. a $ref) could not be found + // NotFoundErrorCode indicates that a resource (e.g. a $ref) could not be found. NotFoundErrorCode = http.StatusNotFound ) func invalidDocumentMsg() errors.Error { return errors.New(InternalErrorCode, InvalidDocumentError) } + func invalidRefMsg(path string) errors.Error { return errors.New(NotFoundErrorCode, InvalidReferenceError, path) } + func unresolvedReferencesMsg(err error) errors.Error { return errors.New(errors.CompositeErrorCode, UnresolvedReferencesError, err) } + func noValidPathMsg() errors.Error { return errors.New(errors.CompositeErrorCode, NoValidPathErrorOrWarning) } + func emptyPathParameterMsg(path string) errors.Error { return errors.New(errors.CompositeErrorCode, EmptyPathParameterError, path) } + func nonUniqueOperationIDMsg(path string, i int) errors.Error { return errors.New(errors.CompositeErrorCode, NonUniqueOperationIDError, path, i) } + func circularAncestryDefinitionMsg(path string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, CircularAncestryDefinitionError, path, args) } + func duplicatePropertiesMsg(path string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, DuplicatePropertiesError, path, args) } + func pathParamNotInPathMsg(path, param string) errors.Error { return errors.New(errors.CompositeErrorCode, PathParamNotInPathError, param, path) } + func arrayRequiresItemsMsg(path, operation string) errors.Error { return errors.New(errors.CompositeErrorCode, ArrayRequiresItemsError, path, operation) } + func arrayInParamRequiresItemsMsg(path, operation string) errors.Error { return errors.New(errors.CompositeErrorCode, ArrayInParamRequiresItemsError, path, operation) } + func arrayInHeaderRequiresItemsMsg(path, operation string) errors.Error { return errors.New(errors.CompositeErrorCode, ArrayInHeaderRequiresItemsError, path, operation) } + func invalidItemsPatternMsg(path, operation, pattern string) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidItemsPatternError, path, operation, pattern) } + func invalidPatternMsg(pattern, path string) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidPatternError, pattern, path) } + func requiredButNotDefinedMsg(path, definition string) errors.Error { return errors.New(errors.CompositeErrorCode, RequiredButNotDefinedError, path, definition) } + func pathParamGarbledMsg(path, param string) errors.Error { return errors.New(errors.CompositeErrorCode, PathParamGarbledWarning, path, param) } + func pathStrippedParamGarbledMsg(path string) errors.Error { return errors.New(errors.CompositeErrorCode, PathStrippedParamGarbledWarning, path) } + func pathOverlapMsg(path, arg string) errors.Error { return errors.New(errors.CompositeErrorCode, PathOverlapError, path, arg) } + func invalidPatternInParamMsg(operation, param, pattern string) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidPatternInParamError, operation, param, pattern) } + func pathParamRequiredMsg(operation, param string) errors.Error { return errors.New(errors.CompositeErrorCode, PathParamRequiredError, operation, param) } + func bothFormDataAndBodyMsg(operation string) errors.Error { return errors.New(errors.CompositeErrorCode, BothFormDataAndBodyError, operation) } + func multipleBodyParamMsg(operation string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, MultipleBodyParamError, operation, args) } + func pathParamNotUniqueMsg(path, param, arg string) errors.Error { return errors.New(errors.CompositeErrorCode, PathParamNotUniqueError, path, param, arg) } + func duplicateParamNameMsg(path, param, operation string) errors.Error { return errors.New(errors.CompositeErrorCode, DuplicateParamNameError, param, path, operation) } + func unusedParamMsg(arg string) errors.Error { return errors.New(errors.CompositeErrorCode, UnusedParamWarning, arg) } + func unusedDefinitionMsg(arg string) errors.Error { return errors.New(errors.CompositeErrorCode, UnusedDefinitionWarning, arg) } + func unusedResponseMsg(arg string) errors.Error { return errors.New(errors.CompositeErrorCode, UnusedResponseWarning, arg) } + func readOnlyAndRequiredMsg(path, param string) errors.Error { return errors.New(errors.CompositeErrorCode, ReadOnlyAndRequiredWarning, param, path) } + func noParameterInPathMsg(param string) errors.Error { return errors.New(errors.CompositeErrorCode, NoParameterInPathError, param) } + func requiredHasDefaultMsg(param, path string) errors.Error { return errors.New(errors.CompositeErrorCode, RequiredHasDefaultWarning, param, path) } + func defaultValueDoesNotValidateMsg(param, path string) errors.Error { return errors.New(errors.CompositeErrorCode, DefaultValueDoesNotValidateError, param, path) } + func defaultValueItemsDoesNotValidateMsg(param, path string) errors.Error { return errors.New(errors.CompositeErrorCode, DefaultValueItemsDoesNotValidateError, param, path) } + func noValidResponseMsg(operation string) errors.Error { return errors.New(errors.CompositeErrorCode, NoValidResponseError, operation) } + func defaultValueHeaderDoesNotValidateMsg(operation, header, path string) errors.Error { return errors.New(errors.CompositeErrorCode, DefaultValueHeaderDoesNotValidateError, operation, header, path) } + func defaultValueHeaderItemsDoesNotValidateMsg(operation, header, path string) errors.Error { return errors.New(errors.CompositeErrorCode, DefaultValueHeaderItemsDoesNotValidateError, operation, header, path) } + func invalidPatternInHeaderMsg(operation, header, path, pattern string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidPatternInHeaderError, operation, header, path, pattern, args) } + func invalidPatternInMsg(path, in, pattern string) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidPatternInError, path, in, pattern) } + func defaultValueInDoesNotValidateMsg(operation, path string) errors.Error { return errors.New(errors.CompositeErrorCode, DefaultValueInDoesNotValidateError, operation, path) } + func exampleValueDoesNotValidateMsg(param, path string) errors.Error { return errors.New(errors.CompositeErrorCode, ExampleValueDoesNotValidateError, param, path) } + func exampleValueItemsDoesNotValidateMsg(param, path string) errors.Error { return errors.New(errors.CompositeErrorCode, ExampleValueItemsDoesNotValidateError, param, path) } + func exampleValueHeaderDoesNotValidateMsg(operation, header, path string) errors.Error { return errors.New(errors.CompositeErrorCode, ExampleValueHeaderDoesNotValidateError, operation, header, path) } + func exampleValueHeaderItemsDoesNotValidateMsg(operation, header, path string) errors.Error { return errors.New(errors.CompositeErrorCode, ExampleValueHeaderItemsDoesNotValidateError, operation, header, path) } + func exampleValueInDoesNotValidateMsg(operation, path string) errors.Error { return errors.New(errors.CompositeErrorCode, ExampleValueInDoesNotValidateError, operation, path) } + func examplesWithoutSchemaMsg(operation, response string) errors.Error { return errors.New(errors.CompositeErrorCode, ExamplesWithoutSchemaWarning, operation, response) } + func examplesMimeNotSupportedMsg(operation, response string) errors.Error { return errors.New(errors.CompositeErrorCode, ExamplesMimeNotSupportedWarning, operation, response) } + func refNotAllowedInHeaderMsg(path, header, ref string) errors.Error { return errors.New(errors.CompositeErrorCode, RefNotAllowedInHeaderError, path, header, ref) } + func cannotResolveRefMsg(path, ref string, err error) errors.Error { return errors.New(errors.CompositeErrorCode, CannotResolveReferenceError, path, ref, err) } + func invalidParameterDefinitionMsg(path, method, operationID string) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidParameterDefinitionError, path, method, operationID) } + func invalidParameterDefinitionAsSchemaMsg(path, method, operationID string) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidParameterDefinitionAsSchemaError, path, method, operationID) } + func parameterValidationTypeMismatchMsg(param, path, typ string) errors.Error { return errors.New(errors.CompositeErrorCode, ParamValidationTypeMismatch, param, path, typ) } + func invalidObjectMsg(path, in string) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidObject, path, in) } @@ -350,6 +400,7 @@ func invalidObjectMsg(path, in string) errors.Error { func someParametersBrokenMsg(path, method, operationID string) errors.Error { return errors.New(errors.CompositeErrorCode, SomeParametersBrokenError, path, method, operationID) } + func refShouldNotHaveSiblingsMsg(path, operationID string) errors.Error { return errors.New(errors.CompositeErrorCode, RefShouldNotHaveSiblingsWarning, operationID, path) } diff --git a/vendor/github.com/go-openapi/validate/type.go b/vendor/github.com/go-openapi/validate/type.go index 9b9ab8d9..d29574c3 100644 --- a/vendor/github.com/go-openapi/validate/type.go +++ b/vendor/github.com/go-openapi/validate/type.go @@ -71,7 +71,7 @@ func (t *typeValidator) Validate(data any) *Result { if data == nil { // nil or zero value for the passed structure require Type: null - if len(t.Type) > 0 && !t.Type.Contains(nullType) && !t.Nullable { // TODO: if a property is not required it also passes this + if len(t.Type) > 0 && !t.Type.Contains(nullType) && !t.Nullable { // NOTE: if a property is not required it also passes this return errorHelp.sErr(errors.InvalidType(t.Path, t.In, strings.Join(t.Type, ","), nullType), t.Options.recycleResult) } @@ -86,15 +86,18 @@ func (t *typeValidator) Validate(data any) *Result { schType, format := t.schemaInfoForType(data) // check numerical types - // TODO: check unsigned ints - // TODO: check json.Number (see schema.go) + // Proposal for enhancement: check unsigned ints + // Proposal for enhancement: check json.Number (see schema.go) isLowerInt := t.Format == integerFormatInt64 && format == integerFormatInt32 isLowerFloat := t.Format == numberFormatFloat64 && format == numberFormatFloat32 isFloatInt := schType == numberType && conv.IsFloat64AJSONInteger(val.Float()) && t.Type.Contains(integerType) isIntFloat := schType == integerType && t.Type.Contains(numberType) - if kind != reflect.String && kind != reflect.Slice && t.Format != "" && !t.Type.Contains(schType) && format != t.Format && !isFloatInt && !isIntFloat && !isLowerInt && !isLowerFloat { - // TODO: test case + formatMismatch := kind != reflect.String && kind != reflect.Slice && + t.Format != "" && !t.Type.Contains(schType) && format != t.Format && + !isFloatInt && !isIntFloat && !isLowerInt && !isLowerFloat + if formatMismatch { + // NOTE: test case return errorHelp.sErr(errors.InvalidType(t.Path, t.In, t.Format, format), t.Options.recycleResult) } @@ -112,7 +115,7 @@ func (t *typeValidator) Validate(data any) *Result { func (t *typeValidator) schemaInfoForType(data any) (string, string) { // internal type to JSON type with swagger 2.0 format (with go-openapi/strfmt extensions), // see https://github.com/go-openapi/strfmt/blob/master/README.md - // TODO: this switch really is some sort of reverse lookup for formats. It should be provided by strfmt. + // NOTE: this switch really is some sort of reverse lookup for formats. It should be provided by strfmt. switch data.(type) { case []byte, strfmt.Base64, *strfmt.Base64: return stringType, stringFormatByte @@ -162,8 +165,8 @@ func (t *typeValidator) schemaInfoForType(data any) (string, string) { return stringType, stringFormatUUID4 case strfmt.UUID5, *strfmt.UUID5: return stringType, stringFormatUUID5 - // TODO: missing binary (io.ReadCloser) - // TODO: missing json.Number + // Proposal for enhancement: missing binary (io.ReadCloser) + // Proposal for enhancement: missing json.Number default: val := reflect.ValueOf(data) tpe := val.Type() diff --git a/vendor/github.com/go-openapi/validate/update-fixtures.sh b/vendor/github.com/go-openapi/validate/update-fixtures.sh index 21b06e2b..8ee55ca3 100644 --- a/vendor/github.com/go-openapi/validate/update-fixtures.sh +++ b/vendor/github.com/go-openapi/validate/update-fixtures.sh @@ -1,4 +1,6 @@ -#!/bin/bash +#!/bin/bash +# SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +# SPDX-License-Identifier: Apache-2.0 set -eu -o pipefail dir=$(git rev-parse --show-toplevel) diff --git a/vendor/github.com/go-openapi/validate/validator.go b/vendor/github.com/go-openapi/validate/validator.go index 289a847f..e7aebc52 100644 --- a/vendor/github.com/go-openapi/validate/validator.go +++ b/vendor/github.com/go-openapi/validate/validator.go @@ -12,15 +12,15 @@ import ( "github.com/go-openapi/strfmt" ) -// An EntityValidator is an interface for things that can validate entities +// An EntityValidator is an interface for things that can validate entities. type EntityValidator interface { - Validate(any) *Result + Validate(data any) *Result } type valueValidator interface { SetPath(path string) - Applies(any, reflect.Kind) bool - Validate(any) *Result + Applies(source any, kind reflect.Kind) bool + Validate(data any) *Result } type itemsValidator struct { @@ -286,7 +286,7 @@ func (b *basicCommonValidator) redeem() { pools.poolOfBasicCommonValidators.RedeemValidator(b) } -// A HeaderValidator has very limited subset of validations to apply +// A HeaderValidator has very limited subset of validations to apply. type HeaderValidator struct { name string header *spec.Header @@ -295,7 +295,7 @@ type HeaderValidator struct { Options *SchemaValidatorOptions } -// NewHeaderValidator creates a new header validator object +// NewHeaderValidator creates a new header validator object. func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry, options ...Option) *HeaderValidator { opts := new(SchemaValidatorOptions) for _, o := range options { @@ -340,7 +340,7 @@ func newHeaderValidator(name string, header *spec.Header, formats strfmt.Registr return p } -// Validate the value of the header against its schema +// Validate the value of the header against its schema. func (p *HeaderValidator) Validate(data any) *Result { if p.Options.recycleValidators { defer func() { @@ -479,7 +479,7 @@ func (p *HeaderValidator) redeemChildren() { } } -// A ParamValidator has very limited subset of validations to apply +// A ParamValidator has very limited subset of validations to apply. type ParamValidator struct { param *spec.Parameter validators [6]valueValidator @@ -487,7 +487,7 @@ type ParamValidator struct { Options *SchemaValidatorOptions } -// NewParamValidator creates a new param validator object +// NewParamValidator creates a new param validator object. func NewParamValidator(param *spec.Parameter, formats strfmt.Registry, options ...Option) *ParamValidator { opts := new(SchemaValidatorOptions) for _, o := range options { @@ -531,7 +531,7 @@ func newParamValidator(param *spec.Parameter, formats strfmt.Registry, opts *Sch return p } -// Validate the data against the description of the parameter +// Validate the data against the description of the parameter. func (p *ParamValidator) Validate(data any) *Result { if data == nil { return nil @@ -554,7 +554,7 @@ func (p *ParamValidator) Validate(data any) *Result { }() } - // TODO: validate type + // Proposal for enhancement: validate type for idx, validator := range p.validators { if !validator.Applies(p.param, kind) { if p.Options.recycleValidators { @@ -688,7 +688,8 @@ func newBasicSliceValidator( path, in string, def any, maxItems, minItems *int64, uniqueItems bool, items *spec.Items, source any, formats strfmt.Registry, - opts *SchemaValidatorOptions) *basicSliceValidator { + opts *SchemaValidatorOptions, +) *basicSliceValidator { if opts == nil { opts = new(SchemaValidatorOptions) } @@ -797,7 +798,8 @@ func newNumberValidator( path, in string, def any, multipleOf, maximum *float64, exclusiveMaximum bool, minimum *float64, exclusiveMinimum bool, typ, format string, - opts *SchemaValidatorOptions) *numberValidator { + opts *SchemaValidatorOptions, +) *numberValidator { if opts == nil { opts = new(SchemaValidatorOptions) } @@ -857,9 +859,9 @@ func (n *numberValidator) Applies(source any, kind reflect.Kind) bool { // // If this is the case, replace AddErrors() by AddWarnings() and IsValid() by !HasWarnings(). // -// TODO: consider replacing boundary check errors by simple warnings. +// Proposal for enhancement: consider replacing boundary check errors by simple warnings. // -// TODO: default boundaries with MAX_SAFE_INTEGER are not checked (specific to json.Number?) +// NOTE: default boundaries with MAX_SAFE_INTEGER are not checked (specific to json.Number?) func (n *numberValidator) Validate(val any) *Result { if n.Options.recycleValidators { defer func() { @@ -959,7 +961,8 @@ type stringValidator struct { func newStringValidator( path, in string, def any, required, allowEmpty bool, maxLength, minLength *int64, pattern string, - opts *SchemaValidatorOptions) *stringValidator { + opts *SchemaValidatorOptions, +) *stringValidator { if opts == nil { opts = new(SchemaValidatorOptions) } diff --git a/vendor/github.com/go-openapi/validate/values.go b/vendor/github.com/go-openapi/validate/values.go index e7dd5c8d..2b80766b 100644 --- a/vendor/github.com/go-openapi/validate/values.go +++ b/vendor/github.com/go-openapi/validate/values.go @@ -21,15 +21,15 @@ func (e valueError) Error() string { return string(e) } -// ErrValue indicates that a value validation occurred +// ErrValue indicates that a value validation occurred. const ErrValue valueError = "value validation error" -// Enum validates if the data is a member of the enum +// Enum validates if the data is a member of the enum. func Enum(path, in string, data any, enum any) *errors.Validation { return EnumCase(path, in, data, enum, true) } -// EnumCase validates if the data is a member of the enum and may respect case-sensitivity for strings +// EnumCase validates if the data is a member of the enum and may respect case-sensitivity for strings. func EnumCase(path, in string, data any, enum any, caseSensitive bool) *errors.Validation { val := reflect.ValueOf(enum) if val.Kind() != reflect.Slice { @@ -66,7 +66,7 @@ func EnumCase(path, in string, data any, enum any, caseSensitive bool) *errors.V return errors.EnumFail(path, in, data, values) } -// convertEnumCaseStringKind converts interface if it is kind of string and case insensitivity is set +// convertEnumCaseStringKind converts interface if it is kind of string and case insensitivity is set. func convertEnumCaseStringKind(value any, caseSensitive bool) *string { if caseSensitive { return nil @@ -81,7 +81,7 @@ func convertEnumCaseStringKind(value any, caseSensitive bool) *string { return &str } -// MinItems validates that there are at least n items in a slice +// MinItems validates that there are at least n items in a slice. func MinItems(path, in string, size, minimum int64) *errors.Validation { if size < minimum { return errors.TooFewItems(path, in, minimum, size) @@ -89,7 +89,7 @@ func MinItems(path, in string, size, minimum int64) *errors.Validation { return nil } -// MaxItems validates that there are at most n items in a slice +// MaxItems validates that there are at most n items in a slice. func MaxItems(path, in string, size, maximum int64) *errors.Validation { if size > maximum { return errors.TooManyItems(path, in, maximum, size) @@ -97,7 +97,7 @@ func MaxItems(path, in string, size, maximum int64) *errors.Validation { return nil } -// UniqueItems validates that the provided slice has unique elements +// UniqueItems validates that the provided slice has unique elements. func UniqueItems(path, in string, data any) *errors.Validation { val := reflect.ValueOf(data) if val.Kind() != reflect.Slice { @@ -116,7 +116,7 @@ func UniqueItems(path, in string, data any) *errors.Validation { return nil } -// MinLength validates a string for minimum length +// MinLength validates a string for minimum length. func MinLength(path, in, data string, minLength int64) *errors.Validation { strLen := int64(utf8.RuneCountInString(data)) if strLen < minLength { @@ -125,7 +125,7 @@ func MinLength(path, in, data string, minLength int64) *errors.Validation { return nil } -// MaxLength validates a string for maximum length +// MaxLength validates a string for maximum length. func MaxLength(path, in, data string, maxLength int64) *errors.Validation { strLen := int64(utf8.RuneCountInString(data)) if strLen > maxLength { @@ -134,9 +134,8 @@ func MaxLength(path, in, data string, maxLength int64) *errors.Validation { return nil } -// ReadOnly validates an interface for readonly +// ReadOnly validates an interface for readonly. func ReadOnly(ctx context.Context, path, in string, data any) *errors.Validation { - // read only is only validated when operationType is request if op := extractOperationType(ctx); op != request { return nil @@ -155,7 +154,7 @@ func ReadOnly(ctx context.Context, path, in string, data any) *errors.Validation return errors.ReadOnly(path, in, data) } -// Required validates an interface for requiredness +// Required validates an interface for requiredness. func Required(path, in string, data any) *errors.Validation { val := reflect.ValueOf(data) if val.IsValid() { @@ -167,7 +166,7 @@ func Required(path, in string, data any) *errors.Validation { return errors.Required(path, in, data) } -// RequiredString validates a string for requiredness +// RequiredString validates a string for requiredness. func RequiredString(path, in, data string) *errors.Validation { if data == "" { return errors.Required(path, in, data) @@ -175,7 +174,7 @@ func RequiredString(path, in, data string) *errors.Validation { return nil } -// RequiredNumber validates a number for requiredness +// RequiredNumber validates a number for requiredness. func RequiredNumber(path, in string, data float64) *errors.Validation { if data == 0 { return errors.Required(path, in, data) @@ -183,7 +182,7 @@ func RequiredNumber(path, in string, data float64) *errors.Validation { return nil } -// Pattern validates a string against a regular expression +// Pattern validates a string against a regular expression. func Pattern(path, in, data, pattern string) *errors.Validation { re, err := compileRegexp(pattern) if err != nil { @@ -195,7 +194,7 @@ func Pattern(path, in, data, pattern string) *errors.Validation { return nil } -// MaximumInt validates if a number is smaller than a given maximum +// MaximumInt validates if a number is smaller than a given maximum. func MaximumInt(path, in string, data, maximum int64, exclusive bool) *errors.Validation { if (!exclusive && data > maximum) || (exclusive && data >= maximum) { return errors.ExceedsMaximumInt(path, in, maximum, exclusive, data) @@ -203,7 +202,7 @@ func MaximumInt(path, in string, data, maximum int64, exclusive bool) *errors.Va return nil } -// MaximumUint validates if a number is smaller than a given maximum +// MaximumUint validates if a number is smaller than a given maximum. func MaximumUint(path, in string, data, maximum uint64, exclusive bool) *errors.Validation { if (!exclusive && data > maximum) || (exclusive && data >= maximum) { return errors.ExceedsMaximumUint(path, in, maximum, exclusive, data) @@ -211,7 +210,7 @@ func MaximumUint(path, in string, data, maximum uint64, exclusive bool) *errors. return nil } -// Maximum validates if a number is smaller than a given maximum +// Maximum validates if a number is smaller than a given maximum. func Maximum(path, in string, data, maximum float64, exclusive bool) *errors.Validation { if (!exclusive && data > maximum) || (exclusive && data >= maximum) { return errors.ExceedsMaximum(path, in, maximum, exclusive, data) @@ -219,7 +218,7 @@ func Maximum(path, in string, data, maximum float64, exclusive bool) *errors.Val return nil } -// Minimum validates if a number is smaller than a given minimum +// Minimum validates if a number is smaller than a given minimum. func Minimum(path, in string, data, minimum float64, exclusive bool) *errors.Validation { if (!exclusive && data < minimum) || (exclusive && data <= minimum) { return errors.ExceedsMinimum(path, in, minimum, exclusive, data) @@ -227,7 +226,7 @@ func Minimum(path, in string, data, minimum float64, exclusive bool) *errors.Val return nil } -// MinimumInt validates if a number is smaller than a given minimum +// MinimumInt validates if a number is smaller than a given minimum. func MinimumInt(path, in string, data, minimum int64, exclusive bool) *errors.Validation { if (!exclusive && data < minimum) || (exclusive && data <= minimum) { return errors.ExceedsMinimumInt(path, in, minimum, exclusive, data) @@ -235,7 +234,7 @@ func MinimumInt(path, in string, data, minimum int64, exclusive bool) *errors.Va return nil } -// MinimumUint validates if a number is smaller than a given minimum +// MinimumUint validates if a number is smaller than a given minimum. func MinimumUint(path, in string, data, minimum uint64, exclusive bool) *errors.Validation { if (!exclusive && data < minimum) || (exclusive && data <= minimum) { return errors.ExceedsMinimumUint(path, in, minimum, exclusive, data) @@ -243,7 +242,7 @@ func MinimumUint(path, in string, data, minimum uint64, exclusive bool) *errors. return nil } -// MultipleOf validates if the provided number is a multiple of the factor +// MultipleOf validates if the provided number is a multiple of the factor. func MultipleOf(path, in string, data, factor float64) *errors.Validation { // multipleOf factor must be positive if factor <= 0 { @@ -261,7 +260,7 @@ func MultipleOf(path, in string, data, factor float64) *errors.Validation { return nil } -// MultipleOfInt validates if the provided integer is a multiple of the factor +// MultipleOfInt validates if the provided integer is a multiple of the factor. func MultipleOfInt(path, in string, data int64, factor int64) *errors.Validation { // multipleOf factor must be positive if factor <= 0 { @@ -274,7 +273,7 @@ func MultipleOfInt(path, in string, data int64, factor int64) *errors.Validation return nil } -// MultipleOfUint validates if the provided unsigned integer is a multiple of the factor +// MultipleOfUint validates if the provided unsigned integer is a multiple of the factor. func MultipleOfUint(path, in string, data, factor uint64) *errors.Validation { // multipleOf factor must be positive if factor == 0 { @@ -287,7 +286,7 @@ func MultipleOfUint(path, in string, data, factor uint64) *errors.Validation { return nil } -// FormatOf validates if a string matches a format in the format registry +// FormatOf validates if a string matches a format in the format registry. func FormatOf(path, in, format, data string, registry strfmt.Registry) *errors.Validation { if registry == nil { registry = strfmt.Default @@ -310,10 +309,10 @@ func FormatOf(path, in, format, data string, registry strfmt.Registry) *errors.V // NOTE: currently, the max value is marshalled as a float64, no matter what, // which means there may be a loss during conversions (e.g. for very large integers) // -// TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free +// NOTE: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free. func MaximumNativeType(path, in string, val any, maximum float64, exclusive bool) *errors.Validation { kind := reflect.ValueOf(val).Type().Kind() - switch kind { //nolint:exhaustive + switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value := valueHelp.asInt64(val) return MaximumInt(path, in, value, int64(maximum), exclusive) @@ -340,10 +339,10 @@ func MaximumNativeType(path, in string, val any, maximum float64, exclusive bool // NOTE: currently, the min value is marshalled as a float64, no matter what, // which means there may be a loss during conversions (e.g. for very large integers) // -// TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free +// NOTE: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free. func MinimumNativeType(path, in string, val any, minimum float64, exclusive bool) *errors.Validation { kind := reflect.ValueOf(val).Type().Kind() - switch kind { //nolint:exhaustive + switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value := valueHelp.asInt64(val) return MinimumInt(path, in, value, int64(minimum), exclusive) @@ -362,7 +361,7 @@ func MinimumNativeType(path, in string, val any, minimum float64, exclusive bool } // MultipleOfNativeType provides native type constraint validation as a facade -// to various numeric types version of MultipleOf constraint check. +// to various numeric types version of [MultipleOf] constraint check. // // Assumes that any possible loss conversion during conversion has been // checked beforehand. @@ -370,10 +369,10 @@ func MinimumNativeType(path, in string, val any, minimum float64, exclusive bool // NOTE: currently, the multipleOf factor is marshalled as a float64, no matter what, // which means there may be a loss during conversions (e.g. for very large integers) // -// TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free +// NOTE: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free. func MultipleOfNativeType(path, in string, val any, multipleOf float64) *errors.Validation { kind := reflect.ValueOf(val).Type().Kind() - switch kind { //nolint:exhaustive + switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value := valueHelp.asInt64(val) return MultipleOfInt(path, in, value, int64(multipleOf)) @@ -391,13 +390,13 @@ func MultipleOfNativeType(path, in string, val any, multipleOf float64) *errors. // IsValueValidAgainstRange checks that a numeric value is compatible with // the range defined by Type and Format, that is, may be converted without loss. // -// NOTE: this check is about type capacity and not formal verification such as: 1.0 != 1L +// NOTE: this check is about type capacity and not formal verification such as: 1.0 != 1L. func IsValueValidAgainstRange(val any, typeName, format, prefix, path string) error { kind := reflect.ValueOf(val).Type().Kind() // What is the string representation of val var stringRep string - switch kind { //nolint:exhaustive + switch kind { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: stringRep = conv.FormatUinteger(valueHelp.asUint64(val)) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: diff --git a/vendor/github.com/go-viper/mapstructure/v2/.editorconfig b/vendor/github.com/go-viper/mapstructure/v2/.editorconfig index faef0c91..c37602a0 100644 --- a/vendor/github.com/go-viper/mapstructure/v2/.editorconfig +++ b/vendor/github.com/go-viper/mapstructure/v2/.editorconfig @@ -19,3 +19,6 @@ indent_size = 2 [.golangci.yaml] indent_size = 2 + +[devenv.yaml] +indent_size = 2 diff --git a/vendor/github.com/go-viper/mapstructure/v2/.envrc b/vendor/github.com/go-viper/mapstructure/v2/.envrc index 2e0f9f5f..e2be8891 100644 --- a/vendor/github.com/go-viper/mapstructure/v2/.envrc +++ b/vendor/github.com/go-viper/mapstructure/v2/.envrc @@ -1,4 +1,7 @@ -if ! has nix_direnv_version || ! nix_direnv_version 3.0.4; then - source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.0.4/direnvrc" "sha256-DzlYZ33mWF/Gs8DDeyjr8mnVmQGx7ASYqA5WlxwvBG4=" -fi -use flake . --impure +#!/usr/bin/env bash + +export DIRENV_WARN_TIMEOUT=20s + +eval "$(devenv direnvrc)" + +use devenv diff --git a/vendor/github.com/go-viper/mapstructure/v2/.gitignore b/vendor/github.com/go-viper/mapstructure/v2/.gitignore index 470e7ca2..71caea19 100644 --- a/vendor/github.com/go-viper/mapstructure/v2/.gitignore +++ b/vendor/github.com/go-viper/mapstructure/v2/.gitignore @@ -1,6 +1,10 @@ -/.devenv/ -/.direnv/ -/.pre-commit-config.yaml /bin/ /build/ /var/ + +# Devenv +.devenv* +devenv.local.nix +devenv.local.yaml +.direnv +.pre-commit-config.yaml diff --git a/vendor/github.com/go-viper/mapstructure/v2/devenv.lock b/vendor/github.com/go-viper/mapstructure/v2/devenv.lock new file mode 100644 index 00000000..72c2c9b4 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/devenv.lock @@ -0,0 +1,103 @@ +{ + "nodes": { + "devenv": { + "locked": { + "dir": "src/modules", + "lastModified": 1765288076, + "owner": "cachix", + "repo": "devenv", + "rev": "93c055af1e8fcac49251f1b2e1c57f78620ad351", + "type": "github" + }, + "original": { + "dir": "src/modules", + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1765121682, + "owner": "edolstra", + "repo": "flake-compat", + "rev": "65f23138d8d09a92e30f1e5c87611b23ef451bf3", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "git-hooks": { + "inputs": { + "flake-compat": "flake-compat", + "gitignore": "gitignore", + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1765016596, + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "548fc44fca28a5e81c5d6b846e555e6b9c2a5a3c", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, + "gitignore": { + "inputs": { + "nixpkgs": [ + "git-hooks", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1762808025, + "owner": "hercules-ci", + "repo": "gitignore.nix", + "rev": "cb5e3fdca1de58ccbc3ef53de65bd372b48f567c", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "gitignore.nix", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1764580874, + "owner": "cachix", + "repo": "devenv-nixpkgs", + "rev": "dcf61356c3ab25f1362b4a4428a6d871e84f1d1d", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "rolling", + "repo": "devenv-nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "git-hooks": "git-hooks", + "nixpkgs": "nixpkgs", + "pre-commit-hooks": [ + "git-hooks" + ] + } + } + }, + "root": "root", + "version": 7 +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/devenv.nix b/vendor/github.com/go-viper/mapstructure/v2/devenv.nix new file mode 100644 index 00000000..b31ab7a1 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/devenv.nix @@ -0,0 +1,14 @@ +{ + pkgs, + ... +}: + +{ + languages = { + go.enable = true; + }; + + packages = with pkgs; [ + golangci-lint + ]; +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/devenv.yaml b/vendor/github.com/go-viper/mapstructure/v2/devenv.yaml new file mode 100644 index 00000000..68616a49 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/devenv.yaml @@ -0,0 +1,4 @@ +# yaml-language-server: $schema=https://devenv.sh/devenv.schema.json +inputs: + nixpkgs: + url: github:cachix/devenv-nixpkgs/rolling diff --git a/vendor/github.com/go-viper/mapstructure/v2/flake.lock b/vendor/github.com/go-viper/mapstructure/v2/flake.lock deleted file mode 100644 index 5e67bdd6..00000000 --- a/vendor/github.com/go-viper/mapstructure/v2/flake.lock +++ /dev/null @@ -1,294 +0,0 @@ -{ - "nodes": { - "cachix": { - "inputs": { - "devenv": [ - "devenv" - ], - "flake-compat": [ - "devenv" - ], - "git-hooks": [ - "devenv" - ], - "nixpkgs": "nixpkgs" - }, - "locked": { - "lastModified": 1742042642, - "narHash": "sha256-D0gP8srrX0qj+wNYNPdtVJsQuFzIng3q43thnHXQ/es=", - "owner": "cachix", - "repo": "cachix", - "rev": "a624d3eaf4b1d225f918de8543ed739f2f574203", - "type": "github" - }, - "original": { - "owner": "cachix", - "ref": "latest", - "repo": "cachix", - "type": "github" - } - }, - "devenv": { - "inputs": { - "cachix": "cachix", - "flake-compat": "flake-compat", - "git-hooks": "git-hooks", - "nix": "nix", - "nixpkgs": "nixpkgs_3" - }, - "locked": { - "lastModified": 1744876578, - "narHash": "sha256-8MTBj2REB8t29sIBLpxbR0+AEGJ7f+RkzZPAGsFd40c=", - "owner": "cachix", - "repo": "devenv", - "rev": "7ff7c351bba20d0615be25ecdcbcf79b57b85fe1", - "type": "github" - }, - "original": { - "owner": "cachix", - "repo": "devenv", - "type": "github" - } - }, - "flake-compat": { - "flake": false, - "locked": { - "lastModified": 1733328505, - "narHash": "sha256-NeCCThCEP3eCl2l/+27kNNK7QrwZB1IJCrXfrbv5oqU=", - "owner": "edolstra", - "repo": "flake-compat", - "rev": "ff81ac966bb2cae68946d5ed5fc4994f96d0ffec", - "type": "github" - }, - "original": { - "owner": "edolstra", - "repo": "flake-compat", - "type": "github" - } - }, - "flake-parts": { - "inputs": { - "nixpkgs-lib": [ - "devenv", - "nix", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1712014858, - "narHash": "sha256-sB4SWl2lX95bExY2gMFG5HIzvva5AVMJd4Igm+GpZNw=", - "owner": "hercules-ci", - "repo": "flake-parts", - "rev": "9126214d0a59633752a136528f5f3b9aa8565b7d", - "type": "github" - }, - "original": { - "owner": "hercules-ci", - "repo": "flake-parts", - "type": "github" - } - }, - "flake-parts_2": { - "inputs": { - "nixpkgs-lib": "nixpkgs-lib" - }, - "locked": { - "lastModified": 1743550720, - "narHash": "sha256-hIshGgKZCgWh6AYJpJmRgFdR3WUbkY04o82X05xqQiY=", - "owner": "hercules-ci", - "repo": "flake-parts", - "rev": "c621e8422220273271f52058f618c94e405bb0f5", - "type": "github" - }, - "original": { - "owner": "hercules-ci", - "repo": "flake-parts", - "type": "github" - } - }, - "git-hooks": { - "inputs": { - "flake-compat": [ - "devenv" - ], - "gitignore": "gitignore", - "nixpkgs": [ - "devenv", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1742649964, - "narHash": "sha256-DwOTp7nvfi8mRfuL1escHDXabVXFGT1VlPD1JHrtrco=", - "owner": "cachix", - "repo": "git-hooks.nix", - "rev": "dcf5072734cb576d2b0c59b2ac44f5050b5eac82", - "type": "github" - }, - "original": { - "owner": "cachix", - "repo": "git-hooks.nix", - "type": "github" - } - }, - "gitignore": { - "inputs": { - "nixpkgs": [ - "devenv", - "git-hooks", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1709087332, - "narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=", - "owner": "hercules-ci", - "repo": "gitignore.nix", - "rev": "637db329424fd7e46cf4185293b9cc8c88c95394", - "type": "github" - }, - "original": { - "owner": "hercules-ci", - "repo": "gitignore.nix", - "type": "github" - } - }, - "libgit2": { - "flake": false, - "locked": { - "lastModified": 1697646580, - "narHash": "sha256-oX4Z3S9WtJlwvj0uH9HlYcWv+x1hqp8mhXl7HsLu2f0=", - "owner": "libgit2", - "repo": "libgit2", - "rev": "45fd9ed7ae1a9b74b957ef4f337bc3c8b3df01b5", - "type": "github" - }, - "original": { - "owner": "libgit2", - "repo": "libgit2", - "type": "github" - } - }, - "nix": { - "inputs": { - "flake-compat": [ - "devenv" - ], - "flake-parts": "flake-parts", - "libgit2": "libgit2", - "nixpkgs": "nixpkgs_2", - "nixpkgs-23-11": [ - "devenv" - ], - "nixpkgs-regression": [ - "devenv" - ], - "pre-commit-hooks": [ - "devenv" - ] - }, - "locked": { - "lastModified": 1741798497, - "narHash": "sha256-E3j+3MoY8Y96mG1dUIiLFm2tZmNbRvSiyN7CrSKuAVg=", - "owner": "domenkozar", - "repo": "nix", - "rev": "f3f44b2baaf6c4c6e179de8cbb1cc6db031083cd", - "type": "github" - }, - "original": { - "owner": "domenkozar", - "ref": "devenv-2.24", - "repo": "nix", - "type": "github" - } - }, - "nixpkgs": { - "locked": { - "lastModified": 1733212471, - "narHash": "sha256-M1+uCoV5igihRfcUKrr1riygbe73/dzNnzPsmaLCmpo=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "55d15ad12a74eb7d4646254e13638ad0c4128776", - "type": "github" - }, - "original": { - "owner": "NixOS", - "ref": "nixos-unstable", - "repo": "nixpkgs", - "type": "github" - } - }, - "nixpkgs-lib": { - "locked": { - "lastModified": 1743296961, - "narHash": "sha256-b1EdN3cULCqtorQ4QeWgLMrd5ZGOjLSLemfa00heasc=", - "owner": "nix-community", - "repo": "nixpkgs.lib", - "rev": "e4822aea2a6d1cdd36653c134cacfd64c97ff4fa", - "type": "github" - }, - "original": { - "owner": "nix-community", - "repo": "nixpkgs.lib", - "type": "github" - } - }, - "nixpkgs_2": { - "locked": { - "lastModified": 1717432640, - "narHash": "sha256-+f9c4/ZX5MWDOuB1rKoWj+lBNm0z0rs4CK47HBLxy1o=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "88269ab3044128b7c2f4c7d68448b2fb50456870", - "type": "github" - }, - "original": { - "owner": "NixOS", - "ref": "release-24.05", - "repo": "nixpkgs", - "type": "github" - } - }, - "nixpkgs_3": { - "locked": { - "lastModified": 1733477122, - "narHash": "sha256-qamMCz5mNpQmgBwc8SB5tVMlD5sbwVIToVZtSxMph9s=", - "owner": "cachix", - "repo": "devenv-nixpkgs", - "rev": "7bd9e84d0452f6d2e63b6e6da29fe73fac951857", - "type": "github" - }, - "original": { - "owner": "cachix", - "ref": "rolling", - "repo": "devenv-nixpkgs", - "type": "github" - } - }, - "nixpkgs_4": { - "locked": { - "lastModified": 1744536153, - "narHash": "sha256-awS2zRgF4uTwrOKwwiJcByDzDOdo3Q1rPZbiHQg/N38=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "18dd725c29603f582cf1900e0d25f9f1063dbf11", - "type": "github" - }, - "original": { - "owner": "NixOS", - "ref": "nixpkgs-unstable", - "repo": "nixpkgs", - "type": "github" - } - }, - "root": { - "inputs": { - "devenv": "devenv", - "flake-parts": "flake-parts_2", - "nixpkgs": "nixpkgs_4" - } - } - }, - "root": "root", - "version": 7 -} diff --git a/vendor/github.com/go-viper/mapstructure/v2/flake.nix b/vendor/github.com/go-viper/mapstructure/v2/flake.nix deleted file mode 100644 index 3b116f42..00000000 --- a/vendor/github.com/go-viper/mapstructure/v2/flake.nix +++ /dev/null @@ -1,46 +0,0 @@ -{ - inputs = { - nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; - flake-parts.url = "github:hercules-ci/flake-parts"; - devenv.url = "github:cachix/devenv"; - }; - - outputs = - inputs@{ flake-parts, ... }: - flake-parts.lib.mkFlake { inherit inputs; } { - imports = [ - inputs.devenv.flakeModule - ]; - - systems = [ - "x86_64-linux" - "x86_64-darwin" - "aarch64-darwin" - ]; - - perSystem = - { pkgs, ... }: - rec { - devenv.shells = { - default = { - languages = { - go.enable = true; - }; - - pre-commit.hooks = { - nixpkgs-fmt.enable = true; - }; - - packages = with pkgs; [ - golangci-lint - ]; - - # https://github.com/cachix/devenv/issues/528#issuecomment-1556108767 - containers = pkgs.lib.mkForce { }; - }; - - ci = devenv.shells.default; - }; - }; - }; -} diff --git a/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go b/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go index 7c35bce0..9087fd96 100644 --- a/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go +++ b/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go @@ -173,6 +173,25 @@ // Public: "I made it through!" // } // +// # Custom Decoding with Unmarshaler +// +// Types can implement the Unmarshaler interface to control their own decoding. The interface +// behaves similarly to how UnmarshalJSON does in the standard library. It can be used as an +// alternative or companion to a DecodeHook. +// +// type TrimmedString string +// +// func (t *TrimmedString) UnmarshalMapstructure(input any) error { +// str, ok := input.(string) +// if !ok { +// return fmt.Errorf("expected string, got %T", input) +// } +// *t = TrimmedString(strings.TrimSpace(str)) +// return nil +// } +// +// See the Unmarshaler interface documentation for more details. +// // # Other Configuration // // mapstructure is highly configurable. See the DecoderConfig struct @@ -218,6 +237,17 @@ type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, any) (any, error) // values. type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (any, error) +// Unmarshaler is the interface implemented by types that can unmarshal +// themselves. UnmarshalMapstructure receives the input data (potentially +// transformed by DecodeHook) and should populate the receiver with the +// decoded values. +// +// The Unmarshaler interface takes precedence over the default decoding +// logic for any type (structs, slices, maps, primitives, etc.). +type Unmarshaler interface { + UnmarshalMapstructure(any) error +} + // DecoderConfig is the configuration that is used to create a new decoder // and allows customization of various aspects of decoding. type DecoderConfig struct { @@ -281,6 +311,13 @@ type DecoderConfig struct { // } Squash bool + // Deep will map structures in slices instead of copying them + // + // type Parent struct { + // Children []Child `mapstructure:",deep"` + // } + Deep bool + // Metadata is the struct that will contain extra metadata about // the decoding. If this is nil, then no metadata will be tracked. Metadata *Metadata @@ -290,9 +327,15 @@ type DecoderConfig struct { Result any // The tag name that mapstructure reads for field names. This - // defaults to "mapstructure" + // defaults to "mapstructure". Multiple tag names can be specified + // as a comma-separated list (e.g., "yaml,json"), and the first + // matching non-empty tag will be used. TagName string + // RootName specifies the name to use for the root element in error messages. For example: + // '' has unset fields: + RootName string + // The option of the value in the tag that indicates a field should // be squashed. This defaults to "squash". SquashTagOption string @@ -304,11 +347,34 @@ type DecoderConfig struct { // MatchName is the function used to match the map key to the struct // field name or tag. Defaults to `strings.EqualFold`. This can be used // to implement case-sensitive tag values, support snake casing, etc. + // + // MatchName is used as a fallback comparison when the direct key lookup fails. + // See also MapFieldName for transforming field names before lookup. MatchName func(mapKey, fieldName string) bool // DecodeNil, if set to true, will cause the DecodeHook (if present) to run // even if the input is nil. This can be used to provide default values. DecodeNil bool + + // MapFieldName is the function used to convert the struct field name to the map's key name. + // + // This is useful for automatically converting between naming conventions without + // explicitly tagging each field. For example, to convert Go's PascalCase field names + // to snake_case map keys: + // + // MapFieldName: func(s string) string { + // return strcase.ToSnake(s) + // } + // + // When decoding from a map to a struct, the transformed field name is used for + // the initial lookup. If not found, MatchName is used as a fallback comparison. + // Explicit struct tags always take precedence over MapFieldName. + MapFieldName func(string) string + + // DisableUnmarshaler, if set to true, disables the use of the Unmarshaler + // interface. Types implementing Unmarshaler will be decoded using the + // standard struct decoding logic instead. + DisableUnmarshaler bool } // A Decoder takes a raw interface value and turns it into structured @@ -445,6 +511,12 @@ func NewDecoder(config *DecoderConfig) (*Decoder, error) { config.MatchName = strings.EqualFold } + if config.MapFieldName == nil { + config.MapFieldName = func(s string) string { + return s + } + } + result := &Decoder{ config: config, } @@ -458,7 +530,7 @@ func NewDecoder(config *DecoderConfig) (*Decoder, error) { // Decode decodes the given raw interface to the target pointer specified // by the configuration. func (d *Decoder) Decode(input any) error { - err := d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) + err := d.decode(d.config.RootName, input, reflect.ValueOf(d.config.Result).Elem()) // Retain some of the original behavior when multiple errors ocurr var joinedErr interface{ Unwrap() []error } @@ -540,36 +612,50 @@ func (d *Decoder) decode(name string, input any, outVal reflect.Value) error { var err error addMetaKey := true - switch outputKind { - case reflect.Bool: - err = d.decodeBool(name, input, outVal) - case reflect.Interface: - err = d.decodeBasic(name, input, outVal) - case reflect.String: - err = d.decodeString(name, input, outVal) - case reflect.Int: - err = d.decodeInt(name, input, outVal) - case reflect.Uint: - err = d.decodeUint(name, input, outVal) - case reflect.Float32: - err = d.decodeFloat(name, input, outVal) - case reflect.Complex64: - err = d.decodeComplex(name, input, outVal) - case reflect.Struct: - err = d.decodeStruct(name, input, outVal) - case reflect.Map: - err = d.decodeMap(name, input, outVal) - case reflect.Ptr: - addMetaKey, err = d.decodePtr(name, input, outVal) - case reflect.Slice: - err = d.decodeSlice(name, input, outVal) - case reflect.Array: - err = d.decodeArray(name, input, outVal) - case reflect.Func: - err = d.decodeFunc(name, input, outVal) - default: - // If we reached this point then we weren't able to decode it - return newDecodeError(name, fmt.Errorf("unsupported type: %s", outputKind)) + + // Check if the target implements Unmarshaler and use it if not disabled + unmarshaled := false + if !d.config.DisableUnmarshaler { + if unmarshaler, ok := getUnmarshaler(outVal); ok { + if err = unmarshaler.UnmarshalMapstructure(input); err != nil { + err = newDecodeError(name, err) + } + unmarshaled = true + } + } + + if !unmarshaled { + switch outputKind { + case reflect.Bool: + err = d.decodeBool(name, input, outVal) + case reflect.Interface: + err = d.decodeBasic(name, input, outVal) + case reflect.String: + err = d.decodeString(name, input, outVal) + case reflect.Int: + err = d.decodeInt(name, input, outVal) + case reflect.Uint: + err = d.decodeUint(name, input, outVal) + case reflect.Float32: + err = d.decodeFloat(name, input, outVal) + case reflect.Complex64: + err = d.decodeComplex(name, input, outVal) + case reflect.Struct: + err = d.decodeStruct(name, input, outVal) + case reflect.Map: + err = d.decodeMap(name, input, outVal) + case reflect.Ptr: + addMetaKey, err = d.decodePtr(name, input, outVal) + case reflect.Slice: + err = d.decodeSlice(name, input, outVal) + case reflect.Array: + err = d.decodeArray(name, input, outVal) + case reflect.Func: + err = d.decodeFunc(name, input, outVal) + default: + // If we reached this point then we weren't able to decode it + return newDecodeError(name, fmt.Errorf("unsupported type: %s", outputKind)) + } } // If we reached here, then we successfully decoded SOMETHING, so @@ -668,7 +754,7 @@ func (d *Decoder) decodeString(name string, data any, val reflect.Value) error { case reflect.Uint8: var uints []uint8 if dataKind == reflect.Array { - uints = make([]uint8, dataVal.Len(), dataVal.Len()) + uints = make([]uint8, dataVal.Len()) for i := range uints { uints[i] = dataVal.Index(i).Interface().(uint8) } @@ -1060,8 +1146,8 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re ) } - tagValue := f.Tag.Get(d.config.TagName) - keyName := f.Name + tagValue, _ := getTagValue(f, d.config.TagName) + keyName := d.config.MapFieldName(f.Name) if tagValue == "" && d.config.IgnoreUntaggedFields { continue @@ -1070,6 +1156,9 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re // If Squash is set in the config, we squash the field down. squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous + // If Deep is set in the config, set as default value. + deep := d.config.Deep + v = dereferencePtrToStructIfNeeded(v, d.config.TagName) // Determine the name of the key in the map @@ -1078,12 +1167,12 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re continue } // If "omitempty" is specified in the tag, it ignores empty values. - if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) { + if strings.Contains(tagValue[index+1:], "omitempty") && isEmptyValue(v) { continue } // If "omitzero" is specified in the tag, it ignores zero values. - if strings.Index(tagValue[index+1:], "omitzero") != -1 && v.IsZero() { + if strings.Contains(tagValue[index+1:], "omitzero") && v.IsZero() { continue } @@ -1103,7 +1192,7 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re ) } } else { - if strings.Index(tagValue[index+1:], "remain") != -1 { + if strings.Contains(tagValue[index+1:], "remain") { if v.Kind() != reflect.Map { return newDecodeError( name+"."+f.Name, @@ -1118,6 +1207,9 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re continue } } + + deep = deep || strings.Contains(tagValue[index+1:], "deep") + if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" { keyName = keyNameTagValue } @@ -1164,6 +1256,41 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) } + case reflect.Slice: + if deep { + var childType reflect.Type + switch v.Type().Elem().Kind() { + case reflect.Struct: + childType = reflect.TypeOf(map[string]any{}) + default: + childType = v.Type().Elem() + } + + sType := reflect.SliceOf(childType) + + addrVal := reflect.New(sType) + + vSlice := reflect.MakeSlice(sType, v.Len(), v.Cap()) + + if v.Len() > 0 { + reflect.Indirect(addrVal).Set(vSlice) + + err := d.decode(keyName, v.Interface(), reflect.Indirect(addrVal)) + if err != nil { + return err + } + } + + vSlice = reflect.Indirect(addrVal) + + valMap.SetMapIndex(reflect.ValueOf(keyName), vSlice) + + break + } + + // When deep mapping is not needed, fallthrough to normal copy + fallthrough + default: valMap.SetMapIndex(reflect.ValueOf(keyName), v) } @@ -1471,7 +1598,10 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e remain := false // We always parse the tags cause we're looking for other tags too - tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") + tagParts := getTagParts(fieldType, d.config.TagName) + if len(tagParts) == 0 { + tagParts = []string{""} + } for _, tag := range tagParts[1:] { if tag == d.config.SquashTagOption { squash = true @@ -1492,6 +1622,18 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e if !fieldVal.IsNil() { structs = append(structs, fieldVal.Elem().Elem()) } + case reflect.Ptr: + if fieldVal.Type().Elem().Kind() == reflect.Struct { + if fieldVal.IsNil() { + fieldVal.Set(reflect.New(fieldVal.Type().Elem())) + } + structs = append(structs, fieldVal.Elem()) + } else { + errs = append(errs, newDecodeError( + name+"."+fieldType.Name, + fmt.Errorf("unsupported type for squashed pointer: %s", fieldVal.Type().Elem().Kind()), + )) + } default: errs = append(errs, newDecodeError( name+"."+fieldType.Name, @@ -1516,13 +1658,15 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e field, fieldValue := f.field, f.val fieldName := field.Name - tagValue := field.Tag.Get(d.config.TagName) + tagValue, _ := getTagValue(field, d.config.TagName) if tagValue == "" && d.config.IgnoreUntaggedFields { continue } tagValue = strings.SplitN(tagValue, ",", 2)[0] if tagValue != "" { fieldName = tagValue + } else { + fieldName = d.config.MapFieldName(fieldName) } rawMapKey := reflect.ValueOf(fieldName) @@ -1605,8 +1749,14 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e } sort.Strings(keys) + // Improve error message when name is empty by showing the target struct type + // in the case where it is empty for embedded structs. + errorName := name + if errorName == "" { + errorName = val.Type().String() + } errs = append(errs, newDecodeError( - name, + errorName, fmt.Errorf("has invalid keys: %s", strings.Join(keys, ", ")), )) } @@ -1692,7 +1842,7 @@ func isStructTypeConvertibleToMap(typ reflect.Type, checkMapstructureTags bool, if f.PkgPath == "" && !checkMapstructureTags { // check for unexported fields return true } - if checkMapstructureTags && f.Tag.Get(tagName) != "" { // check for mapstructure tags inside + if checkMapstructureTags && hasAnyTag(f, tagName) { // check for mapstructure tags inside return true } } @@ -1700,13 +1850,99 @@ func isStructTypeConvertibleToMap(typ reflect.Type, checkMapstructureTags bool, } func dereferencePtrToStructIfNeeded(v reflect.Value, tagName string) reflect.Value { - if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { + if v.Kind() != reflect.Ptr { + return v + } + + switch v.Elem().Kind() { + case reflect.Slice: + return v.Elem() + + case reflect.Struct: + deref := v.Elem() + derefT := deref.Type() + if isStructTypeConvertibleToMap(derefT, true, tagName) { + return deref + } + return v + + default: return v } - deref := v.Elem() - derefT := deref.Type() - if isStructTypeConvertibleToMap(derefT, true, tagName) { - return deref +} + +func hasAnyTag(field reflect.StructField, tagName string) bool { + _, ok := getTagValue(field, tagName) + return ok +} + +func getTagParts(field reflect.StructField, tagName string) []string { + tagValue, ok := getTagValue(field, tagName) + if !ok { + return nil } - return v + return strings.Split(tagValue, ",") +} + +func getTagValue(field reflect.StructField, tagName string) (string, bool) { + for _, name := range splitTagNames(tagName) { + if tag := field.Tag.Get(name); tag != "" { + return tag, true + } + } + return "", false +} + +func splitTagNames(tagName string) []string { + if tagName == "" { + return []string{"mapstructure"} + } + parts := strings.Split(tagName, ",") + result := make([]string, 0, len(parts)) + + for _, name := range parts { + name = strings.TrimSpace(name) + if name != "" { + result = append(result, name) + } + } + + return result +} + +// unmarshalerType is cached for performance +var unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() + +// getUnmarshaler checks if the value implements Unmarshaler and returns +// the Unmarshaler and a boolean indicating if it was found. It handles both +// pointer and value receivers. +func getUnmarshaler(val reflect.Value) (Unmarshaler, bool) { + // Skip invalid or nil values + if !val.IsValid() { + return nil, false + } + + switch val.Kind() { + case reflect.Pointer, reflect.Interface: + if val.IsNil() { + return nil, false + } + } + + // Check pointer receiver first (most common case) + if val.CanAddr() { + ptrVal := val.Addr() + // Quick check: if no methods, can't implement any interface + if ptrVal.Type().NumMethod() > 0 && ptrVal.Type().Implements(unmarshalerType) { + return ptrVal.Interface().(Unmarshaler), true + } + } + + // Check value receiver + // Quick check: if no methods, can't implement any interface + if val.Type().NumMethod() > 0 && val.CanInterface() && val.Type().Implements(unmarshalerType) { + return val.Interface().(Unmarshaler), true + } + + return nil, false } diff --git a/vendor/github.com/oklog/ulid/.travis.yml b/vendor/github.com/oklog/ulid/.travis.yml deleted file mode 100644 index 43eb762f..00000000 --- a/vendor/github.com/oklog/ulid/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go -sudo: false -go: - - 1.10.x -install: - - go get -v github.com/golang/lint/golint - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - - go get -d -t -v ./... - - go build -v ./... -script: - - go vet ./... - - $HOME/gopath/bin/golint . - - go test -v -race ./... - - go test -v -covermode=count -coverprofile=cov.out - - $HOME/gopath/bin/goveralls -coverprofile=cov.out -service=travis-ci -repotoken "$COVERALLS_TOKEN" || true diff --git a/vendor/github.com/oklog/ulid/Gopkg.lock b/vendor/github.com/oklog/ulid/Gopkg.lock deleted file mode 100644 index 349b449a..00000000 --- a/vendor/github.com/oklog/ulid/Gopkg.lock +++ /dev/null @@ -1,15 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - branch = "master" - name = "github.com/pborman/getopt" - packages = ["v2"] - revision = "7148bc3a4c3008adfcab60cbebfd0576018f330b" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "6779b05abd5cd429c5393641d2453005a3cb74a400d161b2b5c5d0ca2e10e116" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/oklog/ulid/Gopkg.toml b/vendor/github.com/oklog/ulid/Gopkg.toml deleted file mode 100644 index 624a7a01..00000000 --- a/vendor/github.com/oklog/ulid/Gopkg.toml +++ /dev/null @@ -1,26 +0,0 @@ - -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - - -[[constraint]] - branch = "master" - name = "github.com/pborman/getopt" diff --git a/vendor/github.com/oklog/ulid/.gitignore b/vendor/github.com/oklog/ulid/v2/.gitignore similarity index 100% rename from vendor/github.com/oklog/ulid/.gitignore rename to vendor/github.com/oklog/ulid/v2/.gitignore diff --git a/vendor/github.com/oklog/ulid/AUTHORS.md b/vendor/github.com/oklog/ulid/v2/AUTHORS.md similarity index 100% rename from vendor/github.com/oklog/ulid/AUTHORS.md rename to vendor/github.com/oklog/ulid/v2/AUTHORS.md diff --git a/vendor/github.com/oklog/ulid/CHANGELOG.md b/vendor/github.com/oklog/ulid/v2/CHANGELOG.md similarity index 100% rename from vendor/github.com/oklog/ulid/CHANGELOG.md rename to vendor/github.com/oklog/ulid/v2/CHANGELOG.md diff --git a/vendor/github.com/oklog/ulid/CONTRIBUTING.md b/vendor/github.com/oklog/ulid/v2/CONTRIBUTING.md similarity index 100% rename from vendor/github.com/oklog/ulid/CONTRIBUTING.md rename to vendor/github.com/oklog/ulid/v2/CONTRIBUTING.md diff --git a/vendor/github.com/oklog/ulid/LICENSE b/vendor/github.com/oklog/ulid/v2/LICENSE similarity index 100% rename from vendor/github.com/oklog/ulid/LICENSE rename to vendor/github.com/oklog/ulid/v2/LICENSE diff --git a/vendor/github.com/oklog/ulid/README.md b/vendor/github.com/oklog/ulid/v2/README.md similarity index 55% rename from vendor/github.com/oklog/ulid/README.md rename to vendor/github.com/oklog/ulid/v2/README.md index 0a3d2f82..f6db0af3 100644 --- a/vendor/github.com/oklog/ulid/README.md +++ b/vendor/github.com/oklog/ulid/v2/README.md @@ -1,13 +1,13 @@ # Universally Unique Lexicographically Sortable Identifier -![Project status](https://img.shields.io/badge/version-1.3.0-yellow.svg) -[![Build Status](https://secure.travis-ci.org/oklog/ulid.png)](http://travis-ci.org/oklog/ulid) +[![Project status](https://img.shields.io/github/release/oklog/ulid.svg?style=flat-square)](https://github.com/oklog/ulid/releases/latest) +![Build Status](https://github.com/oklog/ulid/actions/workflows/test.yml/badge.svg) [![Go Report Card](https://goreportcard.com/badge/oklog/ulid?cache=0)](https://goreportcard.com/report/oklog/ulid) [![Coverage Status](https://coveralls.io/repos/github/oklog/ulid/badge.svg?branch=master&cache=0)](https://coveralls.io/github/oklog/ulid?branch=master) -[![GoDoc](https://godoc.org/github.com/oklog/ulid?status.svg)](https://godoc.org/github.com/oklog/ulid) +[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/oklog/ulid/v2) [![Apache 2 licensed](https://img.shields.io/badge/license-Apache2-blue.svg)](https://raw.githubusercontent.com/oklog/ulid/master/LICENSE) -A Go port of [alizain/ulid](https://github.com/alizain/ulid) with binary format implemented. +A Go port of [ulid/javascript](https://github.com/ulid/javascript) with binary format implemented. ## Background @@ -31,27 +31,109 @@ A ULID however: ## Install +This package requires Go modules. + ```shell -go get github.com/oklog/ulid +go get github.com/oklog/ulid/v2 ``` ## Usage -An ULID is constructed with a `time.Time` and an `io.Reader` entropy source. -This design allows for greater flexibility in choosing your trade-offs. +ULIDs are constructed from two things: a timestamp with millisecond precision, +and some random data. + +Timestamps are modeled as uint64 values representing a Unix time in milliseconds. +They can be produced by passing a [time.Time](https://pkg.go.dev/time#Time) to +[ulid.Timestamp](https://pkg.go.dev/github.com/oklog/ulid/v2#Timestamp), +or by calling [time.Time.UnixMilli](https://pkg.go.dev/time#Time.UnixMilli) +and converting the returned value to `uint64`. + +Random data is taken from a provided [io.Reader](https://pkg.go.dev/io#Reader). +This design allows for greater flexibility when choosing trade-offs, but can be +a bit confusing to newcomers. -Please note that `rand.Rand` from the `math` package is *not* safe for concurrent use. -Instantiate one per long living go-routine or use a `sync.Pool` if you want to avoid the potential contention of a locked `rand.Source` as its been frequently observed in the package level functions. +If you just want to generate a ULID and don't (yet) care about details like +performance, cryptographic security, etc., use the +[ulid.Make](https://pkg.go.dev/github.com/oklog/ulid/v2#Make) helper function. +This function calls [time.Now](https://pkg.go.dev/time#Now) to get a timestamp, +and uses a source of entropy which is process-global, +[pseudo-random](https://pkg.go.dev/math/rand), and +[monotonic](https://pkg.go.dev/github.com/oklog/ulid/v2#LockedMonotonicReader). + +```go +fmt.Println(ulid.Make()) +// 01G65Z755AFWAKHE12NY0CQ9FH +``` +More advanced use cases should utilize +[ulid.New](https://pkg.go.dev/github.com/oklog/ulid/v2#New). ```go -func ExampleULID() { - t := time.Unix(1000000, 0) - entropy := ulid.Monotonic(rand.New(rand.NewSource(t.UnixNano())), 0) - fmt.Println(ulid.MustNew(ulid.Timestamp(t), entropy)) - // Output: 0000XSNJG0MQJHBF4QX1EFD6Y3 -} +entropy := rand.New(rand.NewSource(time.Now().UnixNano())) +ms := ulid.Timestamp(time.Now()) +fmt.Println(ulid.New(ms, entropy)) +// 01G65Z755AFWAKHE12NY0CQ9FH +``` + +Care should be taken when providing a source of entropy. + +The above example utilizes [math/rand.Rand](https://pkg.go.dev/math/rand#Rand), +which is not safe for concurrent use by multiple goroutines. Consider +alternatives such as +[x/exp/rand](https://pkg.go.dev/golang.org/x/exp/rand#LockedSource). +Security-sensitive use cases should always use cryptographically secure entropy +provided by [crypto/rand](https://pkg.go.dev/crypto/rand). + +Performance-sensitive use cases should avoid synchronization when generating +IDs. One option is to use a unique source of entropy for each concurrent +goroutine, which results in no lock contention, but cannot provide strong +guarantees about the random data, and does not provide monotonicity within a +given millisecond. One common performance optimization is to pool sources of +entropy using a [sync.Pool](https://pkg.go.dev/sync#Pool). + +Monotonicity is a property that says each ULID is "bigger than" the previous +one. ULIDs are automatically monotonic, but only to millisecond precision. ULIDs +generated within the same millisecond are ordered by their random component, +which means they are by default un-ordered. You can use +[ulid.MonotonicEntropy](https://pkg.go.dev/github.com/oklog/ulid/v2#MonotonicEntropy) or +[ulid.LockedMonotonicEntropy](https://pkg.go.dev/github.com/oklog/ulid/v2#LockedMonotonicEntropy) +to create ULIDs that are monotonic within a given millisecond, with caveats. See +the documentation for details. + +If you don't care about time-based ordering of generated IDs, then there's no +reason to use ULIDs! There are many other kinds of IDs that are easier, faster, +smaller, etc. Consider UUIDs. +## Commandline tool + +This repo also provides a tool to generate and parse ULIDs at the command line. + +```shell +go install github.com/oklog/ulid/v2/cmd/ulid@latest +``` + +Usage: + +```shell +Usage: ulid [-hlqz] [-f ] [parameters ...] + -f, --format= when parsing, show times in this format: default, rfc3339, unix, ms + -h, --help print this help text + -l, --local when parsing, show local time instead of UTC + -q, --quick when generating, use non-crypto-grade entropy + -z, --zero when generating, fix entropy to all-zeroes +``` + +Examples: + +```shell +$ ulid +01D78XYFJ1PRM1WPBCBT3VHMNV +$ ulid -z +01D78XZ44G0000000000000000 +$ ulid 01D78XZ44G0000000000000000 +Sun Mar 31 03:51:23.536 UTC 2019 +$ ulid --format=rfc3339 --local 01D78XZ44G0000000000000000 +2019-03-31T05:51:23.536+02:00 ``` ## Specification @@ -63,7 +145,7 @@ Below is the current specification of ULID as implemented in this repository. **Timestamp** - 48 bits - UNIX-time in milliseconds -- Won't run out of space till the year 10895 AD +- Won't run out of space till the year 10889 AD **Entropy** - 80 bits @@ -145,6 +227,6 @@ BenchmarkCompare-8 200000000 7.34 ns/op 4359.23 MB/s ## Prior Art -- [alizain/ulid](https://github.com/alizain/ulid) +- [ulid/javascript](https://github.com/ulid/javascript) - [RobThree/NUlid](https://github.com/RobThree/NUlid) - [imdario/go-ulid](https://github.com/imdario/go-ulid) diff --git a/vendor/github.com/oklog/ulid/ulid.go b/vendor/github.com/oklog/ulid/v2/ulid.go similarity index 73% rename from vendor/github.com/oklog/ulid/ulid.go rename to vendor/github.com/oklog/ulid/v2/ulid.go index c5d0d66f..77e9ddd6 100644 --- a/vendor/github.com/oklog/ulid/ulid.go +++ b/vendor/github.com/oklog/ulid/v2/ulid.go @@ -23,11 +23,12 @@ import ( "math" "math/bits" "math/rand" + "sync" "time" ) /* -An ULID is a 16 byte Universally Unique Lexicographically Sortable Identifier +A ULID is a 16 byte Universally Unique Lexicographically Sortable Identifier The components are encoded as 16 octets. Each component is encoded with the MSB first (network byte order). @@ -59,7 +60,7 @@ var ( // size. ErrBufferSize = errors.New("ulid: bad buffer size when marshaling") - // ErrBigTime is returned when constructing an ULID with a time that is larger + // ErrBigTime is returned when constructing a ULID with a time that is larger // than MaxTime. ErrBigTime = errors.New("ulid: time too big") @@ -74,14 +75,29 @@ var ( // ErrScanValue is returned when the value passed to scan cannot be unmarshaled // into the ULID. ErrScanValue = errors.New("ulid: source value must be a string or byte slice") + + // Zero is a zero-value ULID. + Zero ULID ) -// New returns an ULID with the given Unix milliseconds timestamp and an +// MonotonicReader is an interface that should yield monotonically increasing +// entropy into the provided slice for all calls with the same ms parameter. If +// a MonotonicReader is provided to the New constructor, its MonotonicRead +// method will be used instead of Read. +type MonotonicReader interface { + io.Reader + MonotonicRead(ms uint64, p []byte) error +} + +// New returns a ULID with the given Unix milliseconds timestamp and an // optional entropy source. Use the Timestamp function to convert // a time.Time to Unix milliseconds. // // ErrBigTime is returned when passing a timestamp bigger than MaxTime. // Reading from the entropy source may also return an error. +// +// Safety for concurrent use is only dependent on the safety of the +// entropy source. func New(ms uint64, entropy io.Reader) (id ULID, err error) { if err = id.SetTime(ms); err != nil { return id, err @@ -90,7 +106,7 @@ func New(ms uint64, entropy io.Reader) (id ULID, err error) { switch e := entropy.(type) { case nil: return id, err - case *monotonic: + case MonotonicReader: err = e.MonotonicRead(ms, id[6:]) default: _, err = io.ReadFull(e, id[6:]) @@ -109,6 +125,33 @@ func MustNew(ms uint64, entropy io.Reader) ULID { return id } +// MustNewDefault is a convenience function equivalent to MustNew with +// DefaultEntropy as the entropy. It may panic if the given time.Time is too +// large or too small. +func MustNewDefault(t time.Time) ULID { + return MustNew(Timestamp(t), defaultEntropy) +} + +var defaultEntropy = func() io.Reader { + rng := rand.New(rand.NewSource(time.Now().UnixNano())) + return &LockedMonotonicReader{MonotonicReader: Monotonic(rng, 0)} +}() + +// DefaultEntropy returns a thread-safe per process monotonically increasing +// entropy source. +func DefaultEntropy() io.Reader { + return defaultEntropy +} + +// Make returns a ULID with the current time in Unix milliseconds and +// monotonically increasing entropy for the same millisecond. +// It is safe for concurrent use, leveraging a sync.Pool underneath for minimal +// contention. +func Make() (id ULID) { + // NOTE: MustNew can't panic since DefaultEntropy never returns an error. + return MustNew(Now(), defaultEntropy) +} + // Parse parses an encoded ULID, returning an error in case of failure. // // ErrDataSize is returned if the len(ulid) is different from an encoded @@ -180,24 +223,24 @@ func parse(v []byte, strict bool, id *ULID) error { // to decode a base32 ULID. // 6 bytes timestamp (48 bits) - (*id)[0] = ((dec[v[0]] << 5) | dec[v[1]]) - (*id)[1] = ((dec[v[2]] << 3) | (dec[v[3]] >> 2)) - (*id)[2] = ((dec[v[3]] << 6) | (dec[v[4]] << 1) | (dec[v[5]] >> 4)) - (*id)[3] = ((dec[v[5]] << 4) | (dec[v[6]] >> 1)) - (*id)[4] = ((dec[v[6]] << 7) | (dec[v[7]] << 2) | (dec[v[8]] >> 3)) - (*id)[5] = ((dec[v[8]] << 5) | dec[v[9]]) + (*id)[0] = (dec[v[0]] << 5) | dec[v[1]] + (*id)[1] = (dec[v[2]] << 3) | (dec[v[3]] >> 2) + (*id)[2] = (dec[v[3]] << 6) | (dec[v[4]] << 1) | (dec[v[5]] >> 4) + (*id)[3] = (dec[v[5]] << 4) | (dec[v[6]] >> 1) + (*id)[4] = (dec[v[6]] << 7) | (dec[v[7]] << 2) | (dec[v[8]] >> 3) + (*id)[5] = (dec[v[8]] << 5) | dec[v[9]] // 10 bytes of entropy (80 bits) - (*id)[6] = ((dec[v[10]] << 3) | (dec[v[11]] >> 2)) - (*id)[7] = ((dec[v[11]] << 6) | (dec[v[12]] << 1) | (dec[v[13]] >> 4)) - (*id)[8] = ((dec[v[13]] << 4) | (dec[v[14]] >> 1)) - (*id)[9] = ((dec[v[14]] << 7) | (dec[v[15]] << 2) | (dec[v[16]] >> 3)) - (*id)[10] = ((dec[v[16]] << 5) | dec[v[17]]) - (*id)[11] = ((dec[v[18]] << 3) | dec[v[19]]>>2) - (*id)[12] = ((dec[v[19]] << 6) | (dec[v[20]] << 1) | (dec[v[21]] >> 4)) - (*id)[13] = ((dec[v[21]] << 4) | (dec[v[22]] >> 1)) - (*id)[14] = ((dec[v[22]] << 7) | (dec[v[23]] << 2) | (dec[v[24]] >> 3)) - (*id)[15] = ((dec[v[24]] << 5) | dec[v[25]]) + (*id)[6] = (dec[v[10]] << 3) | (dec[v[11]] >> 2) + (*id)[7] = (dec[v[11]] << 6) | (dec[v[12]] << 1) | (dec[v[13]] >> 4) + (*id)[8] = (dec[v[13]] << 4) | (dec[v[14]] >> 1) + (*id)[9] = (dec[v[14]] << 7) | (dec[v[15]] << 2) | (dec[v[16]] >> 3) + (*id)[10] = (dec[v[16]] << 5) | dec[v[17]] + (*id)[11] = (dec[v[18]] << 3) | dec[v[19]]>>2 + (*id)[12] = (dec[v[19]] << 6) | (dec[v[20]] << 1) | (dec[v[21]] >> 4) + (*id)[13] = (dec[v[21]] << 4) | (dec[v[22]] >> 1) + (*id)[14] = (dec[v[22]] << 7) | (dec[v[23]] << 2) | (dec[v[24]] >> 3) + (*id)[15] = (dec[v[24]] << 5) | dec[v[25]] return nil } @@ -222,9 +265,14 @@ func MustParseStrict(ulid string) ULID { return id } +// Bytes returns bytes slice representation of ULID. +func (id ULID) Bytes() []byte { + return id[:] +} + // String returns a lexicographically sortable string encoded ULID -// (26 characters, non-standard base 32) e.g. 01AN4Z07BY79KA1307SR9X4MV3 -// Format: tttttttttteeeeeeeeeeeeeeee where t is time and e is entropy +// (26 characters, non-standard base 32) e.g. 01AN4Z07BY79KA1307SR9X4MV3. +// Format: tttttttttteeeeeeeeeeeeeeee where t is time and e is entropy. func (id ULID) String() string { ulid := make([]byte, EncodedSize) _ = id.MarshalTextTo(ulid) @@ -250,7 +298,7 @@ func (id ULID) MarshalBinaryTo(dst []byte) error { } // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface by -// copying the passed data and converting it to an ULID. ErrDataSize is +// copying the passed data and converting it to a ULID. ErrDataSize is // returned if the data length is different from ULID length. func (id *ULID) UnmarshalBinary(data []byte) error { if len(data) != len(*id) { @@ -366,17 +414,28 @@ func (id ULID) Time() uint64 { uint64(id[1])<<32 | uint64(id[0])<<40 } +// Timestamp returns the time encoded in the ULID as a time.Time. +func (id ULID) Timestamp() time.Time { + return Time(id.Time()) +} + +// IsZero returns true if the ULID is a zero-value ULID, i.e. ulid.Zero. +func (id ULID) IsZero() bool { + return id.Compare(Zero) == 0 +} + // maxTime is the maximum Unix time in milliseconds that can be -// represented in an ULID. +// represented in a ULID. var maxTime = ULID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}.Time() // MaxTime returns the maximum Unix time in milliseconds that -// can be encoded in an ULID. +// can be encoded in a ULID. func MaxTime() uint64 { return maxTime } // Now is a convenience function that returns the current // UTC time in Unix milliseconds. Equivalent to: -// Timestamp(time.Now().UTC()) +// +// Timestamp(time.Now().UTC()) func Now() uint64 { return Timestamp(time.Now().UTC()) } // Timestamp converts a time.Time to Unix milliseconds. @@ -452,41 +511,62 @@ func (id *ULID) Scan(src interface{}) error { return ErrScanValue } -// Value implements the sql/driver.Valuer interface. This returns the value -// represented as a byte slice. If instead a string is desirable, a wrapper -// type can be created that calls String(). +// Value implements the sql/driver.Valuer interface, returning the ULID as a +// slice of bytes, by invoking MarshalBinary. If your use case requires a string +// representation instead, you can create a wrapper type that calls String() +// instead. // -// // stringValuer wraps a ULID as a string-based driver.Valuer. -// type stringValuer ULID +// type stringValuer ulid.ULID // -// func (id stringValuer) Value() (driver.Value, error) { -// return ULID(id).String(), nil +// func (v stringValuer) Value() (driver.Value, error) { +// return ulid.ULID(v).String(), nil // } // // // Example usage. // db.Exec("...", stringValuer(id)) +// +// All valid ULIDs, including zero-value ULIDs, return a valid Value with a nil +// error. If your use case requires zero-value ULIDs to return a non-nil error, +// you can create a wrapper type that special-cases this behavior. +// +// var zeroValueULID ulid.ULID +// +// type invalidZeroValuer ulid.ULID +// +// func (v invalidZeroValuer) Value() (driver.Value, error) { +// if ulid.ULID(v).Compare(zeroValueULID) == 0 { +// return nil, fmt.Errorf("zero value") +// } +// return ulid.ULID(v).Value() +// } +// +// // Example usage. +// db.Exec("...", invalidZeroValuer(id)) func (id ULID) Value() (driver.Value, error) { return id.MarshalBinary() } -// Monotonic returns an entropy source that is guaranteed to yield -// strictly increasing entropy bytes for the same ULID timestamp. -// On conflicts, the previous ULID entropy is incremented with a -// random number between 1 and `inc` (inclusive). +// Monotonic returns a source of entropy that yields strictly increasing entropy +// bytes, to a limit governeed by the `inc` parameter. +// +// Specifically, calls to MonotonicRead within the same ULID timestamp return +// entropy incremented by a random number between 1 and `inc` inclusive. If an +// increment results in entropy that would overflow available space, +// MonotonicRead returns ErrMonotonicOverflow. // -// The provided entropy source must actually yield random bytes or else -// monotonic reads are not guaranteed to terminate, since there isn't -// enough randomness to compute an increment number. +// Passing `inc == 0` results in the reasonable default `math.MaxUint32`. Lower +// values of `inc` provide more monotonic entropy in a single millisecond, at +// the cost of easier "guessability" of generated ULIDs. If your code depends on +// ULIDs having secure entropy bytes, then it's recommended to use the secure +// default value of `inc == 0`, unless you know what you're doing. // -// When `inc == 0`, it'll be set to a secure default of `math.MaxUint32`. -// The lower the value of `inc`, the easier the next ULID within the -// same millisecond is to guess. If your code depends on ULIDs having -// secure entropy bytes, then don't go under this default unless you know -// what you're doing. +// The provided entropy source must actually yield random bytes. Otherwise, +// monotonic reads are not guaranteed to terminate, since there isn't enough +// randomness to compute an increment number. // -// The returned io.Reader isn't safe for concurrent use. -func Monotonic(entropy io.Reader, inc uint64) io.Reader { - m := monotonic{ +// The returned type isn't safe for concurrent use. +func Monotonic(entropy io.Reader, inc uint64) *MonotonicEntropy { + m := MonotonicEntropy{ Reader: bufio.NewReader(entropy), inc: inc, } @@ -495,23 +575,42 @@ func Monotonic(entropy io.Reader, inc uint64) io.Reader { m.inc = math.MaxUint32 } - if rng, ok := entropy.(*rand.Rand); ok { + if rng, ok := entropy.(rng); ok { m.rng = rng } return &m } -type monotonic struct { +type rng interface{ Int63n(n int64) int64 } + +// LockedMonotonicReader wraps a MonotonicReader with a sync.Mutex for safe +// concurrent use. +type LockedMonotonicReader struct { + mu sync.Mutex + MonotonicReader +} + +// MonotonicRead synchronizes calls to the wrapped MonotonicReader. +func (r *LockedMonotonicReader) MonotonicRead(ms uint64, p []byte) (err error) { + r.mu.Lock() + err = r.MonotonicReader.MonotonicRead(ms, p) + r.mu.Unlock() + return err +} + +// MonotonicEntropy is an opaque type that provides monotonic entropy. +type MonotonicEntropy struct { io.Reader ms uint64 inc uint64 entropy uint80 rand [8]byte - rng *rand.Rand + rng rng } -func (m *monotonic) MonotonicRead(ms uint64, entropy []byte) (err error) { +// MonotonicRead implements the MonotonicReader interface. +func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) { if !m.entropy.IsZero() && m.ms == ms { err = m.increment() m.entropy.AppendTo(entropy) @@ -524,7 +623,7 @@ func (m *monotonic) MonotonicRead(ms uint64, entropy []byte) (err error) { // increment the previous entropy number with a random number // of up to m.inc (inclusive). -func (m *monotonic) increment() error { +func (m *MonotonicEntropy) increment() error { if inc, err := m.random(); err != nil { return err } else if m.entropy.Add(inc) { @@ -536,7 +635,7 @@ func (m *monotonic) increment() error { // random returns a uniform random value in [1, m.inc), reading entropy // from m.Reader. When m.inc == 0 || m.inc == 1, it returns 1. // Adapted from: https://golang.org/pkg/crypto/rand/#Int -func (m *monotonic) random() (inc uint64, err error) { +func (m *MonotonicEntropy) random() (inc uint64, err error) { if m.inc <= 1 { return 1, nil } diff --git a/vendor/github.com/sigstore/rekor/pkg/types/dsse/v0.0.1/entry.go b/vendor/github.com/sigstore/rekor/pkg/types/dsse/v0.0.1/entry.go index 2914bffb..2d437933 100644 --- a/vendor/github.com/sigstore/rekor/pkg/types/dsse/v0.0.1/entry.go +++ b/vendor/github.com/sigstore/rekor/pkg/types/dsse/v0.0.1/entry.go @@ -57,6 +57,24 @@ func init() { type V001Entry struct { DSSEObj models.DSSEV001Schema env *dsse.Envelope + + // memory optimization: extract and store these during Unmarshal + // so we can clear the huge payload from memory + extractedIndexKeys []string + isInsertable bool +} + +type indexKeyExtract struct { + Subject []struct { + Digest map[string]string `json:"digest"` + } `json:"subject"` + Predicate json.RawMessage `json:"predicate"` +} + +type materialsExtract struct { + Materials []struct { + Digest map[string]string `json:"digest"` + } `json:"materials"` } func (v V001Entry) APIVersion() string { @@ -108,58 +126,13 @@ func (v V001Entry) IndexKeys() ([]string, error) { return result, nil } - switch v.env.PayloadType { - case in_toto.PayloadType: - - if v.env.Payload == "" { - log.Logger.Info("DSSEObj DSSE payload is empty") - return result, nil - } - decodedPayload, err := v.env.DecodeB64Payload() - if err != nil { - return result, fmt.Errorf("could not decode envelope payload: %w", err) - } - statement, err := parseStatement(decodedPayload) - if err != nil { - return result, err - } - for _, s := range statement.Subject { - for alg, ds := range s.Digest { - result = append(result, alg+":"+ds) - } - } - // Not all in-toto statements will contain a SLSA provenance predicate. - // See https://github.com/in-toto/attestation/blob/main/spec/README.md#predicate - // for other predicates. - if predicate, err := parseSlsaPredicate(decodedPayload); err == nil { - if predicate.Predicate.Materials != nil { - for _, s := range predicate.Predicate.Materials { - for alg, ds := range s.Digest { - result = append(result, alg+":"+ds) - } - } - } - } - default: + if v.env.PayloadType == in_toto.PayloadType { + result = append(result, v.extractedIndexKeys...) + } else { log.Logger.Infof("Unknown DSSE envelope payloadType: %s", v.env.PayloadType) } - return result, nil -} - -func parseStatement(p []byte) (*in_toto.Statement, error) { - ps := in_toto.Statement{} - if err := json.Unmarshal(p, &ps); err != nil { - return nil, err - } - return &ps, nil -} -func parseSlsaPredicate(p []byte) (*in_toto.ProvenanceStatement, error) { - predicate := in_toto.ProvenanceStatement{} - if err := json.Unmarshal(p, &predicate); err != nil { - return nil, err - } - return &predicate, nil + return result, nil } // DecodeEntry performs direct decode into the provided output pointer @@ -344,6 +317,28 @@ func (v *V001Entry) Unmarshal(pe models.ProposedEntry) error { return err } + // extraction of index keys - done here so we can clear the huge strings from memory + if env.PayloadType == in_toto.PayloadType { + var extract indexKeyExtract + if err := json.Unmarshal(decodedPayload, &extract); err == nil { + for _, s := range extract.Subject { + for alg, ds := range s.Digest { + v.extractedIndexKeys = append(v.extractedIndexKeys, alg+":"+ds) + } + } + if extract.Predicate != nil { + var materials materialsExtract + if err := json.Unmarshal(extract.Predicate, &materials); err == nil { + for _, m := range materials.Materials { + for alg, ds := range m.Digest { + v.extractedIndexKeys = append(v.extractedIndexKeys, alg+":"+ds) + } + } + } + } + } + } + payloadHash := sha256.Sum256(decodedPayload) dsseObj.PayloadHash = &models.DSSEV001SchemaPayloadHash{ Algorithm: conv.Pointer(models.DSSEV001SchemaPayloadHashAlgorithmSha256), @@ -359,6 +354,11 @@ func (v *V001Entry) Unmarshal(pe models.ProposedEntry) error { // we've gotten through all processing without error, now update the object we're unmarshalling into v.DSSEObj = *dsseObj v.env = env + v.isInsertable = true + + // memory optimization: clear huge strings/buffers + v.env.Payload = "" + v.DSSEObj.ProposedContent = nil return nil } @@ -533,6 +533,9 @@ func (v V001Entry) ArtifactHash() (string, error) { } func (v V001Entry) Insertable() (bool, error) { + if v.isInsertable { + return true, nil + } if v.DSSEObj.ProposedContent == nil { return false, errors.New("missing proposed content") } diff --git a/vendor/github.com/sigstore/rekor/pkg/verify/verify.go b/vendor/github.com/sigstore/rekor/pkg/verify/verify.go index 61846923..7081d34d 100644 --- a/vendor/github.com/sigstore/rekor/pkg/verify/verify.go +++ b/vendor/github.com/sigstore/rekor/pkg/verify/verify.go @@ -145,7 +145,10 @@ func VerifyInclusion(ctx context.Context, e *models.LogEntryAnon) error { hashes := [][]byte{} for _, h := range e.Verification.InclusionProof.Hashes { - hb, _ := hex.DecodeString(h) + hb, err := hex.DecodeString(h) + if err != nil { + return err + } hashes = append(hashes, hb) } @@ -155,7 +158,11 @@ func VerifyInclusion(ctx context.Context, e *models.LogEntryAnon) error { } // Verify the inclusion proof. - entryBytes, err := base64.StdEncoding.DecodeString(e.Body.(string)) + b, ok := e.Body.(string) + if !ok { + return fmt.Errorf("entry body must be a string, was %T", e.Body) + } + entryBytes, err := base64.StdEncoding.DecodeString(b) if err != nil { return err } 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 a0d81858..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. - -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. -// -// A D should not be constructed with duplicate key names, as that can cause undefined server behavior. -// -// 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/bsoncodec/array_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/array_codec.go deleted file mode 100644 index 652aa48b..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/array_codec.go +++ /dev/null @@ -1,55 +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" - "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" -) - -// ArrayCodec is the Codec used for bsoncore.Array values. -// -// Deprecated: ArrayCodec will not be directly accessible in Go Driver 2.0. -type ArrayCodec struct{} - -var defaultArrayCodec = NewArrayCodec() - -// NewArrayCodec returns an ArrayCodec. -// -// Deprecated: NewArrayCodec will not be available in Go Driver 2.0. See -// [ArrayCodec] for more details. -func NewArrayCodec() *ArrayCodec { - return &ArrayCodec{} -} - -// EncodeValue is the ValueEncoder for bsoncore.Array values. -func (ac *ArrayCodec) EncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { - if !val.IsValid() || val.Type() != tCoreArray { - return ValueEncoderError{Name: "CoreArrayEncodeValue", Types: []reflect.Type{tCoreArray}, Received: val} - } - - arr := val.Interface().(bsoncore.Array) - return bsonrw.Copier{}.CopyArrayFromBytes(vw, arr) -} - -// DecodeValue is the ValueDecoder for bsoncore.Array values. -func (ac *ArrayCodec) DecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { - if !val.CanSet() || val.Type() != tCoreArray { - return ValueDecoderError{Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, Received: val} - } - - if val.IsNil() { - val.Set(reflect.MakeSlice(val.Type(), 0, 0)) - } - - val.SetLen(0) - arr, err := bsonrw.Copier{}.AppendArrayBytes(val.Interface().(bsoncore.Array), vr) - val.Set(reflect.ValueOf(arr)) - return err -} 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 0693bd43..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go +++ /dev/null @@ -1,382 +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" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -var ( - emptyValue = reflect.Value{} -) - -// 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Marshaler] instead. -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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.ValueMarshaler] instead. -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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Unmarshaler] instead. -type Unmarshaler interface { - UnmarshalBSON([]byte) error -} - -// ValueUnmarshaler is an interface implemented by types that can unmarshal a -// BSON value representation 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.ValueUnmarshaler] instead. -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 causes the Encoder to marshal Go integer values (int, int8, int16, int32, int64, - // uint, uint8, uint16, uint32, or uint64) as the minimum BSON int size (either 32 or 64 bits) - // that can represent the integer value. - // - // Deprecated: Use bson.Encoder.IntMinSize instead. - MinSize bool - - errorOnInlineDuplicates bool - stringifyMapKeysWithFmt bool - nilMapAsEmpty bool - nilSliceAsEmpty bool - nilByteSliceAsEmpty bool - omitZeroStruct bool - useJSONStructTags bool -} - -// ErrorOnInlineDuplicates causes the Encoder to return an error if there is a duplicate field in -// the marshaled BSON when the "inline" struct tag option is set. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.ErrorOnInlineDuplicates] instead. -func (ec *EncodeContext) ErrorOnInlineDuplicates() { - ec.errorOnInlineDuplicates = true -} - -// StringifyMapKeysWithFmt causes the Encoder to convert Go map keys to BSON document field name -// strings using fmt.Sprintf() instead of the default string conversion logic. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.StringifyMapKeysWithFmt] instead. -func (ec *EncodeContext) StringifyMapKeysWithFmt() { - ec.stringifyMapKeysWithFmt = true -} - -// NilMapAsEmpty causes the Encoder to marshal nil Go maps as empty BSON documents instead of BSON -// null. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilMapAsEmpty] instead. -func (ec *EncodeContext) NilMapAsEmpty() { - ec.nilMapAsEmpty = true -} - -// NilSliceAsEmpty causes the Encoder to marshal nil Go slices as empty BSON arrays instead of BSON -// null. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilSliceAsEmpty] instead. -func (ec *EncodeContext) NilSliceAsEmpty() { - ec.nilSliceAsEmpty = true -} - -// NilByteSliceAsEmpty causes the Encoder to marshal nil Go byte slices as empty BSON binary values -// instead of BSON null. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilByteSliceAsEmpty] instead. -func (ec *EncodeContext) NilByteSliceAsEmpty() { - ec.nilByteSliceAsEmpty = true -} - -// OmitZeroStruct causes the Encoder to consider the zero value for a struct (e.g. MyStruct{}) -// as empty and omit it from the marshaled BSON when the "omitempty" struct tag option is set. -// -// Note that the Encoder only examines exported struct fields when determining if a struct is the -// zero value. It considers pointers to a zero struct value (e.g. &MyStruct{}) not empty. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.OmitZeroStruct] instead. -func (ec *EncodeContext) OmitZeroStruct() { - ec.omitZeroStruct = true -} - -// UseJSONStructTags causes the Encoder to fall back to using the "json" struct tag if a "bson" -// struct tag is not specified. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.UseJSONStructTags] instead. -func (ec *EncodeContext) UseJSONStructTags() { - ec.useJSONStructTags = true -} - -// DecodeContext is the contextual information required for a Codec to decode a -// value. -type DecodeContext struct { - *Registry - - // Truncate, if true, instructs decoders to to truncate the fractional part of BSON "double" - // values when attempting to unmarshal them into a Go integer (int, int8, int16, int32, int64, - // uint, uint8, uint16, uint32, or uint64) struct field. The truncation logic does not apply to - // BSON "decimal128" values. - // - // Deprecated: Use bson.Decoder.AllowTruncatingDoubles instead. - 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. - // - // Deprecated: Use bson.Decoder.DefaultDocumentM or bson.Decoder.DefaultDocumentD instead. - Ancestor reflect.Type - - // defaultDocumentType specifies the Go type to decode top-level and nested BSON documents into. In particular, the - // usage for this field is restricted to data typed as "interface{}" or "map[string]interface{}". If DocumentType is - // set to a type that a BSON document cannot be unmarshaled into (e.g. "string"), unmarshalling will result in an - // error. DocumentType overrides the Ancestor field. - defaultDocumentType reflect.Type - - binaryAsSlice bool - useJSONStructTags bool - useLocalTimeZone bool - zeroMaps bool - zeroStructs bool -} - -// BinaryAsSlice causes the Decoder to unmarshal BSON binary field values that are the "Generic" or -// "Old" BSON binary subtype as a Go byte slice instead of a primitive.Binary. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.BinaryAsSlice] instead. -func (dc *DecodeContext) BinaryAsSlice() { - dc.binaryAsSlice = true -} - -// UseJSONStructTags causes the Decoder to fall back to using the "json" struct tag if a "bson" -// struct tag is not specified. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.UseJSONStructTags] instead. -func (dc *DecodeContext) UseJSONStructTags() { - dc.useJSONStructTags = true -} - -// UseLocalTimeZone causes the Decoder to unmarshal time.Time values in the local timezone instead -// of the UTC timezone. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.UseLocalTimeZone] instead. -func (dc *DecodeContext) UseLocalTimeZone() { - dc.useLocalTimeZone = true -} - -// ZeroMaps causes the Decoder to delete any existing values from Go maps in the destination value -// passed to Decode before unmarshaling BSON documents into them. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.ZeroMaps] instead. -func (dc *DecodeContext) ZeroMaps() { - dc.zeroMaps = true -} - -// ZeroStructs causes the Decoder to delete any existing values from Go structs in the destination -// value passed to Decode before unmarshaling BSON documents into them. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.ZeroStructs] instead. -func (dc *DecodeContext) ZeroStructs() { - dc.zeroStructs = true -} - -// DefaultDocumentM causes the Decoder to always unmarshal documents into the primitive.M type. This -// behavior is restricted to data typed as "interface{}" or "map[string]interface{}". -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.DefaultDocumentM] instead. -func (dc *DecodeContext) DefaultDocumentM() { - dc.defaultDocumentType = reflect.TypeOf(primitive.M{}) -} - -// DefaultDocumentD causes the Decoder to always unmarshal documents into the primitive.D type. This -// behavior is restricted to data typed as "interface{}" or "map[string]interface{}". -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.DefaultDocumentD] instead. -func (dc *DecodeContext) DefaultDocumentD() { - dc.defaultDocumentType = reflect.TypeOf(primitive.D{}) -} - -// ValueCodec is an interface for encoding and decoding a reflect.Value. -// values. -// -// Deprecated: Use [ValueEncoder] and [ValueDecoder] instead. -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) -} - -// typeDecoder is the interface implemented by types that can handle the decoding of a value given its type. -type typeDecoder interface { - decodeType(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error) -} - -// typeDecoderFunc is an adapter function that allows a function with the correct signature to be used as a typeDecoder. -type typeDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error) - -func (fn typeDecoderFunc) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - return fn(dc, vr, t) -} - -// decodeAdapter allows two functions with the correct signatures to be used as both a ValueDecoder and typeDecoder. -type decodeAdapter struct { - ValueDecoderFunc - typeDecoderFunc -} - -var _ ValueDecoder = decodeAdapter{} -var _ typeDecoder = decodeAdapter{} - -// decodeTypeOrValue calls decoder.decodeType is decoder is a typeDecoder. Otherwise, it allocates a new element of type -// t and calls decoder.DecodeValue on it. -func decodeTypeOrValue(decoder ValueDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - td, _ := decoder.(typeDecoder) - return decodeTypeOrValueWithInfo(decoder, td, dc, vr, t, true) -} - -func decodeTypeOrValueWithInfo(vd ValueDecoder, td typeDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type, convert bool) (reflect.Value, error) { - if td != nil { - val, err := td.decodeType(dc, vr, t) - if err == nil && convert && val.Type() != t { - // This conversion step is necessary for slices and maps. If a user declares variables like: - // - // type myBool bool - // var m map[string]myBool - // - // and tries to decode BSON bytes into the map, the decoding will fail if this conversion is not present - // because we'll try to assign a value of type bool to one of type myBool. - val = val.Convert(t) - } - return val, err - } - - val := reflect.New(t).Elem() - err := vd.DecodeValue(dc, vr, val) - return val, err -} - -// CodecZeroer is the interface implemented by Codecs that can also determine if -// a value of the type that would be encoded is zero. -// -// Deprecated: Defining custom rules for the zero/empty value will not be supported in Go Driver -// 2.0. Users who want to omit empty complex values should use a pointer field and set the value to -// nil instead. -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 0134b5a9..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/byte_slice_codec.go +++ /dev/null @@ -1,138 +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" -) - -// ByteSliceCodec is the Codec used for []byte values. -// -// Deprecated: ByteSliceCodec will not be directly configurable in Go Driver -// 2.0. To configure the byte slice encode and decode behavior, use the -// configuration methods on a [go.mongodb.org/mongo-driver/bson.Encoder] or -// [go.mongodb.org/mongo-driver/bson.Decoder]. To configure the byte slice -// encode and decode behavior for a mongo.Client, use -// [go.mongodb.org/mongo-driver/mongo/options.ClientOptions.SetBSONOptions]. -// -// For example, to configure a mongo.Client to encode nil byte slices as empty -// BSON binary values, use: -// -// opt := options.Client().SetBSONOptions(&options.BSONOptions{ -// NilByteSliceAsEmpty: true, -// }) -// -// See the deprecation notice for each field in ByteSliceCodec for the -// corresponding settings. -type ByteSliceCodec struct { - // EncodeNilAsEmpty causes EncodeValue to marshal nil Go byte slices as empty BSON binary values - // instead of BSON null. - // - // Deprecated: Use bson.Encoder.NilByteSliceAsEmpty or options.BSONOptions.NilByteSliceAsEmpty - // instead. - EncodeNilAsEmpty bool -} - -var ( - defaultByteSliceCodec = NewByteSliceCodec() - - // Assert that defaultByteSliceCodec satisfies the typeDecoder interface, which allows it to be - // used by collection type decoders (e.g. map, slice, etc) to set individual values in a - // collection. - _ typeDecoder = defaultByteSliceCodec -) - -// NewByteSliceCodec returns a ByteSliceCodec with options opts. -// -// Deprecated: NewByteSliceCodec will not be available in Go Driver 2.0. See -// [ByteSliceCodec] for more details. -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 && !ec.nilByteSliceAsEmpty { - return vw.WriteNull() - } - return vw.WriteBinary(val.Interface().([]byte)) -} - -func (bsc *ByteSliceCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tByteSlice { - return emptyValue, ValueDecoderError{ - Name: "ByteSliceDecodeValue", - Types: []reflect.Type{tByteSlice}, - Received: reflect.Zero(t), - } - } - - var data []byte - var err error - switch vrType := vr.Type(); vrType { - case bsontype.String: - str, err := vr.ReadString() - if err != nil { - return emptyValue, err - } - data = []byte(str) - case bsontype.Symbol: - sym, err := vr.ReadSymbol() - if err != nil { - return emptyValue, err - } - data = []byte(sym) - case bsontype.Binary: - var subtype byte - data, subtype, err = vr.ReadBinary() - if err != nil { - return emptyValue, err - } - if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld { - return emptyValue, decodeBinaryError{subtype: subtype, typeName: "[]byte"} - } - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a []byte", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(data), nil -} - -// 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} - } - - elem, err := bsc.decodeType(dc, vr, tByteSlice) - if err != nil { - return err - } - - val.Set(elem) - return nil -} diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/codec_cache.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/codec_cache.go deleted file mode 100644 index 844b5029..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/codec_cache.go +++ /dev/null @@ -1,166 +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" - "sync/atomic" -) - -// Runtime check that the kind encoder and decoder caches can store any valid -// reflect.Kind constant. -func init() { - if s := reflect.Kind(len(kindEncoderCache{}.entries)).String(); s != "kind27" { - panic("The capacity of kindEncoderCache is too small.\n" + - "This is due to a new type being added to reflect.Kind.") - } -} - -// statically assert array size -var _ = (kindEncoderCache{}).entries[reflect.UnsafePointer] -var _ = (kindDecoderCache{}).entries[reflect.UnsafePointer] - -type typeEncoderCache struct { - cache sync.Map // map[reflect.Type]ValueEncoder -} - -func (c *typeEncoderCache) Store(rt reflect.Type, enc ValueEncoder) { - c.cache.Store(rt, enc) -} - -func (c *typeEncoderCache) Load(rt reflect.Type) (ValueEncoder, bool) { - if v, _ := c.cache.Load(rt); v != nil { - return v.(ValueEncoder), true - } - return nil, false -} - -func (c *typeEncoderCache) LoadOrStore(rt reflect.Type, enc ValueEncoder) ValueEncoder { - if v, loaded := c.cache.LoadOrStore(rt, enc); loaded { - enc = v.(ValueEncoder) - } - return enc -} - -func (c *typeEncoderCache) Clone() *typeEncoderCache { - cc := new(typeEncoderCache) - c.cache.Range(func(k, v interface{}) bool { - if k != nil && v != nil { - cc.cache.Store(k, v) - } - return true - }) - return cc -} - -type typeDecoderCache struct { - cache sync.Map // map[reflect.Type]ValueDecoder -} - -func (c *typeDecoderCache) Store(rt reflect.Type, dec ValueDecoder) { - c.cache.Store(rt, dec) -} - -func (c *typeDecoderCache) Load(rt reflect.Type) (ValueDecoder, bool) { - if v, _ := c.cache.Load(rt); v != nil { - return v.(ValueDecoder), true - } - return nil, false -} - -func (c *typeDecoderCache) LoadOrStore(rt reflect.Type, dec ValueDecoder) ValueDecoder { - if v, loaded := c.cache.LoadOrStore(rt, dec); loaded { - dec = v.(ValueDecoder) - } - return dec -} - -func (c *typeDecoderCache) Clone() *typeDecoderCache { - cc := new(typeDecoderCache) - c.cache.Range(func(k, v interface{}) bool { - if k != nil && v != nil { - cc.cache.Store(k, v) - } - return true - }) - return cc -} - -// atomic.Value requires that all calls to Store() have the same concrete type -// so we wrap the ValueEncoder with a kindEncoderCacheEntry to ensure the type -// is always the same (since different concrete types may implement the -// ValueEncoder interface). -type kindEncoderCacheEntry struct { - enc ValueEncoder -} - -type kindEncoderCache struct { - entries [reflect.UnsafePointer + 1]atomic.Value // *kindEncoderCacheEntry -} - -func (c *kindEncoderCache) Store(rt reflect.Kind, enc ValueEncoder) { - if enc != nil && rt < reflect.Kind(len(c.entries)) { - c.entries[rt].Store(&kindEncoderCacheEntry{enc: enc}) - } -} - -func (c *kindEncoderCache) Load(rt reflect.Kind) (ValueEncoder, bool) { - if rt < reflect.Kind(len(c.entries)) { - if ent, ok := c.entries[rt].Load().(*kindEncoderCacheEntry); ok { - return ent.enc, ent.enc != nil - } - } - return nil, false -} - -func (c *kindEncoderCache) Clone() *kindEncoderCache { - cc := new(kindEncoderCache) - for i, v := range c.entries { - if val := v.Load(); val != nil { - cc.entries[i].Store(val) - } - } - return cc -} - -// atomic.Value requires that all calls to Store() have the same concrete type -// so we wrap the ValueDecoder with a kindDecoderCacheEntry to ensure the type -// is always the same (since different concrete types may implement the -// ValueDecoder interface). -type kindDecoderCacheEntry struct { - dec ValueDecoder -} - -type kindDecoderCache struct { - entries [reflect.UnsafePointer + 1]atomic.Value // *kindDecoderCacheEntry -} - -func (c *kindDecoderCache) Store(rt reflect.Kind, dec ValueDecoder) { - if rt < reflect.Kind(len(c.entries)) { - c.entries[rt].Store(&kindDecoderCacheEntry{dec: dec}) - } -} - -func (c *kindDecoderCache) Load(rt reflect.Kind) (ValueDecoder, bool) { - if rt < reflect.Kind(len(c.entries)) { - if ent, ok := c.entries[rt].Load().(*kindDecoderCacheEntry); ok { - return ent.dec, ent.dec != nil - } - } - return nil, false -} - -func (c *kindDecoderCache) Clone() *kindDecoderCache { - cc := new(kindDecoderCache) - for i, v := range c.entries { - if val := v.Load(); val != nil { - cc.entries[i].Store(val) - } - } - return cc -} 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 8702d6d3..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go +++ /dev/null @@ -1,1819 +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 - errCannotTruncate = errors.New("float64 can only be truncated to a lower precision type when truncation is enabled") -) - -type decodeBinaryError struct { - subtype byte - typeName string -} - -func (d decodeBinaryError) Error() string { - return fmt.Sprintf("only binary values with subtype 0x00 or 0x02 can be decoded into %s, but got subtype %v", d.typeName, d.subtype) -} - -func newDefaultStructCodec() *StructCodec { - codec, err := NewStructCodec(DefaultStructTagParser) - if err != nil { - // This function is called from the codec registration path, so errors can't be propagated. If there's an error - // constructing the StructCodec, we panic to avoid losing it. - panic(fmt.Errorf("error creating default StructCodec: %w", err)) - } - return codec -} - -// DefaultValueDecoders is a namespace type for the default ValueDecoders used -// when creating a registry. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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{} because there is no decoder for -// interface{}, so users must either register this decoder themselves or use the -// EmptyInterfaceDecoder available in the bson package. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) RegisterDefaultDecoders(rb *RegistryBuilder) { - if rb == nil { - panic(errors.New("argument to RegisterDefaultDecoders must not be nil")) - } - - intDecoder := decodeAdapter{dvd.IntDecodeValue, dvd.intDecodeType} - floatDecoder := decodeAdapter{dvd.FloatDecodeValue, dvd.floatDecodeType} - - rb. - RegisterTypeDecoder(tD, ValueDecoderFunc(dvd.DDecodeValue)). - RegisterTypeDecoder(tBinary, decodeAdapter{dvd.BinaryDecodeValue, dvd.binaryDecodeType}). - RegisterTypeDecoder(tUndefined, decodeAdapter{dvd.UndefinedDecodeValue, dvd.undefinedDecodeType}). - RegisterTypeDecoder(tDateTime, decodeAdapter{dvd.DateTimeDecodeValue, dvd.dateTimeDecodeType}). - RegisterTypeDecoder(tNull, decodeAdapter{dvd.NullDecodeValue, dvd.nullDecodeType}). - RegisterTypeDecoder(tRegex, decodeAdapter{dvd.RegexDecodeValue, dvd.regexDecodeType}). - RegisterTypeDecoder(tDBPointer, decodeAdapter{dvd.DBPointerDecodeValue, dvd.dBPointerDecodeType}). - RegisterTypeDecoder(tTimestamp, decodeAdapter{dvd.TimestampDecodeValue, dvd.timestampDecodeType}). - RegisterTypeDecoder(tMinKey, decodeAdapter{dvd.MinKeyDecodeValue, dvd.minKeyDecodeType}). - RegisterTypeDecoder(tMaxKey, decodeAdapter{dvd.MaxKeyDecodeValue, dvd.maxKeyDecodeType}). - RegisterTypeDecoder(tJavaScript, decodeAdapter{dvd.JavaScriptDecodeValue, dvd.javaScriptDecodeType}). - RegisterTypeDecoder(tSymbol, decodeAdapter{dvd.SymbolDecodeValue, dvd.symbolDecodeType}). - RegisterTypeDecoder(tByteSlice, defaultByteSliceCodec). - RegisterTypeDecoder(tTime, defaultTimeCodec). - RegisterTypeDecoder(tEmpty, defaultEmptyInterfaceCodec). - RegisterTypeDecoder(tCoreArray, defaultArrayCodec). - RegisterTypeDecoder(tOID, decodeAdapter{dvd.ObjectIDDecodeValue, dvd.objectIDDecodeType}). - RegisterTypeDecoder(tDecimal, decodeAdapter{dvd.Decimal128DecodeValue, dvd.decimal128DecodeType}). - RegisterTypeDecoder(tJSONNumber, decodeAdapter{dvd.JSONNumberDecodeValue, dvd.jsonNumberDecodeType}). - RegisterTypeDecoder(tURL, decodeAdapter{dvd.URLDecodeValue, dvd.urlDecodeType}). - RegisterTypeDecoder(tCoreDocument, ValueDecoderFunc(dvd.CoreDocumentDecodeValue)). - RegisterTypeDecoder(tCodeWithScope, decodeAdapter{dvd.CodeWithScopeDecodeValue, dvd.codeWithScopeDecodeType}). - RegisterDefaultDecoder(reflect.Bool, decodeAdapter{dvd.BooleanDecodeValue, dvd.booleanDecodeType}). - RegisterDefaultDecoder(reflect.Int, intDecoder). - RegisterDefaultDecoder(reflect.Int8, intDecoder). - RegisterDefaultDecoder(reflect.Int16, intDecoder). - RegisterDefaultDecoder(reflect.Int32, intDecoder). - RegisterDefaultDecoder(reflect.Int64, intDecoder). - RegisterDefaultDecoder(reflect.Uint, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint8, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint16, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint32, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Uint64, defaultUIntCodec). - RegisterDefaultDecoder(reflect.Float32, floatDecoder). - RegisterDefaultDecoder(reflect.Float64, floatDecoder). - RegisterDefaultDecoder(reflect.Array, ValueDecoderFunc(dvd.ArrayDecodeValue)). - RegisterDefaultDecoder(reflect.Map, defaultMapCodec). - RegisterDefaultDecoder(reflect.Slice, defaultSliceCodec). - RegisterDefaultDecoder(reflect.String, defaultStringCodec). - RegisterDefaultDecoder(reflect.Struct, newDefaultStructCodec()). - 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)) -} - -// DDecodeValue is the ValueDecoderFunc for primitive.D instances. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) DDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { - if !val.IsValid() || !val.CanSet() || val.Type() != tD { - return ValueDecoderError{Name: "DDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} - } - - switch vrType := vr.Type(); vrType { - case bsontype.Type(0), bsontype.EmbeddedDocument: - dc.Ancestor = tD - case bsontype.Null: - val.Set(reflect.Zero(val.Type())) - return vr.ReadNull() - default: - return fmt.Errorf("cannot decode %v into a primitive.D", vrType) - } - - dr, err := vr.ReadDocument() - if err != nil { - return err - } - - decoder, err := dc.LookupDecoder(tEmpty) - if err != nil { - return err - } - tEmptyTypeDecoder, _ := decoder.(typeDecoder) - - // Use the elements in the provided value if it's non nil. Otherwise, allocate a new D instance. - var elems primitive.D - if !val.IsNil() { - val.SetLen(0) - elems = val.Interface().(primitive.D) - } else { - elems = make(primitive.D, 0) - } - - for { - key, elemVr, err := dr.ReadElement() - if errors.Is(err, bsonrw.ErrEOD) { - break - } else if err != nil { - return err - } - - // Pass false for convert because we don't need to call reflect.Value.Convert for tEmpty. - elem, err := decodeTypeOrValueWithInfo(decoder, tEmptyTypeDecoder, dc, elemVr, tEmpty, false) - if err != nil { - return err - } - - elems = append(elems, primitive.E{Key: key, Value: elem.Interface()}) - } - - val.Set(reflect.ValueOf(elems)) - return nil -} - -func (dvd DefaultValueDecoders) booleanDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t.Kind() != reflect.Bool { - return emptyValue, ValueDecoderError{ - Name: "BooleanDecodeValue", - Kinds: []reflect.Kind{reflect.Bool}, - Received: reflect.Zero(t), - } - } - - var b bool - var err error - switch vrType := vr.Type(); vrType { - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return emptyValue, err - } - b = (i32 != 0) - case bsontype.Int64: - i64, err := vr.ReadInt64() - if err != nil { - return emptyValue, err - } - b = (i64 != 0) - case bsontype.Double: - f64, err := vr.ReadDouble() - if err != nil { - return emptyValue, err - } - b = (f64 != 0) - case bsontype.Boolean: - b, err = vr.ReadBoolean() - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a boolean", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(b), nil -} - -// BooleanDecodeValue is the ValueDecoderFunc for bool types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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} - } - - elem, err := dvd.booleanDecodeType(dctx, vr, val.Type()) - if err != nil { - return err - } - - val.SetBool(elem.Bool()) - return nil -} - -func (DefaultValueDecoders) intDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - var i64 int64 - var err error - switch vrType := vr.Type(); vrType { - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return emptyValue, err - } - i64 = int64(i32) - case bsontype.Int64: - i64, err = vr.ReadInt64() - if err != nil { - return emptyValue, err - } - case bsontype.Double: - f64, err := vr.ReadDouble() - if err != nil { - return emptyValue, err - } - if !dc.Truncate && math.Floor(f64) != f64 { - return emptyValue, errCannotTruncate - } - if f64 > float64(math.MaxInt64) { - return emptyValue, fmt.Errorf("%g overflows int64", f64) - } - i64 = int64(f64) - case bsontype.Boolean: - b, err := vr.ReadBoolean() - if err != nil { - return emptyValue, err - } - if b { - i64 = 1 - } - case bsontype.Null: - if err = vr.ReadNull(); err != nil { - return emptyValue, err - } - case bsontype.Undefined: - if err = vr.ReadUndefined(); err != nil { - return emptyValue, err - } - default: - return emptyValue, fmt.Errorf("cannot decode %v into an integer type", vrType) - } - - switch t.Kind() { - case reflect.Int8: - if i64 < math.MinInt8 || i64 > math.MaxInt8 { - return emptyValue, fmt.Errorf("%d overflows int8", i64) - } - - return reflect.ValueOf(int8(i64)), nil - case reflect.Int16: - if i64 < math.MinInt16 || i64 > math.MaxInt16 { - return emptyValue, fmt.Errorf("%d overflows int16", i64) - } - - return reflect.ValueOf(int16(i64)), nil - case reflect.Int32: - if i64 < math.MinInt32 || i64 > math.MaxInt32 { - return emptyValue, fmt.Errorf("%d overflows int32", i64) - } - - return reflect.ValueOf(int32(i64)), nil - case reflect.Int64: - return reflect.ValueOf(i64), nil - case reflect.Int: - if i64 > math.MaxInt { // Can we fit this inside of an int - return emptyValue, fmt.Errorf("%d overflows int", i64) - } - - return reflect.ValueOf(int(i64)), nil - default: - return emptyValue, ValueDecoderError{ - Name: "IntDecodeValue", - Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, - Received: reflect.Zero(t), - } - } -} - -// IntDecodeValue is the ValueDecoderFunc for int types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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, - } - } - - elem, err := dvd.intDecodeType(dc, vr, val.Type()) - if err != nil { - return err - } - - val.SetInt(elem.Int()) - return nil -} - -// UintDecodeValue is the ValueDecoderFunc for uint types. -// -// Deprecated: UintDecodeValue is not registered by default. 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 || uint64(i64) > uint64(math.MaxUint) { // 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 -} - -func (dvd DefaultValueDecoders) floatDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - var f float64 - var err error - switch vrType := vr.Type(); vrType { - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return emptyValue, err - } - f = float64(i32) - case bsontype.Int64: - i64, err := vr.ReadInt64() - if err != nil { - return emptyValue, err - } - f = float64(i64) - case bsontype.Double: - f, err = vr.ReadDouble() - if err != nil { - return emptyValue, err - } - case bsontype.Boolean: - b, err := vr.ReadBoolean() - if err != nil { - return emptyValue, err - } - if b { - f = 1 - } - case bsontype.Null: - if err = vr.ReadNull(); err != nil { - return emptyValue, err - } - case bsontype.Undefined: - if err = vr.ReadUndefined(); err != nil { - return emptyValue, err - } - default: - return emptyValue, fmt.Errorf("cannot decode %v into a float32 or float64 type", vrType) - } - - switch t.Kind() { - case reflect.Float32: - if !dc.Truncate && float64(float32(f)) != f { - return emptyValue, errCannotTruncate - } - - return reflect.ValueOf(float32(f)), nil - case reflect.Float64: - return reflect.ValueOf(f), nil - default: - return emptyValue, ValueDecoderError{ - Name: "FloatDecodeValue", - Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, - Received: reflect.Zero(t), - } - } -} - -// FloatDecodeValue is the ValueDecoderFunc for float types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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, - } - } - - elem, err := dvd.floatDecodeType(ec, vr, val.Type()) - if err != nil { - return err - } - - val.SetFloat(elem.Float()) - return nil -} - -// StringDecodeValue is the ValueDecoderFunc for string types. -// -// Deprecated: StringDecodeValue is not registered by default. Use StringCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) StringDecodeValue(_ 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 -} - -func (DefaultValueDecoders) javaScriptDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tJavaScript { - return emptyValue, ValueDecoderError{ - Name: "JavaScriptDecodeValue", - Types: []reflect.Type{tJavaScript}, - Received: reflect.Zero(t), - } - } - - var js string - var err error - switch vrType := vr.Type(); vrType { - case bsontype.JavaScript: - js, err = vr.ReadJavascript() - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.JavaScript", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.JavaScript(js)), nil -} - -// JavaScriptDecodeValue is the ValueDecoderFunc for the primitive.JavaScript type. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.javaScriptDecodeType(dctx, vr, tJavaScript) - if err != nil { - return err - } - - val.SetString(elem.String()) - return nil -} - -func (DefaultValueDecoders) symbolDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tSymbol { - return emptyValue, ValueDecoderError{ - Name: "SymbolDecodeValue", - Types: []reflect.Type{tSymbol}, - Received: reflect.Zero(t), - } - } - - var symbol string - var err error - switch vrType := vr.Type(); vrType { - case bsontype.String: - symbol, err = vr.ReadString() - case bsontype.Symbol: - symbol, err = vr.ReadSymbol() - case bsontype.Binary: - data, subtype, err := vr.ReadBinary() - if err != nil { - return emptyValue, err - } - - if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld { - return emptyValue, decodeBinaryError{subtype: subtype, typeName: "primitive.Symbol"} - } - symbol = string(data) - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.Symbol", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.Symbol(symbol)), nil -} - -// SymbolDecodeValue is the ValueDecoderFunc for the primitive.Symbol type. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.symbolDecodeType(dctx, vr, tSymbol) - if err != nil { - return err - } - - val.SetString(elem.String()) - return nil -} - -func (DefaultValueDecoders) binaryDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tBinary { - return emptyValue, ValueDecoderError{ - Name: "BinaryDecodeValue", - Types: []reflect.Type{tBinary}, - Received: reflect.Zero(t), - } - } - - 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() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a Binary", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.Binary{Subtype: subtype, Data: data}), nil -} - -// BinaryDecodeValue is the ValueDecoderFunc for Binary. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.binaryDecodeType(dc, vr, tBinary) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) undefinedDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tUndefined { - return emptyValue, ValueDecoderError{ - Name: "UndefinedDecodeValue", - Types: []reflect.Type{tUndefined}, - Received: reflect.Zero(t), - } - } - - var err error - switch vrType := vr.Type(); vrType { - case bsontype.Undefined: - err = vr.ReadUndefined() - case bsontype.Null: - err = vr.ReadNull() - default: - return emptyValue, fmt.Errorf("cannot decode %v into an Undefined", vr.Type()) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.Undefined{}), nil -} - -// UndefinedDecodeValue is the ValueDecoderFunc for Undefined. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.undefinedDecodeType(dc, vr, tUndefined) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -// Accept both 12-byte string and pretty-printed 24-byte hex string formats. -func (dvd DefaultValueDecoders) objectIDDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tOID { - return emptyValue, ValueDecoderError{ - Name: "ObjectIDDecodeValue", - Types: []reflect.Type{tOID}, - Received: reflect.Zero(t), - } - } - - var oid primitive.ObjectID - var err error - switch vrType := vr.Type(); vrType { - case bsontype.ObjectID: - oid, err = vr.ReadObjectID() - if err != nil { - return emptyValue, err - } - case bsontype.String: - str, err := vr.ReadString() - if err != nil { - return emptyValue, err - } - if oid, err = primitive.ObjectIDFromHex(str); err == nil { - break - } - if len(str) != 12 { - return emptyValue, 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 emptyValue, err - } - case bsontype.Undefined: - if err = vr.ReadUndefined(); err != nil { - return emptyValue, err - } - default: - return emptyValue, fmt.Errorf("cannot decode %v into an ObjectID", vrType) - } - - return reflect.ValueOf(oid), nil -} - -// ObjectIDDecodeValue is the ValueDecoderFunc for primitive.ObjectID. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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} - } - - elem, err := dvd.objectIDDecodeType(dc, vr, tOID) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) dateTimeDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tDateTime { - return emptyValue, ValueDecoderError{ - Name: "DateTimeDecodeValue", - Types: []reflect.Type{tDateTime}, - Received: reflect.Zero(t), - } - } - - var dt int64 - var err error - switch vrType := vr.Type(); vrType { - case bsontype.DateTime: - dt, err = vr.ReadDateTime() - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a DateTime", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.DateTime(dt)), nil -} - -// DateTimeDecodeValue is the ValueDecoderFunc for DateTime. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.dateTimeDecodeType(dc, vr, tDateTime) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) nullDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tNull { - return emptyValue, ValueDecoderError{ - Name: "NullDecodeValue", - Types: []reflect.Type{tNull}, - Received: reflect.Zero(t), - } - } - - var err error - switch vrType := vr.Type(); vrType { - case bsontype.Undefined: - err = vr.ReadUndefined() - case bsontype.Null: - err = vr.ReadNull() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a Null", vr.Type()) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.Null{}), nil -} - -// NullDecodeValue is the ValueDecoderFunc for Null. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.nullDecodeType(dc, vr, tNull) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) regexDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tRegex { - return emptyValue, ValueDecoderError{ - Name: "RegexDecodeValue", - Types: []reflect.Type{tRegex}, - Received: reflect.Zero(t), - } - } - - 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() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a Regex", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.Regex{Pattern: pattern, Options: options}), nil -} - -// RegexDecodeValue is the ValueDecoderFunc for Regex. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.regexDecodeType(dc, vr, tRegex) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) dBPointerDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tDBPointer { - return emptyValue, ValueDecoderError{ - Name: "DBPointerDecodeValue", - Types: []reflect.Type{tDBPointer}, - Received: reflect.Zero(t), - } - } - - 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() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a DBPointer", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.DBPointer{DB: ns, Pointer: pointer}), nil -} - -// DBPointerDecodeValue is the ValueDecoderFunc for DBPointer. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.dBPointerDecodeType(dc, vr, tDBPointer) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) timestampDecodeType(_ DecodeContext, vr bsonrw.ValueReader, reflectType reflect.Type) (reflect.Value, error) { - if reflectType != tTimestamp { - return emptyValue, ValueDecoderError{ - Name: "TimestampDecodeValue", - Types: []reflect.Type{tTimestamp}, - Received: reflect.Zero(reflectType), - } - } - - 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() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a Timestamp", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.Timestamp{T: t, I: incr}), nil -} - -// TimestampDecodeValue is the ValueDecoderFunc for Timestamp. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.timestampDecodeType(dc, vr, tTimestamp) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) minKeyDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tMinKey { - return emptyValue, ValueDecoderError{ - Name: "MinKeyDecodeValue", - Types: []reflect.Type{tMinKey}, - Received: reflect.Zero(t), - } - } - - var err error - switch vrType := vr.Type(); vrType { - case bsontype.MinKey: - err = vr.ReadMinKey() - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a MinKey", vr.Type()) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.MinKey{}), nil -} - -// MinKeyDecodeValue is the ValueDecoderFunc for MinKey. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.minKeyDecodeType(dc, vr, tMinKey) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (DefaultValueDecoders) maxKeyDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tMaxKey { - return emptyValue, ValueDecoderError{ - Name: "MaxKeyDecodeValue", - Types: []reflect.Type{tMaxKey}, - Received: reflect.Zero(t), - } - } - - var err error - switch vrType := vr.Type(); vrType { - case bsontype.MaxKey: - err = vr.ReadMaxKey() - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a MaxKey", vr.Type()) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(primitive.MaxKey{}), nil -} - -// MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd 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} - } - - elem, err := dvd.maxKeyDecodeType(dc, vr, tMaxKey) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (dvd DefaultValueDecoders) decimal128DecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tDecimal { - return emptyValue, ValueDecoderError{ - Name: "Decimal128DecodeValue", - Types: []reflect.Type{tDecimal}, - Received: reflect.Zero(t), - } - } - - 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() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.Decimal128", vr.Type()) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(d128), nil -} - -// Decimal128DecodeValue is the ValueDecoderFunc for primitive.Decimal128. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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} - } - - elem, err := dvd.decimal128DecodeType(dctx, vr, tDecimal) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (dvd DefaultValueDecoders) jsonNumberDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tJSONNumber { - return emptyValue, ValueDecoderError{ - Name: "JSONNumberDecodeValue", - Types: []reflect.Type{tJSONNumber}, - Received: reflect.Zero(t), - } - } - - var jsonNum json.Number - var err error - switch vrType := vr.Type(); vrType { - case bsontype.Double: - f64, err := vr.ReadDouble() - if err != nil { - return emptyValue, err - } - jsonNum = json.Number(strconv.FormatFloat(f64, 'f', -1, 64)) - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return emptyValue, err - } - jsonNum = json.Number(strconv.FormatInt(int64(i32), 10)) - case bsontype.Int64: - i64, err := vr.ReadInt64() - if err != nil { - return emptyValue, err - } - jsonNum = json.Number(strconv.FormatInt(i64, 10)) - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a json.Number", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(jsonNum), nil -} - -// JSONNumberDecodeValue is the ValueDecoderFunc for json.Number. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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} - } - - elem, err := dvd.jsonNumberDecodeType(dc, vr, tJSONNumber) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -func (dvd DefaultValueDecoders) urlDecodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tURL { - return emptyValue, ValueDecoderError{ - Name: "URLDecodeValue", - Types: []reflect.Type{tURL}, - Received: reflect.Zero(t), - } - } - - urlPtr := &url.URL{} - var err error - switch vrType := vr.Type(); vrType { - case bsontype.String: - var str string // Declare str here to avoid shadowing err during the ReadString call. - str, err = vr.ReadString() - if err != nil { - return emptyValue, err - } - - urlPtr, err = url.Parse(str) - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a *url.URL", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(urlPtr).Elem(), nil -} - -// URLDecodeValue is the ValueDecoderFunc for url.URL. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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} - } - - elem, err := dvd.urlDecodeType(dc, vr, tURL) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -// TimeDecodeValue is the ValueDecoderFunc for time.Time. -// -// Deprecated: TimeDecodeValue is not registered by default. Use TimeCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) TimeDecodeValue(_ 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. -// -// Deprecated: ByteSliceDecodeValue is not registered by default. Use ByteSliceCodec.DecodeValue instead. -func (dvd DefaultValueDecoders) ByteSliceDecodeValue(_ 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. -// -// Deprecated: MapDecodeValue is not registered by default. Use MapCodec.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 errors.Is(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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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() - case bsontype.Undefined: - val.Set(reflect.Zero(val.Type())) - return vr.ReadUndefined() - 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. -// -// Deprecated: SliceDecodeValue is not registered by default. 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ 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 BSON value is null and the go value is a pointer, then don't call - // UnmarshalBSONValue. Even if the Go pointer is already initialized (i.e., - // non-nil), encountering null in BSON will result in the pointer being - // directly set to nil here. Since the pointer is being replaced with nil, - // there is no opportunity (or reason) for the custom UnmarshalBSONValue logic - // to be called. - if vr.Type() == bsontype.Null && val.Kind() == reflect.Ptr { - val.Set(reflect.Zero(val.Type())) - - return vr.ReadNull() - } - - 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 the type doesn't implement the interface, a pointer to it must. - } - - t, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) - if err != nil { - return err - } - - m, ok := val.Interface().(ValueUnmarshaler) - if !ok { - // NB: this error should be unreachable due to the above checks - return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} - } - return m.UnmarshalBSONValue(t, src) -} - -// UnmarshalerDecodeValue is the ValueDecoderFunc for Unmarshaler implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ 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())) - } - - _, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) - if err != nil { - return err - } - - // If the target Go value is a pointer and the BSON field value is empty, set the value to the - // zero value of the pointer (nil) and don't call UnmarshalBSON. UnmarshalBSON has no way to - // change the pointer value from within the function (only the value at the pointer address), - // so it can't set the pointer to "nil" itself. Since the most common Go value for an empty BSON - // field value is "nil", we set "nil" here and don't call UnmarshalBSON. This behavior matches - // the behavior of the Go "encoding/json" unmarshaler when the target Go value is a pointer and - // the JSON field value is "null". - if val.Kind() == reflect.Ptr && len(src) == 0 { - val.Set(reflect.Zero(val.Type())) - return nil - } - - if !val.Type().Implements(tUnmarshaler) { - if !val.CanAddr() { - return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val} - } - val = val.Addr() // If the type doesn't implement the interface, a pointer to it must. - } - - m, ok := val.Interface().(Unmarshaler) - if !ok { - // NB: this error should be unreachable due to the above checks - return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val} - } - return m.UnmarshalBSON(src) -} - -// EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}. -// -// Deprecated: EmptyInterfaceDecodeValue is not registered by default. 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -func (DefaultValueDecoders) CoreDocumentDecodeValue(_ 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 - } - eTypeDecoder, _ := decoder.(typeDecoder) - - idx := 0 - for { - vr, err := ar.ReadValue() - if errors.Is(err, bsonrw.ErrEOA) { - break - } - if err != nil { - return nil, err - } - - elem, err := decodeTypeOrValueWithInfo(decoder, eTypeDecoder, dc, vr, eType, true) - if err != nil { - return nil, newDecodeError(strconv.Itoa(idx), err) - } - elems = append(elems, elem) - idx++ - } - - return elems, nil -} - -func (dvd DefaultValueDecoders) readCodeWithScope(dc DecodeContext, vr bsonrw.ValueReader) (primitive.CodeWithScope, error) { - var cws primitive.CodeWithScope - - code, dr, err := vr.ReadCodeWithScope() - if err != nil { - return cws, err - } - - scope := reflect.New(tD).Elem() - elems, err := dvd.decodeElemsFromDocumentReader(dc, dr) - if err != nil { - return cws, err - } - - scope.Set(reflect.MakeSlice(tD, 0, len(elems))) - scope.Set(reflect.Append(scope, elems...)) - - cws = primitive.CodeWithScope{ - Code: primitive.JavaScript(code), - Scope: scope.Interface().(primitive.D), - } - return cws, nil -} - -func (dvd DefaultValueDecoders) codeWithScopeDecodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tCodeWithScope { - return emptyValue, ValueDecoderError{ - Name: "CodeWithScopeDecodeValue", - Types: []reflect.Type{tCodeWithScope}, - Received: reflect.Zero(t), - } - } - - var cws primitive.CodeWithScope - var err error - switch vrType := vr.Type(); vrType { - case bsontype.CodeWithScope: - cws, err = dvd.readCodeWithScope(dc, vr) - case bsontype.Null: - err = vr.ReadNull() - case bsontype.Undefined: - err = vr.ReadUndefined() - default: - return emptyValue, fmt.Errorf("cannot decode %v into a primitive.CodeWithScope", vrType) - } - if err != nil { - return emptyValue, err - } - - return reflect.ValueOf(cws), nil -} - -// CodeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value decoders registered. -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} - } - - elem, err := dvd.codeWithScopeDecodeType(dc, vr, tCodeWithScope) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -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 errors.Is(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, newDecodeError(key, 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 4751ae99..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go +++ /dev/null @@ -1,856 +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) - 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -type DefaultValueEncoders struct{} - -// RegisterDefaultEncoders will register the encoder methods attached to DefaultValueEncoders with -// the provided RegistryBuilder. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -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(tCoreArray, defaultArrayCodec). - 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, newDefaultStructCodec()). - 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) BooleanEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -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. -// -// Deprecated: UintEncodeValue is not registered by default. 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) FloatEncodeValue(_ 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. -// -// Deprecated: StringEncodeValue is not registered by default. Use StringCodec.EncodeValue instead. -func (dve DefaultValueEncoders) StringEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) ObjectIDEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) Decimal128EncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) URLEncodeValue(_ 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. -// -// Deprecated: TimeEncodeValue is not registered by default. Use TimeCodec.EncodeValue instead. -func (dve DefaultValueEncoders) TimeEncodeValue(_ 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) - dt := primitive.NewDateTimeFromTime(tt) - return vw.WriteDateTime(int64(dt)) -} - -// ByteSliceEncodeValue is the ValueEncoderFunc for []byte. -// -// Deprecated: ByteSliceEncodeValue is not registered by default. Use ByteSliceCodec.EncodeValue instead. -func (dve DefaultValueEncoders) ByteSliceEncodeValue(_ 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. -// -// Deprecated: MapEncodeValue is not registered by default. 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 && !errors.Is(lookupErr, errInvalidValue) { - return lookupErr - } - - vw, err := dw.WriteDocumentElement(key.String()) - if err != nil { - return err - } - - if errors.Is(lookupErr, errInvalidValue) { - err = vw.WriteNull() - if err != nil { - return err - } - continue - } - - err = currEncoder.EncodeValue(ec, vw, currVal) - if err != nil { - return err - } - } - - return dw.WriteDocumentEnd() -} - -// ArrayEncodeValue is the ValueEncoderFunc for array types. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -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 && !errors.Is(lookupErr, errInvalidValue) { - return lookupErr - } - - vw, err := aw.WriteArrayElement() - if err != nil { - return err - } - - if errors.Is(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. -// -// Deprecated: SliceEncodeValue is not registered by default. 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 && !errors.Is(lookupErr, errInvalidValue) { - return lookupErr - } - - vw, err := aw.WriteArrayElement() - if err != nil { - return err - } - - if errors.Is(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{}. -// -// Deprecated: EmptyInterfaceEncodeValue is not registered by default. 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(_ 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} - } - - m, ok := val.Interface().(ValueMarshaler) - if !ok { - return vw.WriteNull() - } - t, data, err := m.MarshalBSONValue() - if err != nil { - return err - } - return bsonrw.Copier{}.CopyValueFromBytes(vw, t, data) -} - -// MarshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (dve DefaultValueEncoders) MarshalerEncodeValue(_ 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} - } - - m, ok := val.Interface().(Marshaler) - if !ok { - return vw.WriteNull() - } - data, err := m.MarshalBSON() - if err != nil { - return err - } - return bsonrw.Copier{}.CopyValueFromBytes(vw, bsontype.EmbeddedDocument, data) -} - -// ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -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} - } - - m, ok := val.Interface().(Proxy) - if !ok { - return vw.WriteNull() - } - v, err := m.ProxyBSON() - if err != nil { - return err - } - if v == nil { - encoder, err := ec.LookupEncoder(nil) - if err != nil { - return err - } - return encoder.EncodeValue(ec, vw, reflect.ValueOf(nil)) - } - vv := reflect.ValueOf(v) - switch vv.Kind() { - case reflect.Ptr, reflect.Interface: - vv = vv.Elem() - } - encoder, err := ec.LookupEncoder(vv.Type()) - if err != nil { - return err - } - return encoder.EncodeValue(ec, vw, vv) -} - -// JavaScriptEncodeValue is the ValueEncoderFunc for the primitive.JavaScript type. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) JavaScriptEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) SymbolEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) BinaryEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) UndefinedEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) DateTimeEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) NullEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) RegexEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) DBPointerEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) TimestampEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) MinKeyEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) MaxKeyEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -func (DefaultValueEncoders) CoreDocumentEncodeValue(_ 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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.NewRegistry] to get a registry with all default -// value encoders registered. -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 4613e5a1..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2022-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 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 -// -// A Registry is a 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 -// have 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)) -// registry.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.NewRegistry 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 098368f0..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/empty_interface_codec.go +++ /dev/null @@ -1,173 +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" -) - -// EmptyInterfaceCodec is the Codec used for interface{} values. -// -// Deprecated: EmptyInterfaceCodec will not be directly configurable in Go -// Driver 2.0. To configure the empty interface encode and decode behavior, use -// the configuration methods on a [go.mongodb.org/mongo-driver/bson.Encoder] or -// [go.mongodb.org/mongo-driver/bson.Decoder]. To configure the empty interface -// encode and decode behavior for a mongo.Client, use -// [go.mongodb.org/mongo-driver/mongo/options.ClientOptions.SetBSONOptions]. -// -// For example, to configure a mongo.Client to unmarshal BSON binary field -// values as a Go byte slice, use: -// -// opt := options.Client().SetBSONOptions(&options.BSONOptions{ -// BinaryAsSlice: true, -// }) -// -// See the deprecation notice for each field in EmptyInterfaceCodec for the -// corresponding settings. -type EmptyInterfaceCodec struct { - // DecodeBinaryAsSlice causes DecodeValue to unmarshal BSON binary field values that are the - // "Generic" or "Old" BSON binary subtype as a Go byte slice instead of a primitive.Binary. - // - // Deprecated: Use bson.Decoder.BinaryAsSlice or options.BSONOptions.BinaryAsSlice instead. - DecodeBinaryAsSlice bool -} - -var ( - defaultEmptyInterfaceCodec = NewEmptyInterfaceCodec() - - // Assert that defaultEmptyInterfaceCodec satisfies the typeDecoder interface, which allows it - // to be used by collection type decoders (e.g. map, slice, etc) to set individual values in a - // collection. - _ typeDecoder = defaultEmptyInterfaceCodec -) - -// NewEmptyInterfaceCodec returns a EmptyInterfaceCodec with options opts. -// -// Deprecated: NewEmptyInterfaceCodec will not be available in Go Driver 2.0. See -// [EmptyInterfaceCodec] for more details. -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 { - if dc.defaultDocumentType != nil { - // If the bsontype is an embedded document and the DocumentType is set on the DecodeContext, then return - // that type. - return dc.defaultDocumentType, nil - } - if 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 -} - -func (eic EmptyInterfaceCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tEmpty { - return emptyValue, ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: reflect.Zero(t)} - } - - rtype, err := eic.getEmptyInterfaceDecodeType(dc, vr.Type()) - if err != nil { - switch vr.Type() { - case bsontype.Null: - return reflect.Zero(t), vr.ReadNull() - default: - return emptyValue, err - } - } - - decoder, err := dc.LookupDecoder(rtype) - if err != nil { - return emptyValue, err - } - - elem, err := decodeTypeOrValue(decoder, dc, vr, rtype) - if err != nil { - return emptyValue, err - } - - if (eic.DecodeBinaryAsSlice || dc.binaryAsSlice) && rtype == tBinary { - binElem := elem.Interface().(primitive.Binary) - if binElem.Subtype == bsontype.BinaryGeneric || binElem.Subtype == bsontype.BinaryBinaryOld { - elem = reflect.ValueOf(binElem.Data) - } - } - - return elem, nil -} - -// 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} - } - - elem, err := eic.decodeType(dc, vr, val.Type()) - if err != nil { - return err - } - - 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 d7e00ffa..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/map_codec.go +++ /dev/null @@ -1,343 +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" - "errors" - "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. -// -// Deprecated: MapCodec will not be directly configurable in Go Driver 2.0. To -// configure the map encode and decode behavior, use the configuration methods -// on a [go.mongodb.org/mongo-driver/bson.Encoder] or -// [go.mongodb.org/mongo-driver/bson.Decoder]. To configure the map encode and -// decode behavior for a mongo.Client, use -// [go.mongodb.org/mongo-driver/mongo/options.ClientOptions.SetBSONOptions]. -// -// For example, to configure a mongo.Client to marshal nil Go maps as empty BSON -// documents, use: -// -// opt := options.Client().SetBSONOptions(&options.BSONOptions{ -// NilMapAsEmpty: true, -// }) -// -// See the deprecation notice for each field in MapCodec for the corresponding -// settings. -type MapCodec struct { - // DecodeZerosMap causes DecodeValue to delete any existing values from Go maps in the destination - // value passed to Decode before unmarshaling BSON documents into them. - // - // Deprecated: Use bson.Decoder.ZeroMaps or options.BSONOptions.ZeroMaps instead. - DecodeZerosMap bool - - // EncodeNilAsEmpty causes EncodeValue to marshal nil Go maps as empty BSON documents instead of - // BSON null. - // - // Deprecated: Use bson.Encoder.NilMapAsEmpty or options.BSONOptions.NilMapAsEmpty instead. - EncodeNilAsEmpty bool - - // EncodeKeysWithStringer causes the Encoder to convert Go map keys to BSON document field name - // strings using fmt.Sprintf() instead of the default string conversion logic. - // - // Deprecated: Use bson.Encoder.StringifyMapKeysWithFmt or - // options.BSONOptions.StringifyMapKeysWithFmt instead. - EncodeKeysWithStringer bool -} - -// KeyMarshaler is the interface implemented by an object that can marshal itself into a string key. -// This applies to types used as map keys and is similar to encoding.TextMarshaler. -type KeyMarshaler interface { - MarshalKey() (key string, err error) -} - -// KeyUnmarshaler is the interface implemented by an object that can unmarshal a string representation -// of itself. This applies to types used as map keys and is similar to encoding.TextUnmarshaler. -// -// UnmarshalKey must be able to decode the form generated by MarshalKey. -// UnmarshalKey must copy the text if it wishes to retain the text -// after returning. -type KeyUnmarshaler interface { - UnmarshalKey(key string) error -} - -// NewMapCodec returns a MapCodec with options opts. -// -// Deprecated: NewMapCodec will not be available in Go Driver 2.0. See -// [MapCodec] for more details. -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 - } - if mapOpt.EncodeKeysWithStringer != nil { - codec.EncodeKeysWithStringer = *mapOpt.EncodeKeysWithStringer - } - 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 && !ec.nilMapAsEmpty { - // 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, err := mc.encodeKey(key, ec.stringifyMapKeysWithFmt) - if err != nil { - return err - } - - 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 && !errors.Is(lookupErr, errInvalidValue) { - return lookupErr - } - - vw, err := dw.WriteDocumentElement(keyStr) - if err != nil { - return err - } - - if errors.Is(lookupErr, errInvalidValue) { - err = vw.WriteNull() - if err != nil { - return err - } - continue - } - - err = currEncoder.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() - case bsontype.Undefined: - val.Set(reflect.Zero(val.Type())) - return vr.ReadUndefined() - 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 || dc.zeroMaps) { - clearMap(val) - } - - eType := val.Type().Elem() - decoder, err := dc.LookupDecoder(eType) - if err != nil { - return err - } - eTypeDecoder, _ := decoder.(typeDecoder) - - if eType == tEmpty { - dc.Ancestor = val.Type() - } - - keyType := val.Type().Key() - - for { - key, vr, err := dr.ReadElement() - if errors.Is(err, bsonrw.ErrEOD) { - break - } - if err != nil { - return err - } - - k, err := mc.decodeKey(key, keyType) - if err != nil { - return err - } - - elem, err := decodeTypeOrValueWithInfo(decoder, eTypeDecoder, dc, vr, eType, true) - if err != nil { - return newDecodeError(key, 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) - } -} - -func (mc *MapCodec) encodeKey(val reflect.Value, encodeKeysWithStringer bool) (string, error) { - if mc.EncodeKeysWithStringer || encodeKeysWithStringer { - return fmt.Sprint(val), nil - } - - // keys of any string type are used directly - if val.Kind() == reflect.String { - return val.String(), nil - } - // KeyMarshalers are marshaled - if km, ok := val.Interface().(KeyMarshaler); ok { - if val.Kind() == reflect.Ptr && val.IsNil() { - return "", nil - } - buf, err := km.MarshalKey() - if err == nil { - return buf, nil - } - return "", err - } - // keys implement encoding.TextMarshaler are marshaled. - if km, ok := val.Interface().(encoding.TextMarshaler); ok { - if val.Kind() == reflect.Ptr && val.IsNil() { - return "", nil - } - - buf, err := km.MarshalText() - if err != nil { - return "", err - } - - return string(buf), nil - } - - switch val.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return strconv.FormatInt(val.Int(), 10), nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return strconv.FormatUint(val.Uint(), 10), nil - } - return "", fmt.Errorf("unsupported key type: %v", val.Type()) -} - -var keyUnmarshalerType = reflect.TypeOf((*KeyUnmarshaler)(nil)).Elem() -var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() - -func (mc *MapCodec) decodeKey(key string, keyType reflect.Type) (reflect.Value, error) { - keyVal := reflect.ValueOf(key) - var err error - switch { - // First, if EncodeKeysWithStringer is not enabled, try to decode withKeyUnmarshaler - case !mc.EncodeKeysWithStringer && reflect.PtrTo(keyType).Implements(keyUnmarshalerType): - keyVal = reflect.New(keyType) - v := keyVal.Interface().(KeyUnmarshaler) - err = v.UnmarshalKey(key) - keyVal = keyVal.Elem() - // Try to decode encoding.TextUnmarshalers. - case reflect.PtrTo(keyType).Implements(textUnmarshalerType): - keyVal = reflect.New(keyType) - v := keyVal.Interface().(encoding.TextUnmarshaler) - err = v.UnmarshalText([]byte(key)) - keyVal = keyVal.Elem() - // Otherwise, go to type specific behavior - default: - switch keyType.Kind() { - case reflect.String: - keyVal = reflect.ValueOf(key).Convert(keyType) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - n, parseErr := strconv.ParseInt(key, 10, 64) - if parseErr != nil || reflect.Zero(keyType).OverflowInt(n) { - err = fmt.Errorf("failed to unmarshal number key %v", key) - } - keyVal = reflect.ValueOf(n).Convert(keyType) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - n, parseErr := strconv.ParseUint(key, 10, 64) - if parseErr != nil || reflect.Zero(keyType).OverflowUint(n) { - err = fmt.Errorf("failed to unmarshal number key %v", key) - break - } - keyVal = reflect.ValueOf(n).Convert(keyType) - case reflect.Float32, reflect.Float64: - if mc.EncodeKeysWithStringer { - parsed, err := strconv.ParseFloat(key, 64) - if err != nil { - return keyVal, fmt.Errorf("Map key is defined to be a decimal type (%v) but got error %w", keyType.Kind(), err) - } - keyVal = reflect.ValueOf(parsed) - break - } - fallthrough - default: - return keyVal, fmt.Errorf("unsupported key type: %v", keyType) - } - } - return keyVal, err -} 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 ddfa4a33..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go +++ /dev/null @@ -1,108 +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" - "go.mongodb.org/mongo-driver/bson/bsontype" -) - -var _ ValueEncoder = &PointerCodec{} -var _ ValueDecoder = &PointerCodec{} - -// PointerCodec is the Codec used for pointers. -// -// Deprecated: PointerCodec will not be directly accessible in Go Driver 2.0. To -// override the default pointer encode and decode behavior, create a new registry -// with [go.mongodb.org/mongo-driver/bson.NewRegistry] and register a new -// encoder and decoder for pointers. -// -// For example, -// -// reg := bson.NewRegistry() -// reg.RegisterKindEncoder(reflect.Ptr, myPointerEncoder) -// reg.RegisterKindDecoder(reflect.Ptr, myPointerDecoder) -type PointerCodec struct { - ecache typeEncoderCache - dcache typeDecoderCache -} - -// NewPointerCodec returns a PointerCodec that has been initialized. -// -// Deprecated: NewPointerCodec will not be available in Go Driver 2.0. See -// [PointerCodec] for more details. -func NewPointerCodec() *PointerCodec { - return &PointerCodec{} -} - -// 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() - } - - typ := val.Type() - if v, ok := pc.ecache.Load(typ); ok { - if v == nil { - return ErrNoEncoder{Type: typ} - } - return v.EncodeValue(ec, vw, val.Elem()) - } - // TODO(charlie): handle concurrent requests for the same type - enc, err := ec.LookupEncoder(typ.Elem()) - enc = pc.ecache.LoadOrStore(typ, enc) - 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} - } - - typ := val.Type() - if vr.Type() == bsontype.Null { - val.Set(reflect.Zero(typ)) - return vr.ReadNull() - } - if vr.Type() == bsontype.Undefined { - val.Set(reflect.Zero(typ)) - return vr.ReadUndefined() - } - - if val.IsNil() { - val.Set(reflect.New(typ.Elem())) - } - - if v, ok := pc.dcache.Load(typ); ok { - if v == nil { - return ErrNoDecoder{Type: typ} - } - return v.DecodeValue(dc, vr, val.Elem()) - } - // TODO(charlie): handle concurrent requests for the same type - dec, err := dc.LookupDecoder(typ.Elem()) - dec = pc.dcache.LoadOrStore(typ, dec) - 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 196c491b..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go +++ /dev/null @@ -1,524 +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. -// -// Deprecated: ErrNilType will not be supported in Go Driver 2.0. -var ErrNilType = errors.New("cannot perform a decoder lookup on ") - -// ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder. -// -// Deprecated: ErrNotPointer will not be supported in Go Driver 2.0. -var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder") - -// ErrNoEncoder is returned when there wasn't an encoder available for a type. -// -// Deprecated: ErrNoEncoder will not be supported in Go Driver 2.0. -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. -// -// Deprecated: ErrNoDecoder will not be supported in Go Driver 2.0. -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. -// -// Deprecated: ErrNoTypeMapEntry will not be supported in Go Driver 2.0. -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. -// -// Deprecated: ErrNotInterface will not be supported in Go Driver 2.0. -var ErrNotInterface = errors.New("The provided type is not an interface") - -// A RegistryBuilder is used to build a Registry. This type is not goroutine -// safe. -// -// Deprecated: Use Registry instead. -type RegistryBuilder struct { - registry *Registry -} - -// NewRegistryBuilder creates a new empty RegistryBuilder. -// -// Deprecated: Use NewRegistry instead. -func NewRegistryBuilder() *RegistryBuilder { - return &RegistryBuilder{ - registry: NewRegistry(), - } -} - -// RegisterCodec will register the provided ValueCodec for the provided type. -// -// Deprecated: Use Registry.RegisterTypeEncoder and Registry.RegisterTypeDecoder instead. -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 marshaling a type that is that interface. It -// will not be called when marshaling a non-interface type that implements the interface. -// -// Deprecated: Use Registry.RegisterTypeEncoder instead. -func (rb *RegistryBuilder) RegisterTypeEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterTypeEncoder(t, enc) - return rb -} - -// RegisterHookEncoder will register an encoder for the provided interface type t. This encoder will be called when -// marshaling 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. -// -// Deprecated: Use Registry.RegisterInterfaceEncoder instead. -func (rb *RegistryBuilder) RegisterHookEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterInterfaceEncoder(t, 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 unmarshaling into a type that is that interface. -// It will not be called when unmarshaling into a non-interface type that implements the interface. -// -// Deprecated: Use Registry.RegisterTypeDecoder instead. -func (rb *RegistryBuilder) RegisterTypeDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterTypeDecoder(t, dec) - return rb -} - -// RegisterHookDecoder will register an decoder for the provided interface type t. This decoder will be called when -// unmarshaling 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. -// -// Deprecated: Use Registry.RegisterInterfaceDecoder instead. -func (rb *RegistryBuilder) RegisterHookDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterInterfaceDecoder(t, dec) - return rb -} - -// RegisterEncoder registers the provided type and encoder pair. -// -// Deprecated: Use Registry.RegisterTypeEncoder or Registry.RegisterInterfaceEncoder instead. -func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { - if t == tEmpty { - rb.registry.RegisterTypeEncoder(t, enc) - return rb - } - switch t.Kind() { - case reflect.Interface: - rb.registry.RegisterInterfaceEncoder(t, enc) - default: - rb.registry.RegisterTypeEncoder(t, enc) - } - return rb -} - -// RegisterDecoder registers the provided type and decoder pair. -// -// Deprecated: Use Registry.RegisterTypeDecoder or Registry.RegisterInterfaceDecoder instead. -func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { - if t == nil { - rb.registry.RegisterTypeDecoder(t, dec) - return rb - } - if t == tEmpty { - rb.registry.RegisterTypeDecoder(t, dec) - return rb - } - switch t.Kind() { - case reflect.Interface: - rb.registry.RegisterInterfaceDecoder(t, dec) - default: - rb.registry.RegisterTypeDecoder(t, dec) - } - return rb -} - -// RegisterDefaultEncoder will register the provided ValueEncoder to the provided -// kind. -// -// Deprecated: Use Registry.RegisterKindEncoder instead. -func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder { - rb.registry.RegisterKindEncoder(kind, enc) - return rb -} - -// RegisterDefaultDecoder will register the provided ValueDecoder to the -// provided kind. -// -// Deprecated: Use Registry.RegisterKindDecoder instead. -func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder { - rb.registry.RegisterKindDecoder(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{})) -// -// Deprecated: Use Registry.RegisterTypeMapEntry instead. -func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder { - rb.registry.RegisterTypeMapEntry(bt, rt) - return rb -} - -// Build creates a Registry from the current state of this RegistryBuilder. -// -// Deprecated: Use NewRegistry instead. -func (rb *RegistryBuilder) Build() *Registry { - r := &Registry{ - interfaceEncoders: append([]interfaceValueEncoder(nil), rb.registry.interfaceEncoders...), - interfaceDecoders: append([]interfaceValueDecoder(nil), rb.registry.interfaceDecoders...), - typeEncoders: rb.registry.typeEncoders.Clone(), - typeDecoders: rb.registry.typeDecoders.Clone(), - kindEncoders: rb.registry.kindEncoders.Clone(), - kindDecoders: rb.registry.kindDecoders.Clone(), - } - rb.registry.typeMap.Range(func(k, v interface{}) bool { - if k != nil && v != nil { - r.typeMap.Store(k, v) - } - return true - }) - return r -} - -// 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 { - interfaceEncoders []interfaceValueEncoder - interfaceDecoders []interfaceValueDecoder - typeEncoders *typeEncoderCache - typeDecoders *typeDecoderCache - kindEncoders *kindEncoderCache - kindDecoders *kindDecoderCache - typeMap sync.Map // map[bsontype.Type]reflect.Type -} - -// NewRegistry creates a new empty Registry. -func NewRegistry() *Registry { - return &Registry{ - typeEncoders: new(typeEncoderCache), - typeDecoders: new(typeDecoderCache), - kindEncoders: new(kindEncoderCache), - kindDecoders: new(kindDecoderCache), - } -} - -// RegisterTypeEncoder registers the provided ValueEncoder for the provided type. -// -// The type will be used as provided, 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 marshaling a type that is -// that interface. It will not be called when marshaling a non-interface type that implements the -// interface. To get the latter behavior, call RegisterHookEncoder instead. -// -// RegisterTypeEncoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterTypeEncoder(valueType reflect.Type, enc ValueEncoder) { - r.typeEncoders.Store(valueType, enc) -} - -// RegisterTypeDecoder registers the provided ValueDecoder for the provided type. -// -// The type will be used as provided, 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 unmarshaling into a type that -// is that interface. It will not be called when unmarshaling into a non-interface type that -// implements the interface. To get the latter behavior, call RegisterHookDecoder instead. -// -// RegisterTypeDecoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterTypeDecoder(valueType reflect.Type, dec ValueDecoder) { - r.typeDecoders.Store(valueType, dec) -} - -// RegisterKindEncoder registers the provided ValueEncoder for the provided kind. -// -// Use RegisterKindEncoder to register an encoder for any type with the same underlying kind. For -// example, consider the type MyInt defined as -// -// type MyInt int32 -// -// To define an encoder for MyInt and int32, use RegisterKindEncoder like -// -// reg.RegisterKindEncoder(reflect.Int32, myEncoder) -// -// RegisterKindEncoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterKindEncoder(kind reflect.Kind, enc ValueEncoder) { - r.kindEncoders.Store(kind, enc) -} - -// RegisterKindDecoder registers the provided ValueDecoder for the provided kind. -// -// Use RegisterKindDecoder to register a decoder for any type with the same underlying kind. For -// example, consider the type MyInt defined as -// -// type MyInt int32 -// -// To define an decoder for MyInt and int32, use RegisterKindDecoder like -// -// reg.RegisterKindDecoder(reflect.Int32, myDecoder) -// -// RegisterKindDecoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterKindDecoder(kind reflect.Kind, dec ValueDecoder) { - r.kindDecoders.Store(kind, dec) -} - -// RegisterInterfaceEncoder registers an encoder for the provided interface type iface. This encoder will -// be called when marshaling a type if the type implements iface or a pointer to the type -// implements iface. If the provided type is not an interface -// (i.e. iface.Kind() != reflect.Interface), this method will panic. -// -// RegisterInterfaceEncoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterInterfaceEncoder(iface reflect.Type, enc ValueEncoder) { - if iface.Kind() != reflect.Interface { - panicStr := fmt.Errorf("RegisterInterfaceEncoder expects a type with kind reflect.Interface, "+ - "got type %s with kind %s", iface, iface.Kind()) - panic(panicStr) - } - - for idx, encoder := range r.interfaceEncoders { - if encoder.i == iface { - r.interfaceEncoders[idx].ve = enc - return - } - } - - r.interfaceEncoders = append(r.interfaceEncoders, interfaceValueEncoder{i: iface, ve: enc}) -} - -// RegisterInterfaceDecoder registers an decoder for the provided interface type iface. This decoder will -// be called when unmarshaling into a type if the type implements iface or a pointer to the type -// implements iface. If the provided type is not an interface (i.e. iface.Kind() != reflect.Interface), -// this method will panic. -// -// RegisterInterfaceDecoder should not be called concurrently with any other Registry method. -func (r *Registry) RegisterInterfaceDecoder(iface reflect.Type, dec ValueDecoder) { - if iface.Kind() != reflect.Interface { - panicStr := fmt.Errorf("RegisterInterfaceDecoder expects a type with kind reflect.Interface, "+ - "got type %s with kind %s", iface, iface.Kind()) - panic(panicStr) - } - - for idx, decoder := range r.interfaceDecoders { - if decoder.i == iface { - r.interfaceDecoders[idx].vd = dec - return - } - } - - r.interfaceDecoders = append(r.interfaceDecoders, interfaceValueDecoder{i: iface, vd: dec}) -} - -// 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: -// -// reg.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.Raw{})) -func (r *Registry) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) { - r.typeMap.Store(bt, rt) -} - -// LookupEncoder returns the first matching encoder in the Registry. It uses the following lookup -// order: -// -// 1. An encoder registered for the exact type. If the given type is an interface, an encoder -// registered using RegisterTypeEncoder for that interface will be selected. -// -// 2. An encoder registered using RegisterInterfaceEncoder for an interface implemented by the type -// or by a pointer to the type. -// -// 3. An encoder registered using RegisterKindEncoder for the kind of value. -// -// If no encoder is found, an error of type ErrNoEncoder is returned. LookupEncoder is safe for -// concurrent use by multiple goroutines after all codecs and encoders are registered. -func (r *Registry) LookupEncoder(valueType reflect.Type) (ValueEncoder, error) { - if valueType == nil { - return nil, ErrNoEncoder{Type: valueType} - } - enc, found := r.lookupTypeEncoder(valueType) - if found { - if enc == nil { - return nil, ErrNoEncoder{Type: valueType} - } - return enc, nil - } - - enc, found = r.lookupInterfaceEncoder(valueType, true) - if found { - return r.typeEncoders.LoadOrStore(valueType, enc), nil - } - - if v, ok := r.kindEncoders.Load(valueType.Kind()); ok { - return r.storeTypeEncoder(valueType, v), nil - } - return nil, ErrNoEncoder{Type: valueType} -} - -func (r *Registry) storeTypeEncoder(rt reflect.Type, enc ValueEncoder) ValueEncoder { - return r.typeEncoders.LoadOrStore(rt, enc) -} - -func (r *Registry) lookupTypeEncoder(rt reflect.Type) (ValueEncoder, bool) { - return r.typeEncoders.Load(rt) -} - -func (r *Registry) lookupInterfaceEncoder(valueType reflect.Type, allowAddr bool) (ValueEncoder, bool) { - if valueType == nil { - return nil, false - } - for _, ienc := range r.interfaceEncoders { - if valueType.Implements(ienc.i) { - return ienc.ve, true - } - if allowAddr && valueType.Kind() != reflect.Ptr && reflect.PtrTo(valueType).Implements(ienc.i) { - // if *t implements an interface, this will catch if t implements an interface further - // ahead in interfaceEncoders - defaultEnc, found := r.lookupInterfaceEncoder(valueType, false) - if !found { - defaultEnc, _ = r.kindEncoders.Load(valueType.Kind()) - } - return newCondAddrEncoder(ienc.ve, defaultEnc), true - } - } - return nil, false -} - -// LookupDecoder returns the first matching decoder in the Registry. It uses the following lookup -// order: -// -// 1. A decoder registered for the exact type. If the given type is an interface, a decoder -// registered using RegisterTypeDecoder for that interface will be selected. -// -// 2. A decoder registered using RegisterInterfaceDecoder for an interface implemented by the type or by -// a pointer to the type. -// -// 3. A decoder registered using RegisterKindDecoder for the kind of value. -// -// If no decoder is found, an error of type ErrNoDecoder is returned. LookupDecoder is safe for -// concurrent use by multiple goroutines after all codecs and decoders are registered. -func (r *Registry) LookupDecoder(valueType reflect.Type) (ValueDecoder, error) { - if valueType == nil { - return nil, ErrNilType - } - dec, found := r.lookupTypeDecoder(valueType) - if found { - if dec == nil { - return nil, ErrNoDecoder{Type: valueType} - } - return dec, nil - } - - dec, found = r.lookupInterfaceDecoder(valueType, true) - if found { - return r.storeTypeDecoder(valueType, dec), nil - } - - if v, ok := r.kindDecoders.Load(valueType.Kind()); ok { - return r.storeTypeDecoder(valueType, v), nil - } - return nil, ErrNoDecoder{Type: valueType} -} - -func (r *Registry) lookupTypeDecoder(valueType reflect.Type) (ValueDecoder, bool) { - return r.typeDecoders.Load(valueType) -} - -func (r *Registry) storeTypeDecoder(typ reflect.Type, dec ValueDecoder) ValueDecoder { - return r.typeDecoders.LoadOrStore(typ, dec) -} - -func (r *Registry) lookupInterfaceDecoder(valueType reflect.Type, allowAddr bool) (ValueDecoder, bool) { - for _, idec := range r.interfaceDecoders { - if valueType.Implements(idec.i) { - return idec.vd, true - } - if allowAddr && valueType.Kind() != reflect.Ptr && reflect.PtrTo(valueType).Implements(idec.i) { - // if *t implements an interface, this will catch if t implements an interface further - // ahead in interfaceDecoders - defaultDec, found := r.lookupInterfaceDecoder(valueType, false) - if !found { - defaultDec, _ = r.kindDecoders.Load(valueType.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. -// -// LookupTypeMapEntry should not be called concurrently with any other Registry method. -func (r *Registry) LookupTypeMapEntry(bt bsontype.Type) (reflect.Type, error) { - v, ok := r.typeMap.Load(bt) - if v == nil || !ok { - return nil, ErrNoTypeMapEntry{Type: bt} - } - return v.(reflect.Type), 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 14c9fd25..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/slice_codec.go +++ /dev/null @@ -1,214 +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" - - "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. -// -// Deprecated: SliceCodec will not be directly configurable in Go Driver 2.0. To -// configure the slice encode and decode behavior, use the configuration methods -// on a [go.mongodb.org/mongo-driver/bson.Encoder] or -// [go.mongodb.org/mongo-driver/bson.Decoder]. To configure the slice encode and -// decode behavior for a mongo.Client, use -// [go.mongodb.org/mongo-driver/mongo/options.ClientOptions.SetBSONOptions]. -// -// For example, to configure a mongo.Client to marshal nil Go slices as empty -// BSON arrays, use: -// -// opt := options.Client().SetBSONOptions(&options.BSONOptions{ -// NilSliceAsEmpty: true, -// }) -// -// See the deprecation notice for each field in SliceCodec for the corresponding -// settings. -type SliceCodec struct { - // EncodeNilAsEmpty causes EncodeValue to marshal nil Go slices as empty BSON arrays instead of - // BSON null. - // - // Deprecated: Use bson.Encoder.NilSliceAsEmpty instead. - EncodeNilAsEmpty bool -} - -// NewSliceCodec returns a MapCodec with options opts. -// -// Deprecated: NewSliceCodec will not be available in Go Driver 2.0. See -// [SliceCodec] for more details. -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 && !ec.nilSliceAsEmpty { - 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 { - byteSlice := make([]byte, val.Len()) - reflect.Copy(reflect.ValueOf(byteSlice), val) - 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() == tD || 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 && !errors.Is(lookupErr, errInvalidValue) { - return lookupErr - } - - vw, err := aw.WriteArrayElement() - if err != nil { - return err - } - - if errors.Is(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.Undefined: - val.Set(reflect.Zero(val.Type())) - return vr.ReadUndefined() - 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) - val.Set(reflect.AppendSlice(val, reflect.ValueOf(data))) - return nil - case bsontype.String: - if sliceType := val.Type().Elem(); sliceType != tByte { - return fmt.Errorf("SliceDecodeValue can only decode a string into a byte array, got %v", sliceType) - } - 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) - val.Set(reflect.AppendSlice(val, reflect.ValueOf(byteStr))) - 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 a8f885a8..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/string_codec.go +++ /dev/null @@ -1,140 +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" -) - -// StringCodec is the Codec used for string values. -// -// Deprecated: StringCodec will not be directly accessible in Go Driver 2.0. To -// override the default string encode and decode behavior, create a new registry -// with [go.mongodb.org/mongo-driver/bson.NewRegistry] and register a new -// encoder and decoder for strings. -// -// For example, -// -// reg := bson.NewRegistry() -// reg.RegisterKindEncoder(reflect.String, myStringEncoder) -// reg.RegisterKindDecoder(reflect.String, myStringDecoder) -type StringCodec struct { - // DecodeObjectIDAsHex 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. - // - // Deprecated: Decoding object IDs as raw bytes will not be supported in Go Driver 2.0. - DecodeObjectIDAsHex bool -} - -var ( - defaultStringCodec = NewStringCodec() - - // Assert that defaultStringCodec satisfies the typeDecoder interface, which allows it to be - // used by collection type decoders (e.g. map, slice, etc) to set individual values in a - // collection. - _ typeDecoder = defaultStringCodec -) - -// NewStringCodec returns a StringCodec with options opts. -// -// Deprecated: NewStringCodec will not be available in Go Driver 2.0. See -// [StringCodec] for more details. -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(_ 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()) -} - -func (sc *StringCodec) decodeType(_ DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t.Kind() != reflect.String { - return emptyValue, ValueDecoderError{ - Name: "StringDecodeValue", - Kinds: []reflect.Kind{reflect.String}, - Received: reflect.Zero(t), - } - } - - var str string - var err error - switch vr.Type() { - case bsontype.String: - str, err = vr.ReadString() - if err != nil { - return emptyValue, err - } - case bsontype.ObjectID: - oid, err := vr.ReadObjectID() - if err != nil { - return emptyValue, err - } - if sc.DecodeObjectIDAsHex { - str = oid.Hex() - } else { - // TODO(GODRIVER-2796): Return an error here instead of decoding to a garbled string. - byteArray := [12]byte(oid) - str = string(byteArray[:]) - } - case bsontype.Symbol: - str, err = vr.ReadSymbol() - if err != nil { - return emptyValue, err - } - case bsontype.Binary: - data, subtype, err := vr.ReadBinary() - if err != nil { - return emptyValue, err - } - if subtype != bsontype.BinaryGeneric && subtype != bsontype.BinaryBinaryOld { - return emptyValue, decodeBinaryError{subtype: subtype, typeName: "string"} - } - str = string(data) - case bsontype.Null: - if err = vr.ReadNull(); err != nil { - return emptyValue, err - } - case bsontype.Undefined: - if err = vr.ReadUndefined(); err != nil { - return emptyValue, err - } - default: - return emptyValue, fmt.Errorf("cannot decode %v into a string type", vr.Type()) - } - - return reflect.ValueOf(str), nil -} - -// 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} - } - - elem, err := sc.decodeType(dctx, vr, val.Type()) - if err != nil { - return err - } - - val.SetString(elem.String()) - 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 f8d9690c..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go +++ /dev/null @@ -1,736 +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" - "sort" - "strings" - "sync" - "time" - - "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" -) - -// DecodeError represents an error that occurs when unmarshalling BSON bytes into a native Go type. -type DecodeError struct { - keys []string - wrapped error -} - -// Unwrap returns the underlying error -func (de *DecodeError) Unwrap() error { - return de.wrapped -} - -// Error implements the error interface. -func (de *DecodeError) Error() string { - // The keys are stored in reverse order because the de.keys slice is builtup while propagating the error up the - // stack of BSON keys, so we call de.Keys(), which reverses them. - keyPath := strings.Join(de.Keys(), ".") - return fmt.Sprintf("error decoding key %s: %v", keyPath, de.wrapped) -} - -// Keys returns the BSON key path that caused an error as a slice of strings. The keys in the slice are in top-down -// order. For example, if the document being unmarshalled was {a: {b: {c: 1}}} and the value for c was supposed to be -// a string, the keys slice will be ["a", "b", "c"]. -func (de *DecodeError) Keys() []string { - reversedKeys := make([]string, 0, len(de.keys)) - for idx := len(de.keys) - 1; idx >= 0; idx-- { - reversedKeys = append(reversedKeys, de.keys[idx]) - } - - return reversedKeys -} - -// 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. -// -// Deprecated: StructCodec will not be directly configurable in Go Driver 2.0. -// To configure the struct encode and decode behavior, use the configuration -// methods on a [go.mongodb.org/mongo-driver/bson.Encoder] or -// [go.mongodb.org/mongo-driver/bson.Decoder]. To configure the struct encode -// and decode behavior for a mongo.Client, use -// [go.mongodb.org/mongo-driver/mongo/options.ClientOptions.SetBSONOptions]. -// -// For example, to configure a mongo.Client to omit zero-value structs when -// using the "omitempty" struct tag, use: -// -// opt := options.Client().SetBSONOptions(&options.BSONOptions{ -// OmitZeroStruct: true, -// }) -// -// See the deprecation notice for each field in StructCodec for the corresponding -// settings. -type StructCodec struct { - cache sync.Map // map[reflect.Type]*structDescription - parser StructTagParser - - // DecodeZeroStruct causes DecodeValue to delete any existing values from Go structs in the - // destination value passed to Decode before unmarshaling BSON documents into them. - // - // Deprecated: Use bson.Decoder.ZeroStructs or options.BSONOptions.ZeroStructs instead. - DecodeZeroStruct bool - - // DecodeDeepZeroInline causes DecodeValue to delete any existing values from Go structs in the - // destination value passed to Decode before unmarshaling BSON documents into them. - // - // Deprecated: DecodeDeepZeroInline will not be supported in Go Driver 2.0. - DecodeDeepZeroInline bool - - // EncodeOmitDefaultStruct causes the Encoder to consider the zero value for a struct (e.g. - // MyStruct{}) as empty and omit it from the marshaled BSON when the "omitempty" struct tag - // option is set. - // - // Deprecated: Use bson.Encoder.OmitZeroStruct or options.BSONOptions.OmitZeroStruct instead. - EncodeOmitDefaultStruct bool - - // AllowUnexportedFields allows encoding and decoding values from un-exported struct fields. - // - // Deprecated: AllowUnexportedFields does not work on recent versions of Go and will not be - // supported in Go Driver 2.0. - AllowUnexportedFields bool - - // OverwriteDuplicatedInlinedFields, if false, causes EncodeValue to return an error if there is - // a duplicate field in the marshaled BSON when the "inline" struct tag option is set. The - // default value is true. - // - // Deprecated: Use bson.Encoder.ErrorOnInlineDuplicates or - // options.BSONOptions.ErrorOnInlineDuplicates instead. - OverwriteDuplicatedInlinedFields bool -} - -var _ ValueEncoder = &StructCodec{} -var _ ValueDecoder = &StructCodec{} - -// NewStructCodec returns a StructCodec that uses p for struct tag parsing. -// -// Deprecated: NewStructCodec will not be available in Go Driver 2.0. See -// [StructCodec] for more details. -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{ - 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.OverwriteDuplicatedInlinedFields != nil { - codec.OverwriteDuplicatedInlinedFields = *structOpt.OverwriteDuplicatedInlinedFields - } - if structOpt.AllowUnexportedFields != nil { - codec.AllowUnexportedFields = *structOpt.AllowUnexportedFields - } - - return codec, nil -} - -// EncodeValue handles encoding generic struct types. -func (sc *StructCodec) EncodeValue(ec 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(ec.Registry, val.Type(), ec.useJSONStructTags, ec.errorOnInlineDuplicates) - 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(ec, desc.encoder, rv) - - if err != nil && !errors.Is(err, errInvalidValue) { - return err - } - - if errors.Is(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 empty bool - if cz, ok := encoder.(CodecZeroer); ok { - empty = cz.IsTypeZero(rv.Interface()) - } else if rv.Kind() == reflect.Interface { - // isEmpty will not treat an interface rv as an interface, so we need to check for the - // nil interface separately. - empty = rv.IsNil() - } else { - empty = isEmpty(rv, sc.EncodeOmitDefaultStruct || ec.omitZeroStruct) - } - if desc.omitEmpty && empty { - continue - } - - vw2, err := dw.WriteDocumentElement(desc.name) - if err != nil { - return err - } - - ectx := EncodeContext{ - Registry: ec.Registry, - MinSize: desc.minSize || ec.MinSize, - errorOnInlineDuplicates: ec.errorOnInlineDuplicates, - stringifyMapKeysWithFmt: ec.stringifyMapKeysWithFmt, - nilMapAsEmpty: ec.nilMapAsEmpty, - nilSliceAsEmpty: ec.nilSliceAsEmpty, - nilByteSliceAsEmpty: ec.nilByteSliceAsEmpty, - omitZeroStruct: ec.omitZeroStruct, - useJSONStructTags: ec.useJSONStructTags, - } - 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(ec, dw, rv, collisionFn) - } - - return dw.WriteDocumentEnd() -} - -func newDecodeError(key string, original error) error { - var de *DecodeError - if !errors.As(original, &de) { - return &DecodeError{ - keys: []string{key}, - wrapped: original, - } - } - - de.keys = append(de.keys, key) - return de -} - -// 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(dc 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 - case bsontype.Undefined: - if err := vr.ReadUndefined(); 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(dc.Registry, val.Type(), dc.useJSONStructTags, false) - if err != nil { - return err - } - - if sc.DecodeZeroStruct || dc.zeroStructs { - 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 = dc.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 errors.Is(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() - dc.Ancestor = inlineMap.Type() - err = decoder.DecodeValue(dc, 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. - innerErr := fmt.Errorf("field %v is not settable", field) - return newDecodeError(fd.name, innerErr) - } - if field.Kind() == reflect.Ptr && field.IsNil() { - field.Set(reflect.New(field.Type().Elem())) - } - field = field.Addr() - - dctx := DecodeContext{ - Registry: dc.Registry, - Truncate: fd.truncate || dc.Truncate, - defaultDocumentType: dc.defaultDocumentType, - binaryAsSlice: dc.binaryAsSlice, - useJSONStructTags: dc.useJSONStructTags, - useLocalTimeZone: dc.useLocalTimeZone, - zeroMaps: dc.zeroMaps, - zeroStructs: dc.zeroStructs, - } - - if fd.decoder == nil { - return newDecodeError(fd.name, ErrNoDecoder{Type: field.Elem().Type()}) - } - - err = fd.decoder.DecodeValue(dctx, vr, field.Elem()) - if err != nil { - return newDecodeError(fd.name, err) - } - } - - return nil -} - -func isEmpty(v reflect.Value, omitZeroStruct bool) bool { - kind := v.Kind() - if (kind != reflect.Ptr || !v.IsNil()) && v.Type().Implements(tZeroer) { - return v.Interface().(Zeroer).IsZero() - } - switch kind { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Struct: - if !omitZeroStruct { - return false - } - vt := v.Type() - if vt == tTime { - return v.Interface().(time.Time).IsZero() - } - numField := vt.NumField() - for i := 0; i < numField; i++ { - ff := vt.Field(i) - if ff.PkgPath != "" && !ff.Anonymous { - continue // Private field - } - if !isEmpty(v.Field(i), omitZeroStruct) { - return false - } - } - return true - } - return !v.IsValid() || v.IsZero() -} - -type structDescription struct { - fm map[string]fieldDescription - fl []fieldDescription - inlineMap int - inline bool -} - -type fieldDescription struct { - name string // BSON key name - fieldName string // struct field name - idx int - omitEmpty bool - minSize bool - truncate bool - inline []int - encoder ValueEncoder - decoder ValueDecoder -} - -type byIndex []fieldDescription - -func (bi byIndex) Len() int { return len(bi) } - -func (bi byIndex) Swap(i, j int) { bi[i], bi[j] = bi[j], bi[i] } - -func (bi byIndex) Less(i, j int) bool { - // If a field is inlined, its index in the top level struct is stored at inline[0] - iIdx, jIdx := bi[i].idx, bi[j].idx - if len(bi[i].inline) > 0 { - iIdx = bi[i].inline[0] - } - if len(bi[j].inline) > 0 { - jIdx = bi[j].inline[0] - } - if iIdx != jIdx { - return iIdx < jIdx - } - for k, biik := range bi[i].inline { - if k >= len(bi[j].inline) { - return false - } - if biik != bi[j].inline[k] { - return biik < bi[j].inline[k] - } - } - return len(bi[i].inline) < len(bi[j].inline) -} - -func (sc *StructCodec) describeStruct( - r *Registry, - t reflect.Type, - useJSONStructTags bool, - errorOnDuplicates bool, -) (*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. - if v, ok := sc.cache.Load(t); ok { - return v.(*structDescription), nil - } - // TODO(charlie): Only describe the struct once when called - // concurrently with the same type. - ds, err := sc.describeStructSlow(r, t, useJSONStructTags, errorOnDuplicates) - if err != nil { - return nil, err - } - if v, loaded := sc.cache.LoadOrStore(t, ds); loaded { - ds = v.(*structDescription) - } - return ds, nil -} - -func (sc *StructCodec) describeStructSlow( - r *Registry, - t reflect.Type, - useJSONStructTags bool, - errorOnDuplicates bool, -) (*structDescription, error) { - numFields := t.NumField() - sd := &structDescription{ - fm: make(map[string]fieldDescription, numFields), - fl: make([]fieldDescription, 0, numFields), - inlineMap: -1, - } - - var fields []fieldDescription - 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{ - fieldName: sf.Name, - idx: i, - encoder: encoder, - decoder: decoder, - } - - var stags StructTags - // If the caller requested that we use JSON struct tags, use the JSONFallbackStructTagParser - // instead of the parser defined on the codec. - if useJSONStructTags { - stags, err = JSONFallbackStructTagParser.ParseStructTags(sf) - } else { - 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, useJSONStructTags, errorOnDuplicates) - if err != nil { - return nil, err - } - for _, fd := range inlinesf.fl { - if fd.inline == nil { - fd.inline = []int{i, fd.idx} - } else { - fd.inline = append([]int{i}, fd.inline...) - } - fields = append(fields, fd) - - } - default: - return nil, fmt.Errorf("(struct %s) inline fields must be a struct, a struct pointer, or a map", t.String()) - } - continue - } - fields = append(fields, description) - } - - // Sort fieldDescriptions by name and use dominance rules to determine which should be added for each name - sort.Slice(fields, func(i, j int) bool { - x := fields - // sort field by name, breaking ties with depth, then - // breaking ties with index sequence. - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].inline) != len(x[j].inline) { - return len(x[i].inline) < len(x[j].inline) - } - return byIndex(x).Less(i, j) - }) - - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - sd.fl = append(sd.fl, fi) - sd.fm[name] = fi - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if !ok || !sc.OverwriteDuplicatedInlinedFields || errorOnDuplicates { - return nil, fmt.Errorf("struct %s has duplicated key %s", t.String(), name) - } - sd.fl = append(sd.fl, dominant) - sd.fm[name] = dominant - } - - sort.Sort(byIndex(sd.fl)) - - return sd, nil -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's inlining rules. If there are multiple top-level -// fields, the boolean will be false: This condition is an error in Go -// and we skip all the fields. -func dominantField(fields []fieldDescription) (fieldDescription, bool) { - // The fields are sorted in increasing index-length order, then by presence of tag. - // That means that the first field is the dominant one. We need only check - // for error cases: two fields at top level. - if len(fields) > 1 && - len(fields[0].inline) == len(fields[1].inline) { - return fieldDescription{}, false - } - return fields[0], true -} - -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) { - if st.Kind() == reflect.Struct { - numField := st.NumField() - for i := 0; i < numField; i++ { - if result == emptyValue { - result = reflect.Indirect(reflect.New(st)) - } - f := result.Field(i) - if f.CanInterface() { - if f.Type().Kind() == reflect.Struct { - result.Field(i).Set(recursivePointerTo(deepZero(f.Type().Elem()))) - } - } - } - } - return result -} - -// 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 18d85bfb..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go +++ /dev/null @@ -1,148 +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. -// -// Deprecated: Defining custom BSON struct tag parsers will not be supported in Go Driver 2.0. -type StructTagParser interface { - ParseStructTags(reflect.StructField) (StructTags, error) -} - -// StructTagParserFunc is an adapter that allows a generic function to be used -// as a StructTagParser. -// -// Deprecated: Defining custom BSON struct tag parsers will not be supported in Go Driver 2.0. -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. -// -// Deprecated: Defining custom BSON struct tag parsers will not be supported in Go Driver 2.0. -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. -// -// Deprecated: DefaultStructTagParser will be removed in Go Driver 2.0. -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) - } - return parseTags(key, tag) -} - -func parseTags(key string, tag string) (StructTags, error) { - 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 -} - -// JSONFallbackStructTagParser has the same behavior as DefaultStructTagParser -// but will also fallback to parsing the json tag instead on a field where the -// bson tag isn't available. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.UseJSONStructTags] and -// [go.mongodb.org/mongo-driver/bson.Decoder.UseJSONStructTags] instead. -var JSONFallbackStructTagParser StructTagParserFunc = func(sf reflect.StructField) (StructTags, error) { - key := strings.ToLower(sf.Name) - tag, ok := sf.Tag.Lookup("bson") - if !ok { - tag, ok = sf.Tag.Lookup("json") - } - if !ok && !strings.Contains(string(sf.Tag), ":") && len(sf.Tag) > 0 { - tag = string(sf.Tag) - } - - return parseTags(key, tag) -} 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 22fb762c..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/time_codec.go +++ /dev/null @@ -1,151 +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" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -const ( - timeFormatString = "2006-01-02T15:04:05.999Z07:00" -) - -// TimeCodec is the Codec used for time.Time values. -// -// Deprecated: TimeCodec will not be directly configurable in Go Driver 2.0. -// To configure the time.Time encode and decode behavior, use the configuration -// methods on a [go.mongodb.org/mongo-driver/bson.Encoder] or -// [go.mongodb.org/mongo-driver/bson.Decoder]. To configure the time.Time encode -// and decode behavior for a mongo.Client, use -// [go.mongodb.org/mongo-driver/mongo/options.ClientOptions.SetBSONOptions]. -// -// For example, to configure a mongo.Client to ..., use: -// -// opt := options.Client().SetBSONOptions(&options.BSONOptions{ -// UseLocalTimeZone: true, -// }) -// -// See the deprecation notice for each field in TimeCodec for the corresponding -// settings. -type TimeCodec struct { - // UseLocalTimeZone specifies if we should decode into the local time zone. Defaults to false. - // - // Deprecated: Use bson.Decoder.UseLocalTimeZone or options.BSONOptions.UseLocalTimeZone - // instead. - UseLocalTimeZone bool -} - -var ( - defaultTimeCodec = NewTimeCodec() - - // Assert that defaultTimeCodec satisfies the typeDecoder interface, which allows it to be used - // by collection type decoders (e.g. map, slice, etc) to set individual values in a collection. - _ typeDecoder = defaultTimeCodec -) - -// NewTimeCodec returns a TimeCodec with options opts. -// -// Deprecated: NewTimeCodec will not be available in Go Driver 2.0. See -// [TimeCodec] for more details. -func NewTimeCodec(opts ...*bsonoptions.TimeCodecOptions) *TimeCodec { - timeOpt := bsonoptions.MergeTimeCodecOptions(opts...) - - codec := TimeCodec{} - if timeOpt.UseLocalTimeZone != nil { - codec.UseLocalTimeZone = *timeOpt.UseLocalTimeZone - } - return &codec -} - -func (tc *TimeCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - if t != tTime { - return emptyValue, ValueDecoderError{ - Name: "TimeDecodeValue", - Types: []reflect.Type{tTime}, - Received: reflect.Zero(t), - } - } - - var timeVal time.Time - switch vrType := vr.Type(); vrType { - case bsontype.DateTime: - dt, err := vr.ReadDateTime() - if err != nil { - return emptyValue, 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 emptyValue, err - } - timeVal, err = time.Parse(timeFormatString, timeStr) - if err != nil { - return emptyValue, err - } - case bsontype.Int64: - i64, err := vr.ReadInt64() - if err != nil { - return emptyValue, err - } - timeVal = time.Unix(i64/1000, i64%1000*1000000) - case bsontype.Timestamp: - t, _, err := vr.ReadTimestamp() - if err != nil { - return emptyValue, err - } - timeVal = time.Unix(int64(t), 0) - case bsontype.Null: - if err := vr.ReadNull(); err != nil { - return emptyValue, err - } - case bsontype.Undefined: - if err := vr.ReadUndefined(); err != nil { - return emptyValue, err - } - default: - return emptyValue, fmt.Errorf("cannot decode %v into a time.Time", vrType) - } - - if !tc.UseLocalTimeZone && !dc.useLocalTimeZone { - timeVal = timeVal.UTC() - } - return reflect.ValueOf(timeVal), nil -} - -// 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} - } - - elem, err := tc.decodeType(dc, vr, tTime) - if err != nil { - return err - } - - val.Set(elem) - return nil -} - -// EncodeValue is the ValueEncoderFunc for time.TIme. -func (tc *TimeCodec) EncodeValue(_ 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) - dt := primitive.NewDateTimeFromTime(tt) - return vw.WriteDateTime(int64(dt)) -} 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 6ade17b7..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go +++ /dev/null @@ -1,58 +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 tBool = reflect.TypeOf(false) -var tFloat64 = reflect.TypeOf(float64(0)) -var tInt32 = reflect.TypeOf(int32(0)) -var tInt64 = reflect.TypeOf(int64(0)) -var tString = reflect.TypeOf("") -var tTime = reflect.TypeOf(time.Time{}) - -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 tZeroer = reflect.TypeOf((*Zeroer)(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 tA = reflect.TypeOf(primitive.A{}) -var tE = reflect.TypeOf(primitive.E{}) - -var tCoreDocument = reflect.TypeOf(bsoncore.Document{}) -var tCoreArray = reflect.TypeOf(bsoncore.Array{}) 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 39b07135..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/uint_codec.go +++ /dev/null @@ -1,202 +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" - "math" - "reflect" - - "go.mongodb.org/mongo-driver/bson/bsonoptions" - "go.mongodb.org/mongo-driver/bson/bsonrw" - "go.mongodb.org/mongo-driver/bson/bsontype" -) - -// UIntCodec is the Codec used for uint values. -// -// Deprecated: UIntCodec will not be directly configurable in Go Driver 2.0. To -// configure the uint encode and decode behavior, use the configuration methods -// on a [go.mongodb.org/mongo-driver/bson.Encoder] or -// [go.mongodb.org/mongo-driver/bson.Decoder]. To configure the uint encode and -// decode behavior for a mongo.Client, use -// [go.mongodb.org/mongo-driver/mongo/options.ClientOptions.SetBSONOptions]. -// -// For example, to configure a mongo.Client to marshal Go uint values as the -// minimum BSON int size that can represent the value, use: -// -// opt := options.Client().SetBSONOptions(&options.BSONOptions{ -// IntMinSize: true, -// }) -// -// See the deprecation notice for each field in UIntCodec for the corresponding -// settings. -type UIntCodec struct { - // EncodeToMinSize causes EncodeValue to marshal Go uint values (excluding uint64) as the - // minimum BSON int size (either 32-bit or 64-bit) that can represent the integer value. - // - // Deprecated: Use bson.Encoder.IntMinSize or options.BSONOptions.IntMinSize instead. - EncodeToMinSize bool -} - -var ( - defaultUIntCodec = NewUIntCodec() - - // Assert that defaultUIntCodec satisfies the typeDecoder interface, which allows it to be used - // by collection type decoders (e.g. map, slice, etc) to set individual values in a collection. - _ typeDecoder = defaultUIntCodec -) - -// NewUIntCodec returns a UIntCodec with options opts. -// -// Deprecated: NewUIntCodec will not be available in Go Driver 2.0. See -// [UIntCodec] for more details. -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, - } -} - -func (uic *UIntCodec) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) { - var i64 int64 - var err error - switch vrType := vr.Type(); vrType { - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return emptyValue, err - } - i64 = int64(i32) - case bsontype.Int64: - i64, err = vr.ReadInt64() - if err != nil { - return emptyValue, err - } - case bsontype.Double: - f64, err := vr.ReadDouble() - if err != nil { - return emptyValue, err - } - if !dc.Truncate && math.Floor(f64) != f64 { - return emptyValue, errCannotTruncate - } - if f64 > float64(math.MaxInt64) { - return emptyValue, fmt.Errorf("%g overflows int64", f64) - } - i64 = int64(f64) - case bsontype.Boolean: - b, err := vr.ReadBoolean() - if err != nil { - return emptyValue, err - } - if b { - i64 = 1 - } - case bsontype.Null: - if err = vr.ReadNull(); err != nil { - return emptyValue, err - } - case bsontype.Undefined: - if err = vr.ReadUndefined(); err != nil { - return emptyValue, err - } - default: - return emptyValue, fmt.Errorf("cannot decode %v into an integer type", vrType) - } - - switch t.Kind() { - case reflect.Uint8: - if i64 < 0 || i64 > math.MaxUint8 { - return emptyValue, fmt.Errorf("%d overflows uint8", i64) - } - - return reflect.ValueOf(uint8(i64)), nil - case reflect.Uint16: - if i64 < 0 || i64 > math.MaxUint16 { - return emptyValue, fmt.Errorf("%d overflows uint16", i64) - } - - return reflect.ValueOf(uint16(i64)), nil - case reflect.Uint32: - if i64 < 0 || i64 > math.MaxUint32 { - return emptyValue, fmt.Errorf("%d overflows uint32", i64) - } - - return reflect.ValueOf(uint32(i64)), nil - case reflect.Uint64: - if i64 < 0 { - return emptyValue, fmt.Errorf("%d overflows uint64", i64) - } - - return reflect.ValueOf(uint64(i64)), nil - case reflect.Uint: - if i64 < 0 { - return emptyValue, fmt.Errorf("%d overflows uint", i64) - } - v := uint64(i64) - if v > math.MaxUint { // Can we fit this inside of an uint - return emptyValue, fmt.Errorf("%d overflows uint", i64) - } - - return reflect.ValueOf(uint(v)), nil - default: - return emptyValue, ValueDecoderError{ - Name: "UintDecodeValue", - Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, - Received: reflect.Zero(t), - } - } -} - -// 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, - } - } - - elem, err := uic.decodeType(dc, vr, val.Type()) - if err != nil { - return err - } - - val.SetUint(elem.Uint()) - 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 996bd171..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/byte_slice_codec_options.go +++ /dev/null @@ -1,49 +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. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -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 -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -func ByteSliceCodec() *ByteSliceCodecOptions { - return &ByteSliceCodecOptions{} -} - -// SetEncodeNilAsEmpty specifies if a nil byte slice should encode as an empty binary instead of null. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilByteSliceAsEmpty] instead. -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. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -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/doc.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/doc.go deleted file mode 100644 index c40973c8..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2022-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 defines the optional configurations for the BSON codecs. -package bsonoptions 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 f522c7e0..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/empty_interface_codec_options.go +++ /dev/null @@ -1,49 +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. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -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 -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -func EmptyInterfaceCodec() *EmptyInterfaceCodecOptions { - return &EmptyInterfaceCodecOptions{} -} - -// SetDecodeBinaryAsSlice specifies if Old and Generic type binarys should default to []slice instead of primitive.Binary. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.BinaryAsSlice] instead. -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. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -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 a7a7c1d9..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/map_codec_options.go +++ /dev/null @@ -1,82 +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. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -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. - // Specifies how keys should be handled. If false, the behavior matches encoding/json, where the encoding key type must - // either be a string, an integer type, or implement bsoncodec.KeyMarshaler and the decoding key type must either be a - // string, an integer type, or implement bsoncodec.KeyUnmarshaler. If true, keys are encoded with fmt.Sprint() and the - // encoding key type must be a string, an integer type, or a float. If true, the use of Stringer will override - // TextMarshaler/TextUnmarshaler. Defaults to false. - EncodeKeysWithStringer *bool -} - -// MapCodec creates a new *MapCodecOptions -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -func MapCodec() *MapCodecOptions { - return &MapCodecOptions{} -} - -// SetDecodeZerosMap specifies if the map should be zeroed before decoding into it. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.ZeroMaps] instead. -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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilMapAsEmpty] instead. -func (t *MapCodecOptions) SetEncodeNilAsEmpty(b bool) *MapCodecOptions { - t.EncodeNilAsEmpty = &b - return t -} - -// SetEncodeKeysWithStringer specifies how keys should be handled. If false, the behavior matches encoding/json, where the -// encoding key type must either be a string, an integer type, or implement bsoncodec.KeyMarshaler and the decoding key -// type must either be a string, an integer type, or implement bsoncodec.KeyUnmarshaler. If true, keys are encoded with -// fmt.Sprint() and the encoding key type must be a string, an integer type, or a float. If true, the use of Stringer -// will override TextMarshaler/TextUnmarshaler. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.StringifyMapKeysWithFmt] instead. -func (t *MapCodecOptions) SetEncodeKeysWithStringer(b bool) *MapCodecOptions { - t.EncodeKeysWithStringer = &b - return t -} - -// MergeMapCodecOptions combines the given *MapCodecOptions into a single *MapCodecOptions in a last one wins fashion. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -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 - } - if opt.EncodeKeysWithStringer != nil { - s.EncodeKeysWithStringer = opt.EncodeKeysWithStringer - } - } - - 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 3c1e4f35..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/slice_codec_options.go +++ /dev/null @@ -1,49 +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. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -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 -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -func SliceCodec() *SliceCodecOptions { - return &SliceCodecOptions{} -} - -// SetEncodeNilAsEmpty specifies if a nil slice should encode as an empty array instead of null. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilSliceAsEmpty] instead. -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. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -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 f8b76f99..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/string_codec_options.go +++ /dev/null @@ -1,52 +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. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -type StringCodecOptions struct { - DecodeObjectIDAsHex *bool // Specifies if we should decode ObjectID as the hex value. Defaults to true. -} - -// StringCodec creates a new *StringCodecOptions -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -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. -// -// Deprecated: Decoding object IDs as raw bytes will not be supported in Go Driver 2.0. -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. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -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 1cbfa32e..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/struct_codec_options.go +++ /dev/null @@ -1,107 +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 defaultOverwriteDuplicatedInlinedFields = true - -// StructCodecOptions represents all possible options for struct encoding and decoding. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -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. - OverwriteDuplicatedInlinedFields *bool // Specifies if fields in inlined structs can be overwritten by higher level struct fields with the same key. Defaults to true. -} - -// StructCodec creates a new *StructCodecOptions -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -func StructCodec() *StructCodecOptions { - return &StructCodecOptions{} -} - -// SetDecodeZeroStruct specifies if structs should be zeroed before decoding into them. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.ZeroStructs] instead. -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. -// -// Deprecated: DecodeDeepZeroInline will not be supported in Go Driver 2.0. -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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.OmitZeroStruct] instead. -func (t *StructCodecOptions) SetEncodeOmitDefaultStruct(b bool) *StructCodecOptions { - t.EncodeOmitDefaultStruct = &b - return t -} - -// SetOverwriteDuplicatedInlinedFields specifies if inlined struct fields can be overwritten by higher level struct fields with the -// same bson key. When true and decoding, values will be written to the outermost struct with a matching key, and when -// encoding, keys will have the value of the top-most matching field. When false, decoding and encoding will error if -// there are duplicate keys after the struct is inlined. Defaults to true. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.ErrorOnInlineDuplicates] instead. -func (t *StructCodecOptions) SetOverwriteDuplicatedInlinedFields(b bool) *StructCodecOptions { - t.OverwriteDuplicatedInlinedFields = &b - return t -} - -// SetAllowUnexportedFields specifies if unexported fields should be marshaled/unmarshaled. Defaults to false. -// -// Deprecated: AllowUnexportedFields does not work on recent versions of Go and will not be -// supported in Go Driver 2.0. -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. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -func MergeStructCodecOptions(opts ...*StructCodecOptions) *StructCodecOptions { - s := &StructCodecOptions{ - OverwriteDuplicatedInlinedFields: &defaultOverwriteDuplicatedInlinedFields, - } - 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.OverwriteDuplicatedInlinedFields != nil { - s.OverwriteDuplicatedInlinedFields = opt.OverwriteDuplicatedInlinedFields - } - 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 3f38433d..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/time_codec_options.go +++ /dev/null @@ -1,49 +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. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -type TimeCodecOptions struct { - UseLocalTimeZone *bool // Specifies if we should decode into the local time zone. Defaults to false. -} - -// TimeCodec creates a new *TimeCodecOptions -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -func TimeCodec() *TimeCodecOptions { - return &TimeCodecOptions{} -} - -// SetUseLocalTimeZone specifies if we should decode into the local time zone. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.UseLocalTimeZone] instead. -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. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -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 5091e4d9..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonoptions/uint_codec_options.go +++ /dev/null @@ -1,49 +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. -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -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 -// -// Deprecated: Use the bson.Encoder and bson.Decoder configuration methods to set the desired BSON marshal -// and unmarshal behavior instead. -func UIntCodec() *UIntCodecOptions { - return &UIntCodecOptions{} -} - -// SetEncodeToMinSize specifies if all uints except uint64 should be decoded to minimum size bsontype. Defaults to false. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.IntMinSize] instead. -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. -// -// Deprecated: Merging options structs will not be supported in Go Driver 2.0. Users should create a -// single options struct instead. -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 1e25570b..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/copier.go +++ /dev/null @@ -1,489 +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" - "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. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -type Copier struct{} - -// NewCopier creates a new copier with the given registry. If a nil registry is provided -// a default registry is used. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func NewCopier() Copier { - return Copier{} -} - -// CopyDocument handles copying a document from src to dst. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func CopyDocument(dst ValueWriter, src ValueReader) error { - return Copier{}.CopyDocument(dst, src) -} - -// CopyDocument handles copying one document from the src to the dst. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -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) -} - -// CopyArrayFromBytes copies the values from a BSON array represented as a -// []byte to a ValueWriter. -// -// Deprecated: Copying BSON arrays using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func (c Copier) CopyArrayFromBytes(dst ValueWriter, src []byte) error { - aw, err := dst.WriteArray() - if err != nil { - return err - } - - err = c.CopyBytesToArrayWriter(aw, src) - if err != nil { - return err - } - - return aw.WriteArrayEnd() -} - -// CopyDocumentFromBytes copies the values from a BSON document represented as a -// []byte to a ValueWriter. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -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() -} - -type writeElementFn func(key string) (ValueWriter, error) - -// CopyBytesToArrayWriter copies the values from a BSON Array represented as a []byte to an -// ArrayWriter. -// -// Deprecated: Copying BSON arrays using the ArrayWriter interface will not be supported in Go -// Driver 2.0. -func (c Copier) CopyBytesToArrayWriter(dst ArrayWriter, src []byte) error { - wef := func(_ string) (ValueWriter, error) { - return dst.WriteArrayElement() - } - - return c.copyBytesToValueWriter(src, wef) -} - -// CopyBytesToDocumentWriter copies the values from a BSON document represented as a []byte to a -// DocumentWriter. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func (c Copier) CopyBytesToDocumentWriter(dst DocumentWriter, src []byte) error { - wef := func(key string) (ValueWriter, error) { - return dst.WriteDocumentElement(key) - } - - return c.copyBytesToValueWriter(src, wef) -} - -func (c Copier) copyBytesToValueWriter(src []byte, wef writeElementFn) error { - // TODO(skriptble): Create errors types here. Anything that is 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) - } - - // write as either array element or document element using writeElementFn - vw, err := wef(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(vw, t, val.Data) - if err != nil { - return err - } - } - return nil -} - -// CopyDocumentToBytes copies an entire document from the ValueReader and -// returns it as bytes. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -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. -// -// Deprecated: Copying BSON documents using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -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 putValueWriter(vw) - - vw.reset(dst) - - err := c.CopyDocument(vw, src) - dst = vw.buf - return dst, err -} - -// AppendArrayBytes copies an array from the ValueReader to dst. -// -// Deprecated: Copying BSON arrays using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -func (c Copier) AppendArrayBytes(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 putValueWriter(vw) - - vw.reset(dst) - - err := c.copyArray(vw, src) - dst = vw.buf - return dst, err -} - -// CopyValueFromBytes will write the value represtend by t and src to dst. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.UnmarshalValue] instead. -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. -// -// Deprecated: Use [go.mongodb.org/mongo-driver/bson.MarshalValue] instead. -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. -// -// Deprecated: Appending individual BSON elements to an existing slice will not be supported in Go -// Driver 2.0. -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 putValueWriter(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. -// -// Deprecated: Copying BSON values using the ValueWriter and ValueReader interfaces will not be -// supported in Go Driver 2.0. -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 errors.Is(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 errors.Is(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 f0702d9d..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_parser.go +++ /dev/null @@ -1,806 +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 ( - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "io" - "strings" - - "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 - relaxedUUID 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) - - // if $uuid is encountered, parse as binary subtype 4 - if ejp.k == "$uuid" { - ejp.relaxedUUID = true - t = bsontype.Binary - } - - 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 relaxed $uuid format - if ejp.relaxedUUID { - defer func() { ejp.relaxedUUID = false }() - uuid, err := ejp.v.parseSymbol() - if err != nil { - return nil, err - } - - // RFC 4122 defines the length of a UUID as 36 and the hyphens in a UUID as appearing - // in the 8th, 13th, 18th, and 23rd characters. - // - // See https://tools.ietf.org/html/rfc4122#section-3 - valid := len(uuid) == 36 && - string(uuid[8]) == "-" && - string(uuid[13]) == "-" && - string(uuid[18]) == "-" && - string(uuid[23]) == "-" - if !valid { - return nil, fmt.Errorf("$uuid value does not follow RFC 4122 format regarding length and hyphens") - } - - // remove hyphens - uuidNoHyphens := strings.ReplaceAll(uuid, "-", "") - if len(uuidNoHyphens) != 32 { - return nil, fmt.Errorf("$uuid value does not follow RFC 4122 format regarding length and hyphens") - } - - // convert hex to bytes - bytes, err := hex.DecodeString(uuidNoHyphens) - if err != nil { - return nil, fmt.Errorf("$uuid value does not follow RFC 4122 format regarding hex bytes: %w", err) - } - - ejp.advanceState() - if ejp.s != jpsSawEndObject { - return nil, invalidJSONErrorForType("$uuid and value and then }", bsontype.Binary) - } - - base64 := &extJSONValue{ - t: bsontype.String, - v: base64.StdEncoding.EncodeToString(bytes), - } - subType := &extJSONValue{ - t: bsontype.String, - v: "04", - } - - v = &extJSONValue{ - t: bsontype.EmbeddedDocument, - v: &extJSONObject{ - keys: []string{"base64", "subType"}, - values: []*extJSONValue{base64, subType}, - }, - } - - break - } - - // 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 described 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 59ddfc44..00000000 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_reader.go +++ /dev/null @@ -1,653 +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" - "sync" - - "go.mongodb.org/mongo-driver/bson/bsontype" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -// ExtJSONValueReaderPool is a pool for ValueReaders that read ExtJSON. -// -// Deprecated: ExtJSONValueReaderPool will not be supported in Go Driver 2.0. -type ExtJSONValueReaderPool struct { - pool sync.Pool -} - -// NewExtJSONValueReaderPool instantiates a new ExtJSONValueReaderPool. -// -// Deprecated: ExtJSONValueReaderPool will not be supported in Go Driver 2.0. -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. -// -// Deprecated: ExtJSONValueReaderPool will not be supported in Go Driver 2.0. -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. -// -// Deprecated: ExtJSONValueReaderPool will not be supported in Go Driver 2.0. -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) skipObject() { - // read entire object until depth returns to 0 (last ending } or ] seen) - depth := 1 - for depth > 0 { - ejvr.p.advanceState() - - // If object is empty, raise depth and continue. When emptyObject is true, the - // parser has already read both the opening and closing brackets of an empty - // object ("{}"), so the next valid token will be part of the parent document, - // not part of the nested document. - // - // If there is a comma, there are remaining fields, emptyObject must be set back - // to false, and comma must be skipped with advanceState(). - if ejvr.p.emptyObject { - if ejvr.p.s == jpsSawComma { - ejvr.p.emptyObject = false - ejvr.p.advanceState() - } - depth-- - continue - } - - switch ejvr.p.s { - case jpsSawBeginObject, jpsSawBeginArray: - depth++ - case jpsSawEndObject, jpsSawEndArray: - depth-- - } - } -} - -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, bsontype.EmbeddedDocument, bsontype.CodeWithScope: - // read entire array, doc or CodeWithScope - ejvr.skipObject() - 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 errors.Is(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 errors.Is(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