diff --git a/test/tools/go.mod b/test/tools/go.mod
index 9738306c56..c0627283a3 100644
--- a/test/tools/go.mod
+++ b/test/tools/go.mod
@@ -3,77 +3,79 @@ module github.com/containers/podman/test/tools
// Warning: if there is a "toolchain" directive anywhere in this file (and most of the
// time there shouldn't be), its version must be an exact match to the "go" directive.
-go 1.22.0
+go 1.25.0
require (
github.com/cpuguy83/go-md2man/v2 v2.0.7
- github.com/go-swagger/go-swagger v0.32.3
+ github.com/go-swagger/go-swagger v0.33.2
github.com/vbatts/git-validation v1.2.2
)
require (
+ dario.cat/mergo v1.0.2 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
- github.com/Masterminds/semver/v3 v3.2.1 // indirect
- github.com/Masterminds/sprig/v3 v3.2.3 // indirect
- github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
+ github.com/Masterminds/semver/v3 v3.4.0 // indirect
+ github.com/Masterminds/sprig/v3 v3.3.0 // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
- github.com/fsnotify/fsnotify v1.7.0 // indirect
- github.com/go-openapi/analysis v0.23.0 // indirect
- github.com/go-openapi/errors v0.22.0 // indirect
- github.com/go-openapi/inflect v0.21.0 // indirect
- github.com/go-openapi/jsonpointer v0.21.0 // indirect
- github.com/go-openapi/jsonreference v0.21.0 // indirect
- github.com/go-openapi/loads v0.22.0 // indirect
- github.com/go-openapi/runtime v0.28.0 // indirect
- github.com/go-openapi/spec v0.21.0 // indirect
- github.com/go-openapi/strfmt v0.23.0 // indirect
- github.com/go-openapi/swag v0.23.0 // indirect
- github.com/go-openapi/validate v0.24.0 // indirect
- github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
+ github.com/fsnotify/fsnotify v1.9.0 // indirect
+ github.com/go-openapi/analysis v0.24.3 // indirect
+ github.com/go-openapi/errors v0.22.7 // indirect
+ github.com/go-openapi/inflect v0.21.5 // 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.1 // 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/google/uuid v1.6.0 // indirect
github.com/gorilla/handlers v1.5.2 // indirect
github.com/hashicorp/go-version v1.6.0 // indirect
- github.com/hashicorp/hcl v1.0.0 // indirect
- github.com/huandu/xstrings v1.4.0 // indirect
- github.com/imdario/mergo v0.3.16 // indirect
- github.com/jessevdk/go-flags v1.5.0 // indirect
- github.com/josharian/intern v1.0.0 // indirect
+ github.com/huandu/xstrings v1.5.0 // indirect
+ github.com/jessevdk/go-flags v1.6.1 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/magefile/mage v1.15.0 // indirect
- github.com/magiconair/properties v1.8.7 // indirect
- github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
- github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
- github.com/oklog/ulid v1.3.1 // indirect
- github.com/pelletier/go-toml/v2 v2.1.1 // indirect
- github.com/rogpeppe/go-internal v1.12.0 // indirect
+ github.com/oklog/ulid/v2 v2.1.1 // indirect
+ github.com/pelletier/go-toml/v2 v2.2.4 // indirect
+ github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
- github.com/sagikazarmark/locafero v0.4.0 // indirect
- github.com/sagikazarmark/slog-shim v0.1.0 // indirect
- github.com/shopspring/decimal v1.3.1 // indirect
+ github.com/sagikazarmark/locafero v0.10.0 // indirect
+ github.com/shopspring/decimal v1.4.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
- github.com/sourcegraph/conc v0.3.0 // indirect
- github.com/spf13/afero v1.11.0 // indirect
- github.com/spf13/cast v1.6.0 // indirect
- github.com/spf13/pflag v1.0.5 // indirect
- github.com/spf13/viper v1.18.2 // indirect
+ github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
+ github.com/spf13/afero v1.14.0 // indirect
+ github.com/spf13/cast v1.10.0 // indirect
+ github.com/spf13/pflag v1.0.10 // indirect
+ github.com/spf13/viper v1.20.1 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
- github.com/toqueteos/webbrowser v1.2.0 // indirect
- go.mongodb.org/mongo-driver v1.14.0 // indirect
- go.uber.org/multierr v1.11.0 // indirect
- golang.org/x/crypto v0.31.0 // indirect
- golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect
- golang.org/x/mod v0.23.0 // indirect
- golang.org/x/sync v0.11.0 // indirect
- golang.org/x/sys v0.30.0 // indirect
- golang.org/x/text v0.21.0 // indirect
- golang.org/x/tools v0.30.0 // indirect
- gopkg.in/ini.v1 v1.67.0 // indirect
+ github.com/toqueteos/webbrowser v1.2.1 // indirect
+ go.yaml.in/yaml/v3 v3.0.4 // indirect
+ golang.org/x/crypto v0.49.0 // indirect
+ golang.org/x/mod v0.33.0 // indirect
+ golang.org/x/net v0.52.0 // indirect
+ golang.org/x/sync v0.20.0 // indirect
+ golang.org/x/sys v0.42.0 // indirect
+ golang.org/x/text v0.35.0 // indirect
+ golang.org/x/tools v0.42.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/test/tools/go.sum b/test/tools/go.sum
index 1370f500f6..90f69ed5be 100644
--- a/test/tools/go.sum
+++ b/test/tools/go.sum
@@ -1,12 +1,11 @@
+dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
+dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
-github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
-github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0=
-github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
-github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA=
-github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM=
-github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
-github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
+github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
+github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
+github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs=
+github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0=
github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=
github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
@@ -20,187 +19,153 @@ github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
-github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
-github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
-github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU=
-github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo=
-github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w=
-github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE=
-github.com/go-openapi/inflect v0.21.0 h1:FoBjBTQEcbg2cJUWX6uwL9OyIW8eqc9k4KhN4lfbeYk=
-github.com/go-openapi/inflect v0.21.0/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw=
-github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
-github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
-github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
-github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
-github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco=
-github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs=
-github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ=
-github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc=
-github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=
-github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=
-github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c=
-github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4=
-github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
-github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
-github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58=
-github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ=
-github.com/go-swagger/go-swagger v0.32.3 h1:bhAfZ4WaFXyPuw2OrXg34rOcUBR++fpVdonRRYzBK1c=
-github.com/go-swagger/go-swagger v0.32.3/go.mod h1:lAwO1nKff3qNRJYVQeTCl1am5pcNiiA2VyDf8TqzS24=
-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/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
+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/inflect v0.21.5 h1:M2RCq6PPS3YbIaL7CXosGL3BbzAcmfBAT0nC3YfesZA=
+github.com/go-openapi/inflect v0.21.5/go.mod h1:GypUyi6bU880NYurWaEH2CmH84zFDNd+EhhmzroHmB4=
+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.1 h1:7zGCHji7zSYDC2tCXIusoxYQz/48jAf2q+sF6wXTG+c=
+github.com/go-openapi/strfmt v0.26.1/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-swagger/go-swagger v0.33.2 h1:L1dxjjI29MKSWpRT0xXTOOaI3jzDWws2vR9oQmtYBZU=
+github.com/go-swagger/go-swagger v0.33.2/go.mod h1:1HGAWunq7SIuIPIWPHlZEDBURdzUk3BxSPr7x4dFHjc=
+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/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
-github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
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/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek=
github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
-github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
-github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
-github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
-github.com/huandu/xstrings v1.4.0 h1:D17IlohoQq4UcpqD7fDk80P7l+lwAmlFaBHgOipl2FU=
-github.com/huandu/xstrings v1.4.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
-github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
-github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4=
-github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY=
-github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc=
-github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
-github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
-github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
+github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
+github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
+github.com/jessevdk/go-flags v1.6.1 h1:Cvu5U8UGrLay1rZfv/zP7iLpSHGUZ/Ou68T0iX1bBK4=
+github.com/jessevdk/go-flags v1.6.1/go.mod h1:Mk8T1hIAWpOiJiHa9rJASDK2UGWji0EuPGBnNLMooyc=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/magefile/mage v1.15.0 h1:BvGheCMAsG3bWUDbZ8AyXXpCNwU9u5CB6sM+HNb9HYg=
github.com/magefile/mage v1.15.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A=
-github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
-github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
-github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
-github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
-github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
-github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
-github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
-github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
-github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
-github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
-github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
-github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
+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/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
-github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
-github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
-github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
-github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
-github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
-github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
-github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
-github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8=
-github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
+github.com/sagikazarmark/locafero v0.10.0 h1:FM8Cv6j2KqIhM2ZK7HZjm4mpj9NBktLgowT1aN9q5Cc=
+github.com/sagikazarmark/locafero v0.10.0/go.mod h1:Ieo3EUsjifvQu4NZwV5sPd4dwvu0OCgEQV7vjc9yDjw=
+github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
+github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
-github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
-github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
-github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
-github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
-github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
-github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
-github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
-github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
-github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
-github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=
-github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk=
+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
+github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
+github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
+github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
+github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
+github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
-github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
-github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
-github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
-github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
-github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
-github.com/toqueteos/webbrowser v1.2.0 h1:tVP/gpK69Fx+qMJKsLE7TD8LuGWPnEV71wBN9rrstGQ=
-github.com/toqueteos/webbrowser v1.2.0/go.mod h1:XWoZq4cyp9WeUeak7w7LXRUQf1F1ATJMir8RTqb4ayM=
+github.com/toqueteos/webbrowser v1.2.1 h1:O7IsnnU7XQyJ1nHMRfAktUUJOAZD3aQyUVnxzhWphCg=
+github.com/toqueteos/webbrowser v1.2.1/go.mod h1:XWoZq4cyp9WeUeak7w7LXRUQf1F1ATJMir8RTqb4ayM=
github.com/vbatts/git-validation v1.2.2 h1:AHTS8Jara7Pcu0ub7RusMBAvyLtjsJtF/xPU5Pm1BPE=
github.com/vbatts/git-validation v1.2.2/go.mod h1:Fj+04EdPcZ0rMOR+dqvppMVVgyNcOFRT5iFWuIc593A=
-github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
-go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80=
-go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c=
-go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
-go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
-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=
-golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
-golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
-golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
-golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ=
-golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc=
-golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
-golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM=
-golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
-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=
-golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
-golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
+golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
+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.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
+golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
-golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-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.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
-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=
-golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
-golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
-golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
-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.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
-golang.org/x/tools v0.30.0 h1:BgcpHewrV5AUp2G9MebG4XPFI1E2W41zU1SaqVA9vJY=
-golang.org/x/tools v0.30.0/go.mod h1:c347cR/OJfw5TI+GfX7RUPNMdDRRbjvYTS0jPyvsVtY=
-golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
+golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
+golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
+golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
+golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-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=
-gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
-gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
-gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/test/tools/vendor/github.com/imdario/mergo/.deepsource.toml b/test/tools/vendor/dario.cat/mergo/.deepsource.toml
similarity index 72%
rename from test/tools/vendor/github.com/imdario/mergo/.deepsource.toml
rename to test/tools/vendor/dario.cat/mergo/.deepsource.toml
index 8a0681af85..a8bc979e02 100644
--- a/test/tools/vendor/github.com/imdario/mergo/.deepsource.toml
+++ b/test/tools/vendor/dario.cat/mergo/.deepsource.toml
@@ -9,4 +9,4 @@ name = "go"
enabled = true
[analyzers.meta]
- import_path = "github.com/imdario/mergo"
\ No newline at end of file
+ import_path = "dario.cat/mergo"
\ No newline at end of file
diff --git a/test/tools/vendor/github.com/imdario/mergo/.gitignore b/test/tools/vendor/dario.cat/mergo/.gitignore
similarity index 95%
rename from test/tools/vendor/github.com/imdario/mergo/.gitignore
rename to test/tools/vendor/dario.cat/mergo/.gitignore
index 529c3412ba..45ad0f1ae3 100644
--- a/test/tools/vendor/github.com/imdario/mergo/.gitignore
+++ b/test/tools/vendor/dario.cat/mergo/.gitignore
@@ -13,6 +13,9 @@
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
+# Golang/Intellij
+.idea
+
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/
diff --git a/test/tools/vendor/github.com/imdario/mergo/.travis.yml b/test/tools/vendor/dario.cat/mergo/.travis.yml
similarity index 100%
rename from test/tools/vendor/github.com/imdario/mergo/.travis.yml
rename to test/tools/vendor/dario.cat/mergo/.travis.yml
diff --git a/test/tools/vendor/github.com/imdario/mergo/CODE_OF_CONDUCT.md b/test/tools/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md
similarity index 100%
rename from test/tools/vendor/github.com/imdario/mergo/CODE_OF_CONDUCT.md
rename to test/tools/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md
diff --git a/test/tools/vendor/github.com/imdario/mergo/CONTRIBUTING.md b/test/tools/vendor/dario.cat/mergo/CONTRIBUTING.md
similarity index 100%
rename from test/tools/vendor/github.com/imdario/mergo/CONTRIBUTING.md
rename to test/tools/vendor/dario.cat/mergo/CONTRIBUTING.md
diff --git a/test/tools/vendor/dario.cat/mergo/FUNDING.json b/test/tools/vendor/dario.cat/mergo/FUNDING.json
new file mode 100644
index 0000000000..0585e1fe13
--- /dev/null
+++ b/test/tools/vendor/dario.cat/mergo/FUNDING.json
@@ -0,0 +1,7 @@
+{
+ "drips": {
+ "ethereum": {
+ "ownedBy": "0x6160020e7102237aC41bdb156e94401692D76930"
+ }
+ }
+}
diff --git a/test/tools/vendor/github.com/imdario/mergo/LICENSE b/test/tools/vendor/dario.cat/mergo/LICENSE
similarity index 100%
rename from test/tools/vendor/github.com/imdario/mergo/LICENSE
rename to test/tools/vendor/dario.cat/mergo/LICENSE
diff --git a/test/tools/vendor/github.com/imdario/mergo/README.md b/test/tools/vendor/dario.cat/mergo/README.md
similarity index 65%
rename from test/tools/vendor/github.com/imdario/mergo/README.md
rename to test/tools/vendor/dario.cat/mergo/README.md
index ffbbb62c70..0e4a59afd9 100644
--- a/test/tools/vendor/github.com/imdario/mergo/README.md
+++ b/test/tools/vendor/dario.cat/mergo/README.md
@@ -44,77 +44,59 @@ Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the
## Status
-It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, Microsoft, etc](https://github.com/imdario/mergo#mergo-in-the-wild).
+Mergo is stable and frozen, ready for production. Check a short list of the projects using at large scale it [here](https://github.com/imdario/mergo#mergo-in-the-wild).
-### Important note
+No new features are accepted. They will be considered for a future v2 that improves the implementation and fixes bugs for corner cases.
+
+### Important notes
+
+#### 1.0.0
+
+In [1.0.0](//github.com/imdario/mergo/releases/tag/1.0.0) Mergo moves to a vanity URL `dario.cat/mergo`. No more v1 versions will be released.
+
+If the vanity URL is causing issues in your project due to a dependency pulling Mergo - it isn't a direct dependency in your project - it is recommended to use [replace](https://github.com/golang/go/wiki/Modules#when-should-i-use-the-replace-directive) to pin the version to the last one with the old import URL:
+
+```
+replace github.com/imdario/mergo => github.com/imdario/mergo v0.3.16
+```
+
+#### 0.3.9
Please keep in mind that a problematic PR broke [0.3.9](//github.com/imdario/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//github.com/imdario/mergo/releases/tag/0.3.10), and I consider it stable but not bug-free. Also, this version adds support for go modules.
Keep in mind that in [0.3.2](//github.com/imdario/mergo/releases/tag/0.3.2), Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). I added an optional/variadic argument so that it won't break the existing code.
-If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u github.com/imdario/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
+If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u dario.cat/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
### Donations
If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes:
-
### Mergo in the wild
-- [moby/moby](https://github.com/moby/moby)
-- [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes)
-- [vmware/dispatch](https://github.com/vmware/dispatch)
-- [Shopify/themekit](https://github.com/Shopify/themekit)
-- [imdario/zas](https://github.com/imdario/zas)
-- [matcornic/hermes](https://github.com/matcornic/hermes)
-- [OpenBazaar/openbazaar-go](https://github.com/OpenBazaar/openbazaar-go)
-- [kataras/iris](https://github.com/kataras/iris)
-- [michaelsauter/crane](https://github.com/michaelsauter/crane)
-- [go-task/task](https://github.com/go-task/task)
-- [sensu/uchiwa](https://github.com/sensu/uchiwa)
-- [ory/hydra](https://github.com/ory/hydra)
-- [sisatech/vcli](https://github.com/sisatech/vcli)
-- [dairycart/dairycart](https://github.com/dairycart/dairycart)
-- [projectcalico/felix](https://github.com/projectcalico/felix)
-- [resin-os/balena](https://github.com/resin-os/balena)
-- [go-kivik/kivik](https://github.com/go-kivik/kivik)
-- [Telefonica/govice](https://github.com/Telefonica/govice)
-- [supergiant/supergiant](supergiant/supergiant)
-- [SergeyTsalkov/brooce](https://github.com/SergeyTsalkov/brooce)
-- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy)
-- [ohsu-comp-bio/funnel](https://github.com/ohsu-comp-bio/funnel)
-- [EagerIO/Stout](https://github.com/EagerIO/Stout)
-- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api)
-- [russross/canvasassignments](https://github.com/russross/canvasassignments)
-- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api)
-- [casualjim/exeggutor](https://github.com/casualjim/exeggutor)
-- [divshot/gitling](https://github.com/divshot/gitling)
-- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl)
-- [andrerocker/deploy42](https://github.com/andrerocker/deploy42)
-- [elwinar/rambler](https://github.com/elwinar/rambler)
-- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman)
-- [jfbus/impressionist](https://github.com/jfbus/impressionist)
-- [Jmeyering/zealot](https://github.com/Jmeyering/zealot)
-- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host)
-- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go)
-- [thoas/picfit](https://github.com/thoas/picfit)
-- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server)
-- [jnuthong/item_search](https://github.com/jnuthong/item_search)
-- [bukalapak/snowboard](https://github.com/bukalapak/snowboard)
-- [containerssh/containerssh](https://github.com/containerssh/containerssh)
-- [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser)
-- [tjpnz/structbot](https://github.com/tjpnz/structbot)
+Mergo is used by [thousands](https://deps.dev/go/dario.cat%2Fmergo/v1.0.0/dependents) [of](https://deps.dev/go/github.com%2Fimdario%2Fmergo/v0.3.16/dependents) [projects](https://deps.dev/go/github.com%2Fimdario%2Fmergo/v0.3.12), including:
+
+* [containerd/containerd](https://github.com/containerd/containerd)
+* [datadog/datadog-agent](https://github.com/datadog/datadog-agent)
+* [docker/cli/](https://github.com/docker/cli/)
+* [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser)
+* [go-micro/go-micro](https://github.com/go-micro/go-micro)
+* [grafana/loki](https://github.com/grafana/loki)
+* [masterminds/sprig](github.com/Masterminds/sprig)
+* [moby/moby](https://github.com/moby/moby)
+* [slackhq/nebula](https://github.com/slackhq/nebula)
+* [volcano-sh/volcano](https://github.com/volcano-sh/volcano)
## Install
- go get github.com/imdario/mergo
+ go get dario.cat/mergo
// use in your .go code
import (
- "github.com/imdario/mergo"
+ "dario.cat/mergo"
)
## Usage
@@ -135,6 +117,39 @@ if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
}
```
+If you need to override pointers, so the source pointer's value is assigned to the destination's pointer, you must use `WithoutDereference`:
+
+```go
+package main
+
+import (
+ "fmt"
+
+ "dario.cat/mergo"
+)
+
+type Foo struct {
+ A *string
+ B int64
+}
+
+func main() {
+ first := "first"
+ second := "second"
+ src := Foo{
+ A: &first,
+ B: 2,
+ }
+
+ dest := Foo{
+ A: &second,
+ B: 1,
+ }
+
+ mergo.Merge(&dest, src, mergo.WithOverride, mergo.WithoutDereference)
+}
+```
+
Additionally, you can map a `map[string]interface{}` to a struct (and otherwise, from struct to map), following the same restrictions as in `Merge()`. Keys are capitalized to find each corresponding exported field.
```go
@@ -152,7 +167,7 @@ package main
import (
"fmt"
- "github.com/imdario/mergo"
+ "dario.cat/mergo"
)
type Foo struct {
@@ -175,10 +190,6 @@ func main() {
}
```
-Note: if test are failing due missing package, please execute:
-
- go get gopkg.in/yaml.v3
-
### Transformers
Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, `time.Time` is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero `time.Time`?
@@ -188,9 +199,9 @@ package main
import (
"fmt"
- "github.com/imdario/mergo"
- "reflect"
- "time"
+ "dario.cat/mergo"
+ "reflect"
+ "time"
)
type timeTransformer struct {
diff --git a/test/tools/vendor/github.com/imdario/mergo/SECURITY.md b/test/tools/vendor/dario.cat/mergo/SECURITY.md
similarity index 82%
rename from test/tools/vendor/github.com/imdario/mergo/SECURITY.md
rename to test/tools/vendor/dario.cat/mergo/SECURITY.md
index a5de61f77b..3788fcc1c2 100644
--- a/test/tools/vendor/github.com/imdario/mergo/SECURITY.md
+++ b/test/tools/vendor/dario.cat/mergo/SECURITY.md
@@ -4,8 +4,8 @@
| Version | Supported |
| ------- | ------------------ |
-| 0.3.x | :white_check_mark: |
-| < 0.3 | :x: |
+| 1.x.x | :white_check_mark: |
+| < 1.0 | :x: |
## Security contact information
diff --git a/test/tools/vendor/github.com/imdario/mergo/doc.go b/test/tools/vendor/dario.cat/mergo/doc.go
similarity index 88%
rename from test/tools/vendor/github.com/imdario/mergo/doc.go
rename to test/tools/vendor/dario.cat/mergo/doc.go
index fcd985f995..7d96ec0546 100644
--- a/test/tools/vendor/github.com/imdario/mergo/doc.go
+++ b/test/tools/vendor/dario.cat/mergo/doc.go
@@ -8,30 +8,36 @@ A helper to merge structs and maps in Golang. Useful for configuration default v
Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection).
-Status
+# Status
It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc.
-Important note
+# Important notes
+
+1.0.0
+
+In 1.0.0 Mergo moves to a vanity URL `dario.cat/mergo`.
+
+0.3.9
Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules.
Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code.
-If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u github.com/imdario/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
+If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u dario.cat/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
-Install
+# Install
Do your usual installation procedure:
- go get github.com/imdario/mergo
+ go get dario.cat/mergo
- // use in your .go code
- import (
- "github.com/imdario/mergo"
- )
+ // use in your .go code
+ import (
+ "dario.cat/mergo"
+ )
-Usage
+# Usage
You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).
@@ -59,7 +65,7 @@ Here is a nice example:
import (
"fmt"
- "github.com/imdario/mergo"
+ "dario.cat/mergo"
)
type Foo struct {
@@ -81,7 +87,7 @@ Here is a nice example:
// {two 2}
}
-Transformers
+# Transformers
Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time?
@@ -89,9 +95,9 @@ Transformers allow to merge specific types differently than in the default behav
import (
"fmt"
- "github.com/imdario/mergo"
- "reflect"
- "time"
+ "dario.cat/mergo"
+ "reflect"
+ "time"
)
type timeTransformer struct {
@@ -127,17 +133,16 @@ Transformers allow to merge specific types differently than in the default behav
// { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 }
}
-Contact me
+# Contact me
If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario
-About
+# About
Written by Dario Castañé: https://da.rio.hn
-License
+# License
BSD 3-Clause license, as Go language.
-
*/
package mergo
diff --git a/test/tools/vendor/github.com/imdario/mergo/map.go b/test/tools/vendor/dario.cat/mergo/map.go
similarity index 96%
rename from test/tools/vendor/github.com/imdario/mergo/map.go
rename to test/tools/vendor/dario.cat/mergo/map.go
index b50d5c2a4e..759b4f74fd 100644
--- a/test/tools/vendor/github.com/imdario/mergo/map.go
+++ b/test/tools/vendor/dario.cat/mergo/map.go
@@ -58,7 +58,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf
}
fieldName := field.Name
fieldName = changeInitialCase(fieldName, unicode.ToLower)
- if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v), !config.ShouldNotDereference) || overwrite) {
+ if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) || config.overwriteWithEmptyValue {
dstMap[fieldName] = src.Field(i).Interface()
}
}
diff --git a/test/tools/vendor/github.com/imdario/mergo/merge.go b/test/tools/vendor/dario.cat/mergo/merge.go
similarity index 99%
rename from test/tools/vendor/github.com/imdario/mergo/merge.go
rename to test/tools/vendor/dario.cat/mergo/merge.go
index 0ef9b2138c..fd47c95b2b 100644
--- a/test/tools/vendor/github.com/imdario/mergo/merge.go
+++ b/test/tools/vendor/dario.cat/mergo/merge.go
@@ -269,7 +269,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co
if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil {
return
}
- } else {
+ } else if src.Elem().Kind() != reflect.Struct {
if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() {
dst.Set(src)
}
diff --git a/test/tools/vendor/github.com/imdario/mergo/mergo.go b/test/tools/vendor/dario.cat/mergo/mergo.go
similarity index 100%
rename from test/tools/vendor/github.com/imdario/mergo/mergo.go
rename to test/tools/vendor/dario.cat/mergo/mergo.go
diff --git a/test/tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md b/test/tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md
index f12626423a..fabe5e43dc 100644
--- a/test/tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md
+++ b/test/tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md
@@ -1,5 +1,59 @@
# Changelog
+## 3.4.0 (2025-06-27)
+
+### Added
+
+- #268: Added property to Constraints to include prereleases for Check and Validate
+
+### Changed
+
+- #263: Updated Go testing for 1.24, 1.23, and 1.22
+- #269: Updated the error message handling for message case and wrapping errors
+- #266: Restore the ability to have leading 0's when parsing with NewVersion.
+ Opt-out of this by setting CoerceNewVersion to false.
+
+### Fixed
+
+- #257: Fixed the CodeQL link (thanks @dmitris)
+- #262: Restored detailed errors when failed to parse with NewVersion. Opt-out
+ of this by setting DetailedNewVersionErrors to false for faster performance.
+- #267: Handle pre-releases for an "and" group if one constraint includes them
+
+## 3.3.1 (2024-11-19)
+
+### Fixed
+
+- #253: Fix for allowing some version that were invalid
+
+## 3.3.0 (2024-08-27)
+
+### Added
+
+- #238: Add LessThanEqual and GreaterThanEqual functions (thanks @grosser)
+- #213: nil version equality checking (thanks @KnutZuidema)
+
+### Changed
+
+- #241: Simplify StrictNewVersion parsing (thanks @grosser)
+- Testing support up through Go 1.23
+- Minimum version set to 1.21 as this is what's tested now
+- Fuzz testing now supports caching
+
+## 3.2.1 (2023-04-10)
+
+### Changed
+
+- #198: Improved testing around pre-release names
+- #200: Improved code scanning with addition of CodeQL
+- #201: Testing now includes Go 1.20. Go 1.17 has been dropped
+- #202: Migrated Fuzz testing to Go built-in Fuzzing. CI runs daily
+- #203: Docs updated for security details
+
+### Fixed
+
+- #199: Fixed issue with range transformations
+
## 3.2.0 (2022-11-28)
### Added
@@ -109,7 +163,7 @@ functions. These are described in the added and changed sections below.
- #78: Fix unchecked error in example code (thanks @ravron)
- #70: Fix the handling of pre-releases and the 0.0.0 release edge case
- #97: Fixed copyright file for proper display on GitHub
-- #107: Fix handling prerelease when sorting alphanum and num
+- #107: Fix handling prerelease when sorting alphanum and num
- #109: Fixed where Validate sometimes returns wrong message on error
## 1.4.2 (2018-04-10)
diff --git a/test/tools/vendor/github.com/Masterminds/semver/v3/Makefile b/test/tools/vendor/github.com/Masterminds/semver/v3/Makefile
index 0e7b5c7138..9ca87a2c79 100644
--- a/test/tools/vendor/github.com/Masterminds/semver/v3/Makefile
+++ b/test/tools/vendor/github.com/Masterminds/semver/v3/Makefile
@@ -19,6 +19,7 @@ test-cover:
.PHONY: fuzz
fuzz:
@echo "==> Running Fuzz Tests"
+ go env GOCACHE
go test -fuzz=FuzzNewVersion -fuzztime=15s .
go test -fuzz=FuzzStrictNewVersion -fuzztime=15s .
go test -fuzz=FuzzNewConstraint -fuzztime=15s .
@@ -27,4 +28,4 @@ $(GOLANGCI_LINT):
# Install golangci-lint. The configuration for it is in the .golangci.yml
# file in the root of the repository
echo ${GOPATH}
- curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.17.1
+ curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.56.2
diff --git a/test/tools/vendor/github.com/Masterminds/semver/v3/README.md b/test/tools/vendor/github.com/Masterminds/semver/v3/README.md
index eab8cac3b7..2f56c676a5 100644
--- a/test/tools/vendor/github.com/Masterminds/semver/v3/README.md
+++ b/test/tools/vendor/github.com/Masterminds/semver/v3/README.md
@@ -13,12 +13,9 @@ Active](https://masterminds.github.io/stability/active.svg)](https://masterminds
[](https://pkg.go.dev/github.com/Masterminds/semver/v3)
[](https://goreportcard.com/report/github.com/Masterminds/semver)
-If you are looking for a command line tool for version comparisons please see
-[vert](https://github.com/Masterminds/vert) which uses this library.
-
## Package Versions
-Note, import `github.com/github.com/Masterminds/semver/v3` to use the latest version.
+Note, import `github.com/Masterminds/semver/v3` to use the latest version.
There are three major versions fo the `semver` package.
@@ -53,6 +50,18 @@ other versions, convert the version back into a string, and get the original
string. Getting the original string is useful if the semantic version was coerced
into a valid form.
+There are package level variables that affect how `NewVersion` handles parsing.
+
+- `CoerceNewVersion` is `true` by default. When set to `true` it coerces non-compliant
+ versions into SemVer. For example, allowing a leading 0 in a major, minor, or patch
+ part. This enables the use of CalVer in versions even when not compliant with SemVer.
+ When set to `false` less coercion work is done.
+- `DetailedNewVersionErrors` provides more detailed errors. It only has an affect when
+ `CoerceNewVersion` is set to `false`. When `DetailedNewVersionErrors` is set to `true`
+ it can provide some more insight into why a version is invalid. Setting
+ `DetailedNewVersionErrors` to `false` is faster on performance but provides less
+ detailed error messages if a version fails to parse.
+
## Sorting Semantic Versions
A set of versions can be sorted using the `sort` package from the standard library.
@@ -80,12 +89,12 @@ There are two methods for comparing versions. One uses comparison methods on
differences to notes between these two methods of comparison.
1. When two versions are compared using functions such as `Compare`, `LessThan`,
- and others it will follow the specification and always include prereleases
+ and others it will follow the specification and always include pre-releases
within the comparison. It will provide an answer that is valid with the
comparison section of the spec at https://semver.org/#spec-item-11
2. When constraint checking is used for checks or validation it will follow a
different set of rules that are common for ranges with tools like npm/js
- and Rust/Cargo. This includes considering prereleases to be invalid if the
+ and Rust/Cargo. This includes considering pre-releases to be invalid if the
ranges does not include one. If you want to have it include pre-releases a
simple solution is to include `-0` in your range.
3. Constraint ranges can have some complex rules including the shorthand use of
@@ -113,7 +122,7 @@ v, err := semver.NewVersion("1.3")
if err != nil {
// Handle version not being parsable.
}
-// Check if the version meets the constraints. The a variable will be true.
+// Check if the version meets the constraints. The variable a will be true.
a := c.Check(v)
```
@@ -137,20 +146,20 @@ The basic comparisons are:
### Working With Prerelease Versions
Pre-releases, for those not familiar with them, are used for software releases
-prior to stable or generally available releases. Examples of prereleases include
-development, alpha, beta, and release candidate releases. A prerelease may be
+prior to stable or generally available releases. Examples of pre-releases include
+development, alpha, beta, and release candidate releases. A pre-release may be
a version such as `1.2.3-beta.1` while the stable release would be `1.2.3`. In the
-order of precedence, prereleases come before their associated releases. In this
+order of precedence, pre-releases come before their associated releases. In this
example `1.2.3-beta.1 < 1.2.3`.
-According to the Semantic Version specification prereleases may not be
+According to the Semantic Version specification, pre-releases may not be
API compliant with their release counterpart. It says,
> A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version.
-SemVer comparisons using constraints without a prerelease comparator will skip
-prerelease versions. For example, `>=1.2.3` will skip prereleases when looking
-at a list of releases while `>=1.2.3-0` will evaluate and find prereleases.
+SemVer's comparisons using constraints without a pre-release comparator will skip
+pre-release versions. For example, `>=1.2.3` will skip pre-releases when looking
+at a list of releases while `>=1.2.3-0` will evaluate and find pre-releases.
The reason for the `0` as a pre-release version in the example comparison is
because pre-releases can only contain ASCII alphanumerics and hyphens (along with
@@ -163,6 +172,10 @@ means `>=1.2.3-BETA` will return `1.2.3-alpha`. What you might expect from case
sensitivity doesn't apply here. This is due to ASCII sort ordering which is what
the spec specifies.
+The `Constraints` instance returned from `semver.NewConstraint()` has a property
+`IncludePrerelease` that, when set to true, will return prerelease versions when calls
+to `Check()` and `Validate()` are made.
+
### Hyphen Range Comparisons
There are multiple methods to handle ranges and the first is hyphens ranges.
@@ -171,6 +184,9 @@ These look like:
* `1.2 - 1.4.5` which is equivalent to `>= 1.2 <= 1.4.5`
* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4 <= 4.5`
+Note that `1.2-1.4.5` without whitespace is parsed completely differently; it's
+parsed as a single constraint `1.2.0` with _prerelease_ `1.4.5`.
+
### Wildcards In Comparisons
The `x`, `X`, and `*` characters can be used as a wildcard character. This works
@@ -250,7 +266,7 @@ or [create a pull request](https://github.com/Masterminds/semver/pulls).
Security is an important consideration for this project. The project currently
uses the following tools to help discover security issues:
-* [CodeQL](https://github.com/Masterminds/semver)
+* [CodeQL](https://codeql.github.com)
* [gosec](https://github.com/securego/gosec)
* Daily Fuzz testing
diff --git a/test/tools/vendor/github.com/Masterminds/semver/v3/constraints.go b/test/tools/vendor/github.com/Masterminds/semver/v3/constraints.go
index 8461c7ed90..8b7a10f836 100644
--- a/test/tools/vendor/github.com/Masterminds/semver/v3/constraints.go
+++ b/test/tools/vendor/github.com/Masterminds/semver/v3/constraints.go
@@ -12,6 +12,13 @@ import (
// checked against.
type Constraints struct {
constraints [][]*constraint
+ containsPre []bool
+
+ // IncludePrerelease specifies if pre-releases should be included in
+ // the results. Note, if a constraint range has a prerelease than
+ // prereleases will be included for that AND group even if this is
+ // set to false.
+ IncludePrerelease bool
}
// NewConstraint returns a Constraints instance that a Version instance can
@@ -22,11 +29,10 @@ func NewConstraint(c string) (*Constraints, error) {
c = rewriteRange(c)
ors := strings.Split(c, "||")
- or := make([][]*constraint, len(ors))
+ lenors := len(ors)
+ or := make([][]*constraint, lenors)
+ hasPre := make([]bool, lenors)
for k, v := range ors {
-
- // TODO: Find a way to validate and fetch all the constraints in a simpler form
-
// Validate the segment
if !validConstraintRegex.MatchString(v) {
return nil, fmt.Errorf("improper constraint: %s", v)
@@ -43,12 +49,22 @@ func NewConstraint(c string) (*Constraints, error) {
return nil, err
}
+ // If one of the constraints has a prerelease record this.
+ // This information is used when checking all in an "and"
+ // group to ensure they all check for prereleases.
+ if pc.con.pre != "" {
+ hasPre[k] = true
+ }
+
result[i] = pc
}
or[k] = result
}
- o := &Constraints{constraints: or}
+ o := &Constraints{
+ constraints: or,
+ containsPre: hasPre,
+ }
return o, nil
}
@@ -57,10 +73,10 @@ func (cs Constraints) Check(v *Version) bool {
// TODO(mattfarina): For v4 of this library consolidate the Check and Validate
// functions as the underlying functions make that possible now.
// loop over the ORs and check the inner ANDs
- for _, o := range cs.constraints {
+ for i, o := range cs.constraints {
joy := true
for _, c := range o {
- if check, _ := c.check(v); !check {
+ if check, _ := c.check(v, (cs.IncludePrerelease || cs.containsPre[i])); !check {
joy = false
break
}
@@ -83,12 +99,12 @@ func (cs Constraints) Validate(v *Version) (bool, []error) {
// Capture the prerelease message only once. When it happens the first time
// this var is marked
var prerelesase bool
- for _, o := range cs.constraints {
+ for i, o := range cs.constraints {
joy := true
for _, c := range o {
// Before running the check handle the case there the version is
// a prerelease and the check is not searching for prereleases.
- if c.con.pre == "" && v.pre != "" {
+ if !(cs.IncludePrerelease || cs.containsPre[i]) && v.pre != "" {
if !prerelesase {
em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
e = append(e, em)
@@ -98,7 +114,7 @@ func (cs Constraints) Validate(v *Version) (bool, []error) {
} else {
- if _, err := c.check(v); err != nil {
+ if _, err := c.check(v, (cs.IncludePrerelease || cs.containsPre[i])); err != nil {
e = append(e, err)
joy = false
}
@@ -227,8 +243,8 @@ type constraint struct {
}
// Check if a version meets the constraint
-func (c *constraint) check(v *Version) (bool, error) {
- return constraintOps[c.origfunc](v, c)
+func (c *constraint) check(v *Version, includePre bool) (bool, error) {
+ return constraintOps[c.origfunc](v, c, includePre)
}
// String prints an individual constraint into a string
@@ -236,7 +252,7 @@ func (c *constraint) string() string {
return c.origfunc + c.orig
}
-type cfunc func(v *Version, c *constraint) (bool, error)
+type cfunc func(v *Version, c *constraint, includePre bool) (bool, error)
func parseConstraint(c string) (*constraint, error) {
if len(c) > 0 {
@@ -272,7 +288,7 @@ func parseConstraint(c string) (*constraint, error) {
// The constraintRegex should catch any regex parsing errors. So,
// we should never get here.
- return nil, errors.New("constraint Parser Error")
+ return nil, errors.New("constraint parser error")
}
cs.con = con
@@ -290,7 +306,7 @@ func parseConstraint(c string) (*constraint, error) {
// The constraintRegex should catch any regex parsing errors. So,
// we should never get here.
- return nil, errors.New("constraint Parser Error")
+ return nil, errors.New("constraint parser error")
}
cs := &constraint{
@@ -305,16 +321,14 @@ func parseConstraint(c string) (*constraint, error) {
}
// Constraint functions
-func constraintNotEqual(v *Version, c *constraint) (bool, error) {
+func constraintNotEqual(v *Version, c *constraint, includePre bool) (bool, error) {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
+ return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
+ }
+
if c.dirty {
-
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
- return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
- }
-
if c.con.Major() != v.Major() {
return true, nil
}
@@ -345,12 +359,11 @@ func constraintNotEqual(v *Version, c *constraint) (bool, error) {
return true, nil
}
-func constraintGreaterThan(v *Version, c *constraint) (bool, error) {
+func constraintGreaterThan(v *Version, c *constraint, includePre bool) (bool, error) {
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
}
@@ -391,11 +404,10 @@ func constraintGreaterThan(v *Version, c *constraint) (bool, error) {
return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig)
}
-func constraintLessThan(v *Version, c *constraint) (bool, error) {
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
+func constraintLessThan(v *Version, c *constraint, includePre bool) (bool, error) {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
}
@@ -406,12 +418,11 @@ func constraintLessThan(v *Version, c *constraint) (bool, error) {
return false, fmt.Errorf("%s is greater than or equal to %s", v, c.orig)
}
-func constraintGreaterThanEqual(v *Version, c *constraint) (bool, error) {
+func constraintGreaterThanEqual(v *Version, c *constraint, includePre bool) (bool, error) {
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
}
@@ -422,11 +433,10 @@ func constraintGreaterThanEqual(v *Version, c *constraint) (bool, error) {
return false, fmt.Errorf("%s is less than %s", v, c.orig)
}
-func constraintLessThanEqual(v *Version, c *constraint) (bool, error) {
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
+func constraintLessThanEqual(v *Version, c *constraint, includePre bool) (bool, error) {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
}
@@ -455,11 +465,10 @@ func constraintLessThanEqual(v *Version, c *constraint) (bool, error) {
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0
// ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0
// ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0
-func constraintTilde(v *Version, c *constraint) (bool, error) {
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
+func constraintTilde(v *Version, c *constraint, includePre bool) (bool, error) {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
}
@@ -487,16 +496,15 @@ func constraintTilde(v *Version, c *constraint) (bool, error) {
// When there is a .x (dirty) status it automatically opts in to ~. Otherwise
// it's a straight =
-func constraintTildeOrEqual(v *Version, c *constraint) (bool, error) {
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
+func constraintTildeOrEqual(v *Version, c *constraint, includePre bool) (bool, error) {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
}
if c.dirty {
- return constraintTilde(v, c)
+ return constraintTilde(v, c, includePre)
}
eq := v.Equal(c.con)
@@ -516,11 +524,10 @@ func constraintTildeOrEqual(v *Version, c *constraint) (bool, error) {
// ^0.0.3 --> >=0.0.3 <0.0.4
// ^0.0 --> >=0.0.0 <0.1.0
// ^0 --> >=0.0.0 <1.0.0
-func constraintCaret(v *Version, c *constraint) (bool, error) {
- // If there is a pre-release on the version but the constraint isn't looking
- // for them assume that pre-releases are not compatible. See issue 21 for
- // more details.
- if v.Prerelease() != "" && c.con.Prerelease() == "" {
+func constraintCaret(v *Version, c *constraint, includePre bool) (bool, error) {
+ // The existence of prereleases is checked at the group level and passed in.
+ // Exit early if the version has a prerelease but those are to be ignored.
+ if v.Prerelease() != "" && !includePre {
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
}
diff --git a/test/tools/vendor/github.com/Masterminds/semver/v3/version.go b/test/tools/vendor/github.com/Masterminds/semver/v3/version.go
index 7c4bed3347..7a3ba73887 100644
--- a/test/tools/vendor/github.com/Masterminds/semver/v3/version.go
+++ b/test/tools/vendor/github.com/Masterminds/semver/v3/version.go
@@ -14,32 +14,52 @@ import (
// The compiled version of the regex created at init() is cached here so it
// only needs to be created once.
var versionRegex *regexp.Regexp
+var looseVersionRegex *regexp.Regexp
+
+// CoerceNewVersion sets if leading 0's are allowd in the version part. Leading 0's are
+// not allowed in a valid semantic version. When set to true, NewVersion will coerce
+// leading 0's into a valid version.
+var CoerceNewVersion = true
+
+// DetailedNewVersionErrors specifies if detailed errors are returned from the NewVersion
+// function. This is used when CoerceNewVersion is set to false. If set to false
+// ErrInvalidSemVer is returned for an invalid version. This does not apply to
+// StrictNewVersion. Setting this function to false returns errors more quickly.
+var DetailedNewVersionErrors = true
var (
// ErrInvalidSemVer is returned a version is found to be invalid when
// being parsed.
- ErrInvalidSemVer = errors.New("Invalid Semantic Version")
+ ErrInvalidSemVer = errors.New("invalid semantic version")
// ErrEmptyString is returned when an empty string is passed in for parsing.
- ErrEmptyString = errors.New("Version string empty")
+ ErrEmptyString = errors.New("version string empty")
// ErrInvalidCharacters is returned when invalid characters are found as
// part of a version
- ErrInvalidCharacters = errors.New("Invalid characters in version")
+ ErrInvalidCharacters = errors.New("invalid characters in version")
// ErrSegmentStartsZero is returned when a version segment starts with 0.
// This is invalid in SemVer.
- ErrSegmentStartsZero = errors.New("Version segment starts with 0")
+ ErrSegmentStartsZero = errors.New("version segment starts with 0")
// ErrInvalidMetadata is returned when the metadata is an invalid format
- ErrInvalidMetadata = errors.New("Invalid Metadata string")
+ ErrInvalidMetadata = errors.New("invalid metadata string")
// ErrInvalidPrerelease is returned when the pre-release is an invalid format
- ErrInvalidPrerelease = errors.New("Invalid Prerelease string")
+ ErrInvalidPrerelease = errors.New("invalid prerelease string")
)
// semVerRegex is the regular expression used to parse a semantic version.
-const semVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` +
+// This is not the official regex from the semver spec. It has been modified to allow for loose handling
+// where versions like 2.1 are detected.
+const semVerRegex string = `v?(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:\.(0|[1-9]\d*))?` +
+ `(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?` +
+ `(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?`
+
+// looseSemVerRegex is a regular expression that lets invalid semver expressions through
+// with enough detail that certain errors can be checked for.
+const looseSemVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` +
`(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
`(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?`
@@ -53,6 +73,7 @@ type Version struct {
func init() {
versionRegex = regexp.MustCompile("^" + semVerRegex + "$")
+ looseVersionRegex = regexp.MustCompile("^" + looseSemVerRegex + "$")
}
const (
@@ -83,22 +104,23 @@ func StrictNewVersion(v string) (*Version, error) {
original: v,
}
- // check for prerelease or build metadata
- var extra []string
- if strings.ContainsAny(parts[2], "-+") {
- // Start with the build metadata first as it needs to be on the right
- extra = strings.SplitN(parts[2], "+", 2)
- if len(extra) > 1 {
- // build metadata found
- sv.metadata = extra[1]
- parts[2] = extra[0]
+ // Extract build metadata
+ if strings.Contains(parts[2], "+") {
+ extra := strings.SplitN(parts[2], "+", 2)
+ sv.metadata = extra[1]
+ parts[2] = extra[0]
+ if err := validateMetadata(sv.metadata); err != nil {
+ return nil, err
}
+ }
- extra = strings.SplitN(parts[2], "-", 2)
- if len(extra) > 1 {
- // prerelease found
- sv.pre = extra[1]
- parts[2] = extra[0]
+ // Extract build prerelease
+ if strings.Contains(parts[2], "-") {
+ extra := strings.SplitN(parts[2], "-", 2)
+ sv.pre = extra[1]
+ parts[2] = extra[0]
+ if err := validatePrerelease(sv.pre); err != nil {
+ return nil, err
}
}
@@ -114,7 +136,7 @@ func StrictNewVersion(v string) (*Version, error) {
}
}
- // Extract the major, minor, and patch elements onto the returned Version
+ // Extract major, minor, and patch
var err error
sv.major, err = strconv.ParseUint(parts[0], 10, 64)
if err != nil {
@@ -131,10 +153,70 @@ func StrictNewVersion(v string) (*Version, error) {
return nil, err
}
- // No prerelease or build metadata found so returning now as a fastpath.
- if sv.pre == "" && sv.metadata == "" {
- return sv, nil
+ return sv, nil
+}
+
+// NewVersion parses a given version and returns an instance of Version or
+// an error if unable to parse the version. If the version is SemVer-ish it
+// attempts to convert it to SemVer. If you want to validate it was a strict
+// semantic version at parse time see StrictNewVersion().
+func NewVersion(v string) (*Version, error) {
+ if CoerceNewVersion {
+ return coerceNewVersion(v)
}
+ m := versionRegex.FindStringSubmatch(v)
+ if m == nil {
+
+ // Disabling detailed errors is first so that it is in the fast path.
+ if !DetailedNewVersionErrors {
+ return nil, ErrInvalidSemVer
+ }
+
+ // Check for specific errors with the semver string and return a more detailed
+ // error.
+ m = looseVersionRegex.FindStringSubmatch(v)
+ if m == nil {
+ return nil, ErrInvalidSemVer
+ }
+ err := validateVersion(m)
+ if err != nil {
+ return nil, err
+ }
+ return nil, ErrInvalidSemVer
+ }
+
+ sv := &Version{
+ metadata: m[5],
+ pre: m[4],
+ original: v,
+ }
+
+ var err error
+ sv.major, err = strconv.ParseUint(m[1], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("error parsing version segment: %w", err)
+ }
+
+ if m[2] != "" {
+ sv.minor, err = strconv.ParseUint(m[2], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("error parsing version segment: %w", err)
+ }
+ } else {
+ sv.minor = 0
+ }
+
+ if m[3] != "" {
+ sv.patch, err = strconv.ParseUint(m[3], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("error parsing version segment: %w", err)
+ }
+ } else {
+ sv.patch = 0
+ }
+
+ // Perform some basic due diligence on the extra parts to ensure they are
+ // valid.
if sv.pre != "" {
if err = validatePrerelease(sv.pre); err != nil {
@@ -151,12 +233,8 @@ func StrictNewVersion(v string) (*Version, error) {
return sv, nil
}
-// NewVersion parses a given version and returns an instance of Version or
-// an error if unable to parse the version. If the version is SemVer-ish it
-// attempts to convert it to SemVer. If you want to validate it was a strict
-// semantic version at parse time see StrictNewVersion().
-func NewVersion(v string) (*Version, error) {
- m := versionRegex.FindStringSubmatch(v)
+func coerceNewVersion(v string) (*Version, error) {
+ m := looseVersionRegex.FindStringSubmatch(v)
if m == nil {
return nil, ErrInvalidSemVer
}
@@ -170,13 +248,13 @@ func NewVersion(v string) (*Version, error) {
var err error
sv.major, err = strconv.ParseUint(m[1], 10, 64)
if err != nil {
- return nil, fmt.Errorf("Error parsing version segment: %s", err)
+ return nil, fmt.Errorf("error parsing version segment: %w", err)
}
if m[2] != "" {
sv.minor, err = strconv.ParseUint(strings.TrimPrefix(m[2], "."), 10, 64)
if err != nil {
- return nil, fmt.Errorf("Error parsing version segment: %s", err)
+ return nil, fmt.Errorf("error parsing version segment: %w", err)
}
} else {
sv.minor = 0
@@ -185,7 +263,7 @@ func NewVersion(v string) (*Version, error) {
if m[3] != "" {
sv.patch, err = strconv.ParseUint(strings.TrimPrefix(m[3], "."), 10, 64)
if err != nil {
- return nil, fmt.Errorf("Error parsing version segment: %s", err)
+ return nil, fmt.Errorf("error parsing version segment: %w", err)
}
} else {
sv.patch = 0
@@ -381,15 +459,31 @@ func (v *Version) LessThan(o *Version) bool {
return v.Compare(o) < 0
}
+// LessThanEqual tests if one version is less or equal than another one.
+func (v *Version) LessThanEqual(o *Version) bool {
+ return v.Compare(o) <= 0
+}
+
// GreaterThan tests if one version is greater than another one.
func (v *Version) GreaterThan(o *Version) bool {
return v.Compare(o) > 0
}
+// GreaterThanEqual tests if one version is greater or equal than another one.
+func (v *Version) GreaterThanEqual(o *Version) bool {
+ return v.Compare(o) >= 0
+}
+
// Equal tests if two versions are equal to each other.
// Note, versions can be equal with different metadata since metadata
// is not considered part of the comparable version.
func (v *Version) Equal(o *Version) bool {
+ if v == o {
+ return true
+ }
+ if v == nil || o == nil {
+ return false
+ }
return v.Compare(o) == 0
}
@@ -612,7 +706,9 @@ func containsOnly(s string, comp string) bool {
func validatePrerelease(p string) error {
eparts := strings.Split(p, ".")
for _, p := range eparts {
- if containsOnly(p, num) {
+ if p == "" {
+ return ErrInvalidPrerelease
+ } else if containsOnly(p, num) {
if len(p) > 1 && p[0] == '0' {
return ErrSegmentStartsZero
}
@@ -631,9 +727,62 @@ func validatePrerelease(p string) error {
func validateMetadata(m string) error {
eparts := strings.Split(m, ".")
for _, p := range eparts {
- if !containsOnly(p, allowed) {
+ if p == "" {
+ return ErrInvalidMetadata
+ } else if !containsOnly(p, allowed) {
return ErrInvalidMetadata
}
}
return nil
}
+
+// validateVersion checks for common validation issues but may not catch all errors
+func validateVersion(m []string) error {
+ var err error
+ var v string
+ if m[1] != "" {
+ if len(m[1]) > 1 && m[1][0] == '0' {
+ return ErrSegmentStartsZero
+ }
+ _, err = strconv.ParseUint(m[1], 10, 64)
+ if err != nil {
+ return fmt.Errorf("error parsing version segment: %w", err)
+ }
+ }
+
+ if m[2] != "" {
+ v = strings.TrimPrefix(m[2], ".")
+ if len(v) > 1 && v[0] == '0' {
+ return ErrSegmentStartsZero
+ }
+ _, err = strconv.ParseUint(v, 10, 64)
+ if err != nil {
+ return fmt.Errorf("error parsing version segment: %w", err)
+ }
+ }
+
+ if m[3] != "" {
+ v = strings.TrimPrefix(m[3], ".")
+ if len(v) > 1 && v[0] == '0' {
+ return ErrSegmentStartsZero
+ }
+ _, err = strconv.ParseUint(v, 10, 64)
+ if err != nil {
+ return fmt.Errorf("error parsing version segment: %w", err)
+ }
+ }
+
+ if m[5] != "" {
+ if err = validatePrerelease(m[5]); err != nil {
+ return err
+ }
+ }
+
+ if m[8] != "" {
+ if err = validateMetadata(m[8]); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
diff --git a/test/tools/vendor/github.com/Masterminds/sprig/v3/CHANGELOG.md b/test/tools/vendor/github.com/Masterminds/sprig/v3/CHANGELOG.md
index 2ce45dd4ec..b5ef766a7a 100644
--- a/test/tools/vendor/github.com/Masterminds/sprig/v3/CHANGELOG.md
+++ b/test/tools/vendor/github.com/Masterminds/sprig/v3/CHANGELOG.md
@@ -1,5 +1,23 @@
# Changelog
+## Release 3.3.0 (2024-08-29)
+
+### Added
+
+- #400: added sha512sum function (thanks @itzik-elayev)
+
+### Changed
+
+- #407: Removed duplicate documentation (functions were documentated in 2 places)
+- #290: Corrected copy/paster oops in math documentation (thanks @zzhu41)
+- #369: Corrected template reference in docs (thanks @chey)
+- #375: Added link to URL documenation (thanks @carlpett)
+- #406: Updated the mergo dependency which had a breaking change (which was accounted for)
+- #376: Fixed documentation error (thanks @jheyduk)
+- #404: Updated dependency tree
+- #391: Fixed misspelling (thanks @chrishalbert)
+- #405: Updated Go versions used in testing
+
## Release 3.2.3 (2022-11-29)
### Changed
@@ -307,7 +325,7 @@ This release adds new functions, including:
- Added `semver` and `semverCompare` for Semantic Versions
- `list` replaces `tuple`
- Fixed issue with `join`
-- Added `first`, `last`, `intial`, `rest`, `prepend`, `append`, `toString`, `toStrings`, `sortAlpha`, `reverse`, `coalesce`, `pluck`, `pick`, `compact`, `keys`, `omit`, `uniq`, `has`, `without`
+- Added `first`, `last`, `initial`, `rest`, `prepend`, `append`, `toString`, `toStrings`, `sortAlpha`, `reverse`, `coalesce`, `pluck`, `pick`, `compact`, `keys`, `omit`, `uniq`, `has`, `without`
## Release 2.9.0 (2017-02-23)
@@ -361,7 +379,7 @@ Because we switched from `int` to `int64` as the return value for all integer ma
- `min` complements `max` (formerly `biggest`)
- `empty` indicates that a value is the empty value for its type
- `tuple` creates a tuple inside of a template: `{{$t := tuple "a", "b" "c"}}`
-- `dict` creates a dictionary inside of a template `{{$d := dict "key1" "val1" "key2" "val2"}}`
+- `dict` creates a dictionary inside of a template `{{$d := dict "key1" "val1" "key2" "val2"}}`
- Date formatters have been added for HTML dates (as used in `date` input fields)
- Integer math functions can convert from a number of types, including `string` (via `strconv.ParseInt`).
diff --git a/test/tools/vendor/github.com/Masterminds/sprig/v3/crypto.go b/test/tools/vendor/github.com/Masterminds/sprig/v3/crypto.go
index 13a5cd5593..75fe027e4d 100644
--- a/test/tools/vendor/github.com/Masterminds/sprig/v3/crypto.go
+++ b/test/tools/vendor/github.com/Masterminds/sprig/v3/crypto.go
@@ -14,6 +14,7 @@ import (
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
+ "crypto/sha512"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
@@ -36,6 +37,11 @@ import (
"golang.org/x/crypto/scrypt"
)
+func sha512sum(input string) string {
+ hash := sha512.Sum512([]byte(input))
+ return hex.EncodeToString(hash[:])
+}
+
func sha256sum(input string) string {
hash := sha256.Sum256([]byte(input))
return hex.EncodeToString(hash[:])
diff --git a/test/tools/vendor/github.com/Masterminds/sprig/v3/dict.go b/test/tools/vendor/github.com/Masterminds/sprig/v3/dict.go
index ade8896984..4315b3542a 100644
--- a/test/tools/vendor/github.com/Masterminds/sprig/v3/dict.go
+++ b/test/tools/vendor/github.com/Masterminds/sprig/v3/dict.go
@@ -1,7 +1,7 @@
package sprig
import (
- "github.com/imdario/mergo"
+ "dario.cat/mergo"
"github.com/mitchellh/copystructure"
)
diff --git a/test/tools/vendor/github.com/Masterminds/sprig/v3/doc.go b/test/tools/vendor/github.com/Masterminds/sprig/v3/doc.go
index aabb9d4489..91031d6d19 100644
--- a/test/tools/vendor/github.com/Masterminds/sprig/v3/doc.go
+++ b/test/tools/vendor/github.com/Masterminds/sprig/v3/doc.go
@@ -6,7 +6,7 @@ inside of Go `html/template` and `text/template` files.
To add these functions, use the `template.Funcs()` method:
- t := templates.New("foo").Funcs(sprig.FuncMap())
+ t := template.New("foo").Funcs(sprig.FuncMap())
Note that you should add the function map before you parse any template files.
diff --git a/test/tools/vendor/github.com/Masterminds/sprig/v3/functions.go b/test/tools/vendor/github.com/Masterminds/sprig/v3/functions.go
index 57fcec1d9e..cda47d26f2 100644
--- a/test/tools/vendor/github.com/Masterminds/sprig/v3/functions.go
+++ b/test/tools/vendor/github.com/Masterminds/sprig/v3/functions.go
@@ -22,8 +22,7 @@ import (
//
// Use this to pass the functions into the template engine:
//
-// tpl := template.New("foo").Funcs(sprig.FuncMap()))
-//
+// tpl := template.New("foo").Funcs(sprig.FuncMap()))
func FuncMap() template.FuncMap {
return HtmlFuncMap()
}
@@ -142,10 +141,13 @@ var genericMap = map[string]interface{}{
"swapcase": util.SwapCase,
"shuffle": xstrings.Shuffle,
"snakecase": xstrings.ToSnakeCase,
- "camelcase": xstrings.ToCamelCase,
- "kebabcase": xstrings.ToKebabCase,
- "wrap": func(l int, s string) string { return util.Wrap(s, l) },
- "wrapWith": func(l int, sep, str string) string { return util.WrapCustom(str, l, sep, true) },
+ // camelcase used to call xstrings.ToCamelCase, but that function had a breaking change in version
+ // 1.5 that moved it from upper camel case to lower camel case. This is a breaking change for sprig.
+ // A new xstrings.ToPascalCase function was added that provided upper camel case.
+ "camelcase": xstrings.ToPascalCase,
+ "kebabcase": xstrings.ToKebabCase,
+ "wrap": func(l int, s string) string { return util.Wrap(s, l) },
+ "wrapWith": func(l int, sep, str string) string { return util.WrapCustom(str, l, sep, true) },
// Switch order so that "foobar" | contains "foo"
"contains": func(substr string, str string) bool { return strings.Contains(str, substr) },
"hasPrefix": func(substr string, str string) bool { return strings.HasPrefix(str, substr) },
@@ -159,6 +161,7 @@ var genericMap = map[string]interface{}{
"plural": plural,
"sha1sum": sha1sum,
"sha256sum": sha256sum,
+ "sha512sum": sha512sum,
"adler32sum": adler32sum,
"toString": strval,
@@ -336,20 +339,20 @@ var genericMap = map[string]interface{}{
"mustChunk": mustChunk,
// Crypto:
- "bcrypt": bcrypt,
- "htpasswd": htpasswd,
- "genPrivateKey": generatePrivateKey,
- "derivePassword": derivePassword,
- "buildCustomCert": buildCustomCertificate,
- "genCA": generateCertificateAuthority,
- "genCAWithKey": generateCertificateAuthorityWithPEMKey,
- "genSelfSignedCert": generateSelfSignedCertificate,
+ "bcrypt": bcrypt,
+ "htpasswd": htpasswd,
+ "genPrivateKey": generatePrivateKey,
+ "derivePassword": derivePassword,
+ "buildCustomCert": buildCustomCertificate,
+ "genCA": generateCertificateAuthority,
+ "genCAWithKey": generateCertificateAuthorityWithPEMKey,
+ "genSelfSignedCert": generateSelfSignedCertificate,
"genSelfSignedCertWithKey": generateSelfSignedCertificateWithPEMKey,
- "genSignedCert": generateSignedCertificate,
- "genSignedCertWithKey": generateSignedCertificateWithPEMKey,
- "encryptAES": encryptAES,
- "decryptAES": decryptAES,
- "randBytes": randBytes,
+ "genSignedCert": generateSignedCertificate,
+ "genSignedCertWithKey": generateSignedCertificateWithPEMKey,
+ "encryptAES": encryptAES,
+ "decryptAES": decryptAES,
+ "randBytes": randBytes,
// UUIDs:
"uuidv4": uuidv4,
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/.gitignore b/test/tools/vendor/github.com/asaskevich/govalidator/.gitignore
deleted file mode 100644
index 8d69a9418a..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/.gitignore
+++ /dev/null
@@ -1,15 +0,0 @@
-bin/
-.idea/
-# Binaries for programs and plugins
-*.exe
-*.exe~
-*.dll
-*.so
-*.dylib
-
-# Test binary, built with `go test -c`
-*.test
-
-# Output of the go coverage tool, specifically when used with LiteIDE
-*.out
-
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/.travis.yml b/test/tools/vendor/github.com/asaskevich/govalidator/.travis.yml
deleted file mode 100644
index bb83c6670d..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/.travis.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-language: go
-dist: xenial
-go:
- - '1.10'
- - '1.11'
- - '1.12'
- - '1.13'
- - 'tip'
-
-script:
- - go test -coverpkg=./... -coverprofile=coverage.info -timeout=5s
- - bash <(curl -s https://codecov.io/bash)
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md
deleted file mode 100644
index 4b462b0d81..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# Contributor Code of Conduct
-
-This project adheres to [The Code Manifesto](http://codemanifesto.com)
-as its guidelines for contributor interactions.
-
-## The Code Manifesto
-
-We want to work in an ecosystem that empowers developers to reach their
-potential — one that encourages growth and effective collaboration. A space
-that is safe for all.
-
-A space such as this benefits everyone that participates in it. It encourages
-new developers to enter our field. It is through discussion and collaboration
-that we grow, and through growth that we improve.
-
-In the effort to create such a place, we hold to these values:
-
-1. **Discrimination limits us.** This includes discrimination on the basis of
- race, gender, sexual orientation, gender identity, age, nationality,
- technology and any other arbitrary exclusion of a group of people.
-2. **Boundaries honor us.** Your comfort levels are not everyone’s comfort
- levels. Remember that, and if brought to your attention, heed it.
-3. **We are our biggest assets.** None of us were born masters of our trade.
- Each of us has been helped along the way. Return that favor, when and where
- you can.
-4. **We are resources for the future.** As an extension of #3, share what you
- know. Make yourself a resource to help those that come after you.
-5. **Respect defines us.** Treat others as you wish to be treated. Make your
- discussions, criticisms and debates from a position of respectfulness. Ask
- yourself, is it true? Is it necessary? Is it constructive? Anything less is
- unacceptable.
-6. **Reactions require grace.** Angry responses are valid, but abusive language
- and vindictive actions are toxic. When something happens that offends you,
- handle it assertively, but be respectful. Escalate reasonably, and try to
- allow the offender an opportunity to explain themselves, and possibly
- correct the issue.
-7. **Opinions are just that: opinions.** Each and every one of us, due to our
- background and upbringing, have varying opinions. That is perfectly
- acceptable. Remember this: if you respect your own opinions, you should
- respect the opinions of others.
-8. **To err is human.** You might not intend it, but mistakes do happen and
- contribute to build experience. Tolerate honest mistakes, and don't
- hesitate to apologize if you make one yourself.
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md b/test/tools/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md
deleted file mode 100644
index 7ed268a1ed..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md
+++ /dev/null
@@ -1,63 +0,0 @@
-#### Support
-If you do have a contribution to the package, feel free to create a Pull Request or an Issue.
-
-#### What to contribute
-If you don't know what to do, there are some features and functions that need to be done
-
-- [ ] Refactor code
-- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check
-- [ ] Create actual list of contributors and projects that currently using this package
-- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues)
-- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions)
-- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new
-- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc
-- [x] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224)
-- [ ] Implement fuzzing testing
-- [ ] Implement some struct/map/array utilities
-- [ ] Implement map/array validation
-- [ ] Implement benchmarking
-- [ ] Implement batch of examples
-- [ ] Look at forks for new features and fixes
-
-#### Advice
-Feel free to create what you want, but keep in mind when you implement new features:
-- Code must be clear and readable, names of variables/constants clearly describes what they are doing
-- Public functions must be documented and described in source file and added to README.md to the list of available functions
-- There are must be unit-tests for any new functions and improvements
-
-## Financial contributions
-
-We also welcome financial contributions in full transparency on our [open collective](https://opencollective.com/govalidator).
-Anyone can file an expense. If the expense makes sense for the development of the community, it will be "merged" in the ledger of our open collective by the core contributors and the person who filed the expense will be reimbursed.
-
-
-## Credits
-
-
-### Contributors
-
-Thank you to all the people who have already contributed to govalidator!
-
-
-
-### Backers
-
-Thank you to all our backers! [[Become a backer](https://opencollective.com/govalidator#backer)]
-
-
-
-
-### Sponsors
-
-Thank you to all our sponsors! (please ask your company to also support this open source project by [becoming a sponsor](https://opencollective.com/govalidator#sponsor))
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/LICENSE b/test/tools/vendor/github.com/asaskevich/govalidator/LICENSE
deleted file mode 100644
index cacba91024..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014-2020 Alex Saskevich
-
-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.
\ No newline at end of file
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/README.md b/test/tools/vendor/github.com/asaskevich/govalidator/README.md
deleted file mode 100644
index 2c3fc35eb6..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/README.md
+++ /dev/null
@@ -1,622 +0,0 @@
-govalidator
-===========
-[](https://gitter.im/asaskevich/govalidator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [](https://godoc.org/github.com/asaskevich/govalidator)
-[](https://travis-ci.org/asaskevich/govalidator)
-[](https://codecov.io/gh/asaskevich/govalidator) [](https://goreportcard.com/report/github.com/asaskevich/govalidator) [](http://go-search.org/view?id=github.com%2Fasaskevich%2Fgovalidator) [](#backers) [](#sponsors) [](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_shield)
-
-A package of validators and sanitizers for strings, structs and collections. Based on [validator.js](https://github.com/chriso/validator.js).
-
-#### Installation
-Make sure that Go is installed on your computer.
-Type the following command in your terminal:
-
- go get github.com/asaskevich/govalidator
-
-or you can get specified release of the package with `gopkg.in`:
-
- go get gopkg.in/asaskevich/govalidator.v10
-
-After it the package is ready to use.
-
-
-#### Import package in your project
-Add following line in your `*.go` file:
-```go
-import "github.com/asaskevich/govalidator"
-```
-If you are unhappy to use long `govalidator`, you can do something like this:
-```go
-import (
- valid "github.com/asaskevich/govalidator"
-)
-```
-
-#### Activate behavior to require all fields have a validation tag by default
-`SetFieldsRequiredByDefault` causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). A good place to activate this is a package init function or the main() function.
-
-`SetNilPtrAllowedByRequired` causes validation to pass when struct fields marked by `required` are set to nil. This is disabled by default for consistency, but some packages that need to be able to determine between `nil` and `zero value` state can use this. If disabled, both `nil` and `zero` values cause validation errors.
-
-```go
-import "github.com/asaskevich/govalidator"
-
-func init() {
- govalidator.SetFieldsRequiredByDefault(true)
-}
-```
-
-Here's some code to explain it:
-```go
-// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
-type exampleStruct struct {
- Name string ``
- Email string `valid:"email"`
-}
-
-// this, however, will only fail when Email is empty or an invalid email address:
-type exampleStruct2 struct {
- Name string `valid:"-"`
- Email string `valid:"email"`
-}
-
-// lastly, this will only fail when Email is an invalid email address but not when it's empty:
-type exampleStruct2 struct {
- Name string `valid:"-"`
- Email string `valid:"email,optional"`
-}
-```
-
-#### Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123))
-##### Custom validator function signature
-A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible.
-```go
-import "github.com/asaskevich/govalidator"
-
-// old signature
-func(i interface{}) bool
-
-// new signature
-func(i interface{}, o interface{}) bool
-```
-
-##### Adding a custom validator
-This was changed to prevent data races when accessing custom validators.
-```go
-import "github.com/asaskevich/govalidator"
-
-// before
-govalidator.CustomTypeTagMap["customByteArrayValidator"] = func(i interface{}, o interface{}) bool {
- // ...
-}
-
-// after
-govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, o interface{}) bool {
- // ...
-})
-```
-
-#### List of functions:
-```go
-func Abs(value float64) float64
-func BlackList(str, chars string) string
-func ByteLength(str string, params ...string) bool
-func CamelCaseToUnderscore(str string) string
-func Contains(str, substring string) bool
-func Count(array []interface{}, iterator ConditionIterator) int
-func Each(array []interface{}, iterator Iterator)
-func ErrorByField(e error, field string) string
-func ErrorsByField(e error) map[string]string
-func Filter(array []interface{}, iterator ConditionIterator) []interface{}
-func Find(array []interface{}, iterator ConditionIterator) interface{}
-func GetLine(s string, index int) (string, error)
-func GetLines(s string) []string
-func HasLowerCase(str string) bool
-func HasUpperCase(str string) bool
-func HasWhitespace(str string) bool
-func HasWhitespaceOnly(str string) bool
-func InRange(value interface{}, left interface{}, right interface{}) bool
-func InRangeFloat32(value, left, right float32) bool
-func InRangeFloat64(value, left, right float64) bool
-func InRangeInt(value, left, right interface{}) bool
-func IsASCII(str string) bool
-func IsAlpha(str string) bool
-func IsAlphanumeric(str string) bool
-func IsBase64(str string) bool
-func IsByteLength(str string, min, max int) bool
-func IsCIDR(str string) bool
-func IsCRC32(str string) bool
-func IsCRC32b(str string) bool
-func IsCreditCard(str string) bool
-func IsDNSName(str string) bool
-func IsDataURI(str string) bool
-func IsDialString(str string) bool
-func IsDivisibleBy(str, num string) bool
-func IsEmail(str string) bool
-func IsExistingEmail(email string) bool
-func IsFilePath(str string) (bool, int)
-func IsFloat(str string) bool
-func IsFullWidth(str string) bool
-func IsHalfWidth(str string) bool
-func IsHash(str string, algorithm string) bool
-func IsHexadecimal(str string) bool
-func IsHexcolor(str string) bool
-func IsHost(str string) bool
-func IsIP(str string) bool
-func IsIPv4(str string) bool
-func IsIPv6(str string) bool
-func IsISBN(str string, version int) bool
-func IsISBN10(str string) bool
-func IsISBN13(str string) bool
-func IsISO3166Alpha2(str string) bool
-func IsISO3166Alpha3(str string) bool
-func IsISO4217(str string) bool
-func IsISO693Alpha2(str string) bool
-func IsISO693Alpha3b(str string) bool
-func IsIn(str string, params ...string) bool
-func IsInRaw(str string, params ...string) bool
-func IsInt(str string) bool
-func IsJSON(str string) bool
-func IsLatitude(str string) bool
-func IsLongitude(str string) bool
-func IsLowerCase(str string) bool
-func IsMAC(str string) bool
-func IsMD4(str string) bool
-func IsMD5(str string) bool
-func IsMagnetURI(str string) bool
-func IsMongoID(str string) bool
-func IsMultibyte(str string) bool
-func IsNatural(value float64) bool
-func IsNegative(value float64) bool
-func IsNonNegative(value float64) bool
-func IsNonPositive(value float64) bool
-func IsNotNull(str string) bool
-func IsNull(str string) bool
-func IsNumeric(str string) bool
-func IsPort(str string) bool
-func IsPositive(value float64) bool
-func IsPrintableASCII(str string) bool
-func IsRFC3339(str string) bool
-func IsRFC3339WithoutZone(str string) bool
-func IsRGBcolor(str string) bool
-func IsRegex(str string) bool
-func IsRequestURI(rawurl string) bool
-func IsRequestURL(rawurl string) bool
-func IsRipeMD128(str string) bool
-func IsRipeMD160(str string) bool
-func IsRsaPub(str string, params ...string) bool
-func IsRsaPublicKey(str string, keylen int) bool
-func IsSHA1(str string) bool
-func IsSHA256(str string) bool
-func IsSHA384(str string) bool
-func IsSHA512(str string) bool
-func IsSSN(str string) bool
-func IsSemver(str string) bool
-func IsTiger128(str string) bool
-func IsTiger160(str string) bool
-func IsTiger192(str string) bool
-func IsTime(str string, format string) bool
-func IsType(v interface{}, params ...string) bool
-func IsURL(str string) bool
-func IsUTFDigit(str string) bool
-func IsUTFLetter(str string) bool
-func IsUTFLetterNumeric(str string) bool
-func IsUTFNumeric(str string) bool
-func IsUUID(str string) bool
-func IsUUIDv3(str string) bool
-func IsUUIDv4(str string) bool
-func IsUUIDv5(str string) bool
-func IsULID(str string) bool
-func IsUnixTime(str string) bool
-func IsUpperCase(str string) bool
-func IsVariableWidth(str string) bool
-func IsWhole(value float64) bool
-func LeftTrim(str, chars string) string
-func Map(array []interface{}, iterator ResultIterator) []interface{}
-func Matches(str, pattern string) bool
-func MaxStringLength(str string, params ...string) bool
-func MinStringLength(str string, params ...string) bool
-func NormalizeEmail(str string) (string, error)
-func PadBoth(str string, padStr string, padLen int) string
-func PadLeft(str string, padStr string, padLen int) string
-func PadRight(str string, padStr string, padLen int) string
-func PrependPathToErrors(err error, path string) error
-func Range(str string, params ...string) bool
-func RemoveTags(s string) string
-func ReplacePattern(str, pattern, replace string) string
-func Reverse(s string) string
-func RightTrim(str, chars string) string
-func RuneLength(str string, params ...string) bool
-func SafeFileName(str string) string
-func SetFieldsRequiredByDefault(value bool)
-func SetNilPtrAllowedByRequired(value bool)
-func Sign(value float64) float64
-func StringLength(str string, params ...string) bool
-func StringMatches(s string, params ...string) bool
-func StripLow(str string, keepNewLines bool) string
-func ToBoolean(str string) (bool, error)
-func ToFloat(str string) (float64, error)
-func ToInt(value interface{}) (res int64, err error)
-func ToJSON(obj interface{}) (string, error)
-func ToString(obj interface{}) string
-func Trim(str, chars string) string
-func Truncate(str string, length int, ending string) string
-func TruncatingErrorf(str string, args ...interface{}) error
-func UnderscoreToCamelCase(s string) string
-func ValidateMap(inputMap map[string]interface{}, validationMap map[string]interface{}) (bool, error)
-func ValidateStruct(s interface{}) (bool, error)
-func WhiteList(str, chars string) string
-type ConditionIterator
-type CustomTypeValidator
-type Error
-func (e Error) Error() string
-type Errors
-func (es Errors) Error() string
-func (es Errors) Errors() []error
-type ISO3166Entry
-type ISO693Entry
-type InterfaceParamValidator
-type Iterator
-type ParamValidator
-type ResultIterator
-type UnsupportedTypeError
-func (e *UnsupportedTypeError) Error() string
-type Validator
-```
-
-#### Examples
-###### IsURL
-```go
-println(govalidator.IsURL(`http://user@pass:domain.com/path/page`))
-```
-###### IsType
-```go
-println(govalidator.IsType("Bob", "string"))
-println(govalidator.IsType(1, "int"))
-i := 1
-println(govalidator.IsType(&i, "*int"))
-```
-
-IsType can be used through the tag `type` which is essential for map validation:
-```go
-type User struct {
- Name string `valid:"type(string)"`
- Age int `valid:"type(int)"`
- Meta interface{} `valid:"type(string)"`
-}
-result, err := govalidator.ValidateStruct(User{"Bob", 20, "meta"})
-if err != nil {
- println("error: " + err.Error())
-}
-println(result)
-```
-###### ToString
-```go
-type User struct {
- FirstName string
- LastName string
-}
-
-str := govalidator.ToString(&User{"John", "Juan"})
-println(str)
-```
-###### Each, Map, Filter, Count for slices
-Each iterates over the slice/array and calls Iterator for every item
-```go
-data := []interface{}{1, 2, 3, 4, 5}
-var fn govalidator.Iterator = func(value interface{}, index int) {
- println(value.(int))
-}
-govalidator.Each(data, fn)
-```
-```go
-data := []interface{}{1, 2, 3, 4, 5}
-var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} {
- return value.(int) * 3
-}
-_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
-```
-```go
-data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
-var fn govalidator.ConditionIterator = func(value interface{}, index int) bool {
- return value.(int)%2 == 0
-}
-_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
-_ = govalidator.Count(data, fn) // result = 5
-```
-###### ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2)
-If you want to validate structs, you can use tag `valid` for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place `-` in your tag. If you need a validator that is not on the list below, you can add it like this:
-```go
-govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
- return str == "duck"
-})
-```
-For completely custom validators (interface-based), see below.
-
-Here is a list of available validators for struct fields (validator - used function):
-```go
-"email": IsEmail,
-"url": IsURL,
-"dialstring": IsDialString,
-"requrl": IsRequestURL,
-"requri": IsRequestURI,
-"alpha": IsAlpha,
-"utfletter": IsUTFLetter,
-"alphanum": IsAlphanumeric,
-"utfletternum": IsUTFLetterNumeric,
-"numeric": IsNumeric,
-"utfnumeric": IsUTFNumeric,
-"utfdigit": IsUTFDigit,
-"hexadecimal": IsHexadecimal,
-"hexcolor": IsHexcolor,
-"rgbcolor": IsRGBcolor,
-"lowercase": IsLowerCase,
-"uppercase": IsUpperCase,
-"int": IsInt,
-"float": IsFloat,
-"null": IsNull,
-"uuid": IsUUID,
-"uuidv3": IsUUIDv3,
-"uuidv4": IsUUIDv4,
-"uuidv5": IsUUIDv5,
-"creditcard": IsCreditCard,
-"isbn10": IsISBN10,
-"isbn13": IsISBN13,
-"json": IsJSON,
-"multibyte": IsMultibyte,
-"ascii": IsASCII,
-"printableascii": IsPrintableASCII,
-"fullwidth": IsFullWidth,
-"halfwidth": IsHalfWidth,
-"variablewidth": IsVariableWidth,
-"base64": IsBase64,
-"datauri": IsDataURI,
-"ip": IsIP,
-"port": IsPort,
-"ipv4": IsIPv4,
-"ipv6": IsIPv6,
-"dns": IsDNSName,
-"host": IsHost,
-"mac": IsMAC,
-"latitude": IsLatitude,
-"longitude": IsLongitude,
-"ssn": IsSSN,
-"semver": IsSemver,
-"rfc3339": IsRFC3339,
-"rfc3339WithoutZone": IsRFC3339WithoutZone,
-"ISO3166Alpha2": IsISO3166Alpha2,
-"ISO3166Alpha3": IsISO3166Alpha3,
-"ulid": IsULID,
-```
-Validators with parameters
-
-```go
-"range(min|max)": Range,
-"length(min|max)": ByteLength,
-"runelength(min|max)": RuneLength,
-"stringlength(min|max)": StringLength,
-"matches(pattern)": StringMatches,
-"in(string1|string2|...|stringN)": IsIn,
-"rsapub(keylength)" : IsRsaPub,
-"minstringlength(int): MinStringLength,
-"maxstringlength(int): MaxStringLength,
-```
-Validators with parameters for any type
-
-```go
-"type(type)": IsType,
-```
-
-And here is small example of usage:
-```go
-type Post struct {
- Title string `valid:"alphanum,required"`
- Message string `valid:"duck,ascii"`
- Message2 string `valid:"animal(dog)"`
- AuthorIP string `valid:"ipv4"`
- Date string `valid:"-"`
-}
-post := &Post{
- Title: "My Example Post",
- Message: "duck",
- Message2: "dog",
- AuthorIP: "123.234.54.3",
-}
-
-// Add your own struct validation tags
-govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
- return str == "duck"
-})
-
-// Add your own struct validation tags with parameter
-govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool {
- species := params[0]
- return str == species
-})
-govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$")
-
-result, err := govalidator.ValidateStruct(post)
-if err != nil {
- println("error: " + err.Error())
-}
-println(result)
-```
-###### ValidateMap [#2](https://github.com/asaskevich/govalidator/pull/338)
-If you want to validate maps, you can use the map to be validated and a validation map that contain the same tags used in ValidateStruct, both maps have to be in the form `map[string]interface{}`
-
-So here is small example of usage:
-```go
-var mapTemplate = map[string]interface{}{
- "name":"required,alpha",
- "family":"required,alpha",
- "email":"required,email",
- "cell-phone":"numeric",
- "address":map[string]interface{}{
- "line1":"required,alphanum",
- "line2":"alphanum",
- "postal-code":"numeric",
- },
-}
-
-var inputMap = map[string]interface{}{
- "name":"Bob",
- "family":"Smith",
- "email":"foo@bar.baz",
- "address":map[string]interface{}{
- "line1":"",
- "line2":"",
- "postal-code":"",
- },
-}
-
-result, err := govalidator.ValidateMap(inputMap, mapTemplate)
-if err != nil {
- println("error: " + err.Error())
-}
-println(result)
-```
-
-###### WhiteList
-```go
-// Remove all characters from string ignoring characters between "a" and "z"
-println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
-```
-
-###### Custom validation functions
-Custom validation using your own domain specific validators is also available - here's an example of how to use it:
-```go
-import "github.com/asaskevich/govalidator"
-
-type CustomByteArray [6]byte // custom types are supported and can be validated
-
-type StructWithCustomByteArray struct {
- ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence
- Email string `valid:"email"`
- CustomMinLength int `valid:"-"`
-}
-
-govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, context interface{}) bool {
- switch v := context.(type) { // you can type switch on the context interface being validated
- case StructWithCustomByteArray:
- // you can check and validate against some other field in the context,
- // return early or not validate against the context at all – your choice
- case SomeOtherType:
- // ...
- default:
- // expecting some other type? Throw/panic here or continue
- }
-
- switch v := i.(type) { // type switch on the struct field being validated
- case CustomByteArray:
- for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes
- if e != 0 {
- return true
- }
- }
- }
- return false
-})
-govalidator.CustomTypeTagMap.Set("customMinLengthValidator", func(i interface{}, context interface{}) bool {
- switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation
- case StructWithCustomByteArray:
- return len(v.ID) >= v.CustomMinLength
- }
- return false
-})
-```
-
-###### Loop over Error()
-By default .Error() returns all errors in a single String. To access each error you can do this:
-```go
- if err != nil {
- errs := err.(govalidator.Errors).Errors()
- for _, e := range errs {
- fmt.Println(e.Error())
- }
- }
-```
-
-###### Custom error messages
-Custom error messages are supported via annotations by adding the `~` separator - here's an example of how to use it:
-```go
-type Ticket struct {
- Id int64 `json:"id"`
- FirstName string `json:"firstname" valid:"required~First name is blank"`
-}
-```
-
-#### Notes
-Documentation is available here: [godoc.org](https://godoc.org/github.com/asaskevich/govalidator).
-Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/asaskevich/govalidator).
-
-#### Support
-If you do have a contribution to the package, feel free to create a Pull Request or an Issue.
-
-#### What to contribute
-If you don't know what to do, there are some features and functions that need to be done
-
-- [ ] Refactor code
-- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check
-- [ ] Create actual list of contributors and projects that currently using this package
-- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues)
-- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions)
-- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new
-- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc
-- [x] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224)
-- [ ] Implement fuzzing testing
-- [ ] Implement some struct/map/array utilities
-- [ ] Implement map/array validation
-- [ ] Implement benchmarking
-- [ ] Implement batch of examples
-- [ ] Look at forks for new features and fixes
-
-#### Advice
-Feel free to create what you want, but keep in mind when you implement new features:
-- Code must be clear and readable, names of variables/constants clearly describes what they are doing
-- Public functions must be documented and described in source file and added to README.md to the list of available functions
-- There are must be unit-tests for any new functions and improvements
-
-## Credits
-### Contributors
-
-This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
-
-#### Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors)
-* [Daniel Lohse](https://github.com/annismckenzie)
-* [Attila Oláh](https://github.com/attilaolah)
-* [Daniel Korner](https://github.com/Dadie)
-* [Steven Wilkin](https://github.com/stevenwilkin)
-* [Deiwin Sarjas](https://github.com/deiwin)
-* [Noah Shibley](https://github.com/slugmobile)
-* [Nathan Davies](https://github.com/nathj07)
-* [Matt Sanford](https://github.com/mzsanford)
-* [Simon ccl1115](https://github.com/ccl1115)
-
-
-
-
-### Backers
-
-Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/govalidator#backer)]
-
-
-
-
-### Sponsors
-
-Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/govalidator#sponsor)]
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-## License
-[](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_large)
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/arrays.go b/test/tools/vendor/github.com/asaskevich/govalidator/arrays.go
deleted file mode 100644
index 3e1da7cb48..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/arrays.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package govalidator
-
-// Iterator is the function that accepts element of slice/array and its index
-type Iterator func(interface{}, int)
-
-// ResultIterator is the function that accepts element of slice/array and its index and returns any result
-type ResultIterator func(interface{}, int) interface{}
-
-// ConditionIterator is the function that accepts element of slice/array and its index and returns boolean
-type ConditionIterator func(interface{}, int) bool
-
-// ReduceIterator is the function that accepts two element of slice/array and returns result of merging those values
-type ReduceIterator func(interface{}, interface{}) interface{}
-
-// Some validates that any item of array corresponds to ConditionIterator. Returns boolean.
-func Some(array []interface{}, iterator ConditionIterator) bool {
- res := false
- for index, data := range array {
- res = res || iterator(data, index)
- }
- return res
-}
-
-// Every validates that every item of array corresponds to ConditionIterator. Returns boolean.
-func Every(array []interface{}, iterator ConditionIterator) bool {
- res := true
- for index, data := range array {
- res = res && iterator(data, index)
- }
- return res
-}
-
-// Reduce boils down a list of values into a single value by ReduceIterator
-func Reduce(array []interface{}, iterator ReduceIterator, initialValue interface{}) interface{} {
- for _, data := range array {
- initialValue = iterator(initialValue, data)
- }
- return initialValue
-}
-
-// Each iterates over the slice and apply Iterator to every item
-func Each(array []interface{}, iterator Iterator) {
- for index, data := range array {
- iterator(data, index)
- }
-}
-
-// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.
-func Map(array []interface{}, iterator ResultIterator) []interface{} {
- var result = make([]interface{}, len(array))
- for index, data := range array {
- result[index] = iterator(data, index)
- }
- return result
-}
-
-// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.
-func Find(array []interface{}, iterator ConditionIterator) interface{} {
- for index, data := range array {
- if iterator(data, index) {
- return data
- }
- }
- return nil
-}
-
-// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
-func Filter(array []interface{}, iterator ConditionIterator) []interface{} {
- var result = make([]interface{}, 0)
- for index, data := range array {
- if iterator(data, index) {
- result = append(result, data)
- }
- }
- return result
-}
-
-// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.
-func Count(array []interface{}, iterator ConditionIterator) int {
- count := 0
- for index, data := range array {
- if iterator(data, index) {
- count = count + 1
- }
- }
- return count
-}
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/converter.go b/test/tools/vendor/github.com/asaskevich/govalidator/converter.go
deleted file mode 100644
index d68e990fc2..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/converter.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package govalidator
-
-import (
- "encoding/json"
- "fmt"
- "reflect"
- "strconv"
-)
-
-// ToString convert the input to a string.
-func ToString(obj interface{}) string {
- res := fmt.Sprintf("%v", obj)
- return res
-}
-
-// ToJSON convert the input to a valid JSON string
-func ToJSON(obj interface{}) (string, error) {
- res, err := json.Marshal(obj)
- if err != nil {
- res = []byte("")
- }
- return string(res), err
-}
-
-// ToFloat convert the input string to a float, or 0.0 if the input is not a float.
-func ToFloat(value interface{}) (res float64, err error) {
- val := reflect.ValueOf(value)
-
- switch value.(type) {
- case int, int8, int16, int32, int64:
- res = float64(val.Int())
- case uint, uint8, uint16, uint32, uint64:
- res = float64(val.Uint())
- case float32, float64:
- res = val.Float()
- case string:
- res, err = strconv.ParseFloat(val.String(), 64)
- if err != nil {
- res = 0
- }
- default:
- err = fmt.Errorf("ToInt: unknown interface type %T", value)
- res = 0
- }
-
- return
-}
-
-// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
-func ToInt(value interface{}) (res int64, err error) {
- val := reflect.ValueOf(value)
-
- switch value.(type) {
- case int, int8, int16, int32, int64:
- res = val.Int()
- case uint, uint8, uint16, uint32, uint64:
- res = int64(val.Uint())
- case float32, float64:
- res = int64(val.Float())
- case string:
- if IsInt(val.String()) {
- res, err = strconv.ParseInt(val.String(), 0, 64)
- if err != nil {
- res = 0
- }
- } else {
- err = fmt.Errorf("ToInt: invalid numeric format %g", value)
- res = 0
- }
- default:
- err = fmt.Errorf("ToInt: unknown interface type %T", value)
- res = 0
- }
-
- return
-}
-
-// ToBoolean convert the input string to a boolean.
-func ToBoolean(str string) (bool, error) {
- return strconv.ParseBool(str)
-}
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/doc.go b/test/tools/vendor/github.com/asaskevich/govalidator/doc.go
deleted file mode 100644
index 55dce62dc8..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/doc.go
+++ /dev/null
@@ -1,3 +0,0 @@
-package govalidator
-
-// A package of validators and sanitizers for strings, structures and collections.
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/error.go b/test/tools/vendor/github.com/asaskevich/govalidator/error.go
deleted file mode 100644
index 1da2336f47..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/error.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package govalidator
-
-import (
- "sort"
- "strings"
-)
-
-// Errors is an array of multiple errors and conforms to the error interface.
-type Errors []error
-
-// Errors returns itself.
-func (es Errors) Errors() []error {
- return es
-}
-
-func (es Errors) Error() string {
- var errs []string
- for _, e := range es {
- errs = append(errs, e.Error())
- }
- sort.Strings(errs)
- return strings.Join(errs, ";")
-}
-
-// Error encapsulates a name, an error and whether there's a custom error message or not.
-type Error struct {
- Name string
- Err error
- CustomErrorMessageExists bool
-
- // Validator indicates the name of the validator that failed
- Validator string
- Path []string
-}
-
-func (e Error) Error() string {
- if e.CustomErrorMessageExists {
- return e.Err.Error()
- }
-
- errName := e.Name
- if len(e.Path) > 0 {
- errName = strings.Join(append(e.Path, e.Name), ".")
- }
-
- return errName + ": " + e.Err.Error()
-}
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/numerics.go b/test/tools/vendor/github.com/asaskevich/govalidator/numerics.go
deleted file mode 100644
index 5041d9e868..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/numerics.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package govalidator
-
-import (
- "math"
-)
-
-// Abs returns absolute value of number
-func Abs(value float64) float64 {
- return math.Abs(value)
-}
-
-// Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise
-func Sign(value float64) float64 {
- if value > 0 {
- return 1
- } else if value < 0 {
- return -1
- } else {
- return 0
- }
-}
-
-// IsNegative returns true if value < 0
-func IsNegative(value float64) bool {
- return value < 0
-}
-
-// IsPositive returns true if value > 0
-func IsPositive(value float64) bool {
- return value > 0
-}
-
-// IsNonNegative returns true if value >= 0
-func IsNonNegative(value float64) bool {
- return value >= 0
-}
-
-// IsNonPositive returns true if value <= 0
-func IsNonPositive(value float64) bool {
- return value <= 0
-}
-
-// InRangeInt returns true if value lies between left and right border
-func InRangeInt(value, left, right interface{}) bool {
- value64, _ := ToInt(value)
- left64, _ := ToInt(left)
- right64, _ := ToInt(right)
- if left64 > right64 {
- left64, right64 = right64, left64
- }
- return value64 >= left64 && value64 <= right64
-}
-
-// InRangeFloat32 returns true if value lies between left and right border
-func InRangeFloat32(value, left, right float32) bool {
- if left > right {
- left, right = right, left
- }
- return value >= left && value <= right
-}
-
-// InRangeFloat64 returns true if value lies between left and right border
-func InRangeFloat64(value, left, right float64) bool {
- if left > right {
- left, right = right, left
- }
- return value >= left && value <= right
-}
-
-// InRange returns true if value lies between left and right border, generic type to handle int, float32, float64 and string.
-// All types must the same type.
-// False if value doesn't lie in range or if it incompatible or not comparable
-func InRange(value interface{}, left interface{}, right interface{}) bool {
- switch value.(type) {
- case int:
- intValue, _ := ToInt(value)
- intLeft, _ := ToInt(left)
- intRight, _ := ToInt(right)
- return InRangeInt(intValue, intLeft, intRight)
- case float32, float64:
- intValue, _ := ToFloat(value)
- intLeft, _ := ToFloat(left)
- intRight, _ := ToFloat(right)
- return InRangeFloat64(intValue, intLeft, intRight)
- case string:
- return value.(string) >= left.(string) && value.(string) <= right.(string)
- default:
- return false
- }
-}
-
-// IsWhole returns true if value is whole number
-func IsWhole(value float64) bool {
- return math.Remainder(value, 1) == 0
-}
-
-// IsNatural returns true if value is natural number (positive and whole)
-func IsNatural(value float64) bool {
- return IsWhole(value) && IsPositive(value)
-}
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/patterns.go b/test/tools/vendor/github.com/asaskevich/govalidator/patterns.go
deleted file mode 100644
index bafc3765ea..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/patterns.go
+++ /dev/null
@@ -1,113 +0,0 @@
-package govalidator
-
-import "regexp"
-
-// Basic regular expressions for validating strings
-const (
- Email string = "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$"
- CreditCard 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})$"
- ISBN10 string = "^(?:[0-9]{9}X|[0-9]{10})$"
- ISBN13 string = "^(?:[0-9]{13})$"
- UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
- UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
- UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
- UUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
- Alpha string = "^[a-zA-Z]+$"
- Alphanumeric string = "^[a-zA-Z0-9]+$"
- Numeric string = "^[0-9]+$"
- Int string = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
- Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
- Hexadecimal string = "^[0-9a-fA-F]+$"
- Hexcolor string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
- RGBcolor 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*\\)$"
- ASCII string = "^[\x00-\x7F]+$"
- Multibyte string = "[^\x00-\x7F]"
- FullWidth string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
- HalfWidth string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
- Base64 string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
- PrintableASCII string = "^[\x20-\x7E]+$"
- DataURI string = "^data:.+\\/(.+);base64$"
- MagnetURI string = "^magnet:\\?xt=urn:[a-zA-Z0-9]+:[a-zA-Z0-9]{32,40}&dn=.+&tr=.+$"
- Latitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
- Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
- DNSName string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`
- IP string = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))`
- URLSchema string = `((ftp|tcp|udp|wss?|https?):\/\/)`
- URLUsername string = `(\S+(:\S*)?@)`
- URLPath string = `((\/|\?|#)[^\s]*)`
- URLPort string = `(:(\d{1,5}))`
- URLIP string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3]|24\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-5]))`
- URLSubdomain string = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))`
- URL = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$`
- SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$`
- WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
- UnixPath string = `^(/[^/\x00]*)+/?$`
- WinARPath string = `^(?:(?:[a-zA-Z]:|\\\\[a-z0-9_.$●-]+\\[a-z0-9_.$●-]+)\\|\\?[^\\/:*?"<>|\r\n]+\\?)(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
- UnixARPath string = `^((\.{0,2}/)?([^/\x00]*))+/?$`
- Semver string = "^v?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$"
- tagName string = "valid"
- hasLowerCase string = ".*[[:lower:]]"
- hasUpperCase string = ".*[[:upper:]]"
- hasWhitespace string = ".*[[:space:]]"
- hasWhitespaceOnly string = "^[[:space:]]+$"
- IMEI string = "^[0-9a-f]{14}$|^\\d{15}$|^\\d{18}$"
- IMSI string = "^\\d{14,15}$"
- E164 string = `^\+?[1-9]\d{1,14}$`
-)
-
-// Used by IsFilePath func
-const (
- // Unknown is unresolved OS type
- Unknown = iota
- // Win is Windows type
- Win
- // Unix is *nix OS types
- Unix
-)
-
-var (
- userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$")
- hostRegexp = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$")
- userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})")
- rxEmail = regexp.MustCompile(Email)
- rxCreditCard = regexp.MustCompile(CreditCard)
- rxISBN10 = regexp.MustCompile(ISBN10)
- rxISBN13 = regexp.MustCompile(ISBN13)
- rxUUID3 = regexp.MustCompile(UUID3)
- rxUUID4 = regexp.MustCompile(UUID4)
- rxUUID5 = regexp.MustCompile(UUID5)
- rxUUID = regexp.MustCompile(UUID)
- rxAlpha = regexp.MustCompile(Alpha)
- rxAlphanumeric = regexp.MustCompile(Alphanumeric)
- rxNumeric = regexp.MustCompile(Numeric)
- rxInt = regexp.MustCompile(Int)
- rxFloat = regexp.MustCompile(Float)
- rxHexadecimal = regexp.MustCompile(Hexadecimal)
- rxHexcolor = regexp.MustCompile(Hexcolor)
- rxRGBcolor = regexp.MustCompile(RGBcolor)
- rxASCII = regexp.MustCompile(ASCII)
- rxPrintableASCII = regexp.MustCompile(PrintableASCII)
- rxMultibyte = regexp.MustCompile(Multibyte)
- rxFullWidth = regexp.MustCompile(FullWidth)
- rxHalfWidth = regexp.MustCompile(HalfWidth)
- rxBase64 = regexp.MustCompile(Base64)
- rxDataURI = regexp.MustCompile(DataURI)
- rxMagnetURI = regexp.MustCompile(MagnetURI)
- rxLatitude = regexp.MustCompile(Latitude)
- rxLongitude = regexp.MustCompile(Longitude)
- rxDNSName = regexp.MustCompile(DNSName)
- rxURL = regexp.MustCompile(URL)
- rxSSN = regexp.MustCompile(SSN)
- rxWinPath = regexp.MustCompile(WinPath)
- rxUnixPath = regexp.MustCompile(UnixPath)
- rxARWinPath = regexp.MustCompile(WinARPath)
- rxARUnixPath = regexp.MustCompile(UnixARPath)
- rxSemver = regexp.MustCompile(Semver)
- rxHasLowerCase = regexp.MustCompile(hasLowerCase)
- rxHasUpperCase = regexp.MustCompile(hasUpperCase)
- rxHasWhitespace = regexp.MustCompile(hasWhitespace)
- rxHasWhitespaceOnly = regexp.MustCompile(hasWhitespaceOnly)
- rxIMEI = regexp.MustCompile(IMEI)
- rxIMSI = regexp.MustCompile(IMSI)
- rxE164 = regexp.MustCompile(E164)
-)
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/types.go b/test/tools/vendor/github.com/asaskevich/govalidator/types.go
deleted file mode 100644
index c573abb51a..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/types.go
+++ /dev/null
@@ -1,656 +0,0 @@
-package govalidator
-
-import (
- "reflect"
- "regexp"
- "sort"
- "sync"
-)
-
-// Validator is a wrapper for a validator function that returns bool and accepts string.
-type Validator func(str string) bool
-
-// CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type.
-// The second parameter should be the context (in the case of validating a struct: the whole object being validated).
-type CustomTypeValidator func(i interface{}, o interface{}) bool
-
-// ParamValidator is a wrapper for validator functions that accept additional parameters.
-type ParamValidator func(str string, params ...string) bool
-
-// InterfaceParamValidator is a wrapper for functions that accept variants parameters for an interface value
-type InterfaceParamValidator func(in interface{}, params ...string) bool
-type tagOptionsMap map[string]tagOption
-
-func (t tagOptionsMap) orderedKeys() []string {
- var keys []string
- for k := range t {
- keys = append(keys, k)
- }
-
- sort.Slice(keys, func(a, b int) bool {
- return t[keys[a]].order < t[keys[b]].order
- })
-
- return keys
-}
-
-type tagOption struct {
- name string
- customErrorMessage string
- order int
-}
-
-// UnsupportedTypeError is a wrapper for reflect.Type
-type UnsupportedTypeError struct {
- Type reflect.Type
-}
-
-// stringValues is a slice of reflect.Value holding *reflect.StringValue.
-// It implements the methods to sort by string.
-type stringValues []reflect.Value
-
-// InterfaceParamTagMap is a map of functions accept variants parameters for an interface value
-var InterfaceParamTagMap = map[string]InterfaceParamValidator{
- "type": IsType,
-}
-
-// InterfaceParamTagRegexMap maps interface param tags to their respective regexes.
-var InterfaceParamTagRegexMap = map[string]*regexp.Regexp{
- "type": regexp.MustCompile(`^type\((.*)\)$`),
-}
-
-// ParamTagMap is a map of functions accept variants parameters
-var ParamTagMap = map[string]ParamValidator{
- "length": ByteLength,
- "range": Range,
- "runelength": RuneLength,
- "stringlength": StringLength,
- "matches": StringMatches,
- "in": IsInRaw,
- "rsapub": IsRsaPub,
- "minstringlength": MinStringLength,
- "maxstringlength": MaxStringLength,
-}
-
-// ParamTagRegexMap maps param tags to their respective regexes.
-var ParamTagRegexMap = map[string]*regexp.Regexp{
- "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"),
- "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"),
- "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"),
- "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"),
- "in": regexp.MustCompile(`^in\((.*)\)`),
- "matches": regexp.MustCompile(`^matches\((.+)\)$`),
- "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"),
- "minstringlength": regexp.MustCompile("^minstringlength\\((\\d+)\\)$"),
- "maxstringlength": regexp.MustCompile("^maxstringlength\\((\\d+)\\)$"),
-}
-
-type customTypeTagMap struct {
- validators map[string]CustomTypeValidator
-
- sync.RWMutex
-}
-
-func (tm *customTypeTagMap) Get(name string) (CustomTypeValidator, bool) {
- tm.RLock()
- defer tm.RUnlock()
- v, ok := tm.validators[name]
- return v, ok
-}
-
-func (tm *customTypeTagMap) Set(name string, ctv CustomTypeValidator) {
- tm.Lock()
- defer tm.Unlock()
- tm.validators[name] = ctv
-}
-
-// CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function.
-// Use this to validate compound or custom types that need to be handled as a whole, e.g.
-// `type UUID [16]byte` (this would be handled as an array of bytes).
-var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)}
-
-// TagMap is a map of functions, that can be used as tags for ValidateStruct function.
-var TagMap = map[string]Validator{
- "email": IsEmail,
- "url": IsURL,
- "dialstring": IsDialString,
- "requrl": IsRequestURL,
- "requri": IsRequestURI,
- "alpha": IsAlpha,
- "utfletter": IsUTFLetter,
- "alphanum": IsAlphanumeric,
- "utfletternum": IsUTFLetterNumeric,
- "numeric": IsNumeric,
- "utfnumeric": IsUTFNumeric,
- "utfdigit": IsUTFDigit,
- "hexadecimal": IsHexadecimal,
- "hexcolor": IsHexcolor,
- "rgbcolor": IsRGBcolor,
- "lowercase": IsLowerCase,
- "uppercase": IsUpperCase,
- "int": IsInt,
- "float": IsFloat,
- "null": IsNull,
- "notnull": IsNotNull,
- "uuid": IsUUID,
- "uuidv3": IsUUIDv3,
- "uuidv4": IsUUIDv4,
- "uuidv5": IsUUIDv5,
- "creditcard": IsCreditCard,
- "isbn10": IsISBN10,
- "isbn13": IsISBN13,
- "json": IsJSON,
- "multibyte": IsMultibyte,
- "ascii": IsASCII,
- "printableascii": IsPrintableASCII,
- "fullwidth": IsFullWidth,
- "halfwidth": IsHalfWidth,
- "variablewidth": IsVariableWidth,
- "base64": IsBase64,
- "datauri": IsDataURI,
- "ip": IsIP,
- "port": IsPort,
- "ipv4": IsIPv4,
- "ipv6": IsIPv6,
- "dns": IsDNSName,
- "host": IsHost,
- "mac": IsMAC,
- "latitude": IsLatitude,
- "longitude": IsLongitude,
- "ssn": IsSSN,
- "semver": IsSemver,
- "rfc3339": IsRFC3339,
- "rfc3339WithoutZone": IsRFC3339WithoutZone,
- "ISO3166Alpha2": IsISO3166Alpha2,
- "ISO3166Alpha3": IsISO3166Alpha3,
- "ISO4217": IsISO4217,
- "IMEI": IsIMEI,
- "ulid": IsULID,
-}
-
-// ISO3166Entry stores country codes
-type ISO3166Entry struct {
- EnglishShortName string
- FrenchShortName string
- Alpha2Code string
- Alpha3Code string
- Numeric string
-}
-
-//ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes"
-var ISO3166List = []ISO3166Entry{
- {"Afghanistan", "Afghanistan (l')", "AF", "AFG", "004"},
- {"Albania", "Albanie (l')", "AL", "ALB", "008"},
- {"Antarctica", "Antarctique (l')", "AQ", "ATA", "010"},
- {"Algeria", "Algérie (l')", "DZ", "DZA", "012"},
- {"American Samoa", "Samoa américaines (les)", "AS", "ASM", "016"},
- {"Andorra", "Andorre (l')", "AD", "AND", "020"},
- {"Angola", "Angola (l')", "AO", "AGO", "024"},
- {"Antigua and Barbuda", "Antigua-et-Barbuda", "AG", "ATG", "028"},
- {"Azerbaijan", "Azerbaïdjan (l')", "AZ", "AZE", "031"},
- {"Argentina", "Argentine (l')", "AR", "ARG", "032"},
- {"Australia", "Australie (l')", "AU", "AUS", "036"},
- {"Austria", "Autriche (l')", "AT", "AUT", "040"},
- {"Bahamas (the)", "Bahamas (les)", "BS", "BHS", "044"},
- {"Bahrain", "Bahreïn", "BH", "BHR", "048"},
- {"Bangladesh", "Bangladesh (le)", "BD", "BGD", "050"},
- {"Armenia", "Arménie (l')", "AM", "ARM", "051"},
- {"Barbados", "Barbade (la)", "BB", "BRB", "052"},
- {"Belgium", "Belgique (la)", "BE", "BEL", "056"},
- {"Bermuda", "Bermudes (les)", "BM", "BMU", "060"},
- {"Bhutan", "Bhoutan (le)", "BT", "BTN", "064"},
- {"Bolivia (Plurinational State of)", "Bolivie (État plurinational de)", "BO", "BOL", "068"},
- {"Bosnia and Herzegovina", "Bosnie-Herzégovine (la)", "BA", "BIH", "070"},
- {"Botswana", "Botswana (le)", "BW", "BWA", "072"},
- {"Bouvet Island", "Bouvet (l'Île)", "BV", "BVT", "074"},
- {"Brazil", "Brésil (le)", "BR", "BRA", "076"},
- {"Belize", "Belize (le)", "BZ", "BLZ", "084"},
- {"British Indian Ocean Territory (the)", "Indien (le Territoire britannique de l'océan)", "IO", "IOT", "086"},
- {"Solomon Islands", "Salomon (Îles)", "SB", "SLB", "090"},
- {"Virgin Islands (British)", "Vierges britanniques (les Îles)", "VG", "VGB", "092"},
- {"Brunei Darussalam", "Brunéi Darussalam (le)", "BN", "BRN", "096"},
- {"Bulgaria", "Bulgarie (la)", "BG", "BGR", "100"},
- {"Myanmar", "Myanmar (le)", "MM", "MMR", "104"},
- {"Burundi", "Burundi (le)", "BI", "BDI", "108"},
- {"Belarus", "Bélarus (le)", "BY", "BLR", "112"},
- {"Cambodia", "Cambodge (le)", "KH", "KHM", "116"},
- {"Cameroon", "Cameroun (le)", "CM", "CMR", "120"},
- {"Canada", "Canada (le)", "CA", "CAN", "124"},
- {"Cabo Verde", "Cabo Verde", "CV", "CPV", "132"},
- {"Cayman Islands (the)", "Caïmans (les Îles)", "KY", "CYM", "136"},
- {"Central African Republic (the)", "République centrafricaine (la)", "CF", "CAF", "140"},
- {"Sri Lanka", "Sri Lanka", "LK", "LKA", "144"},
- {"Chad", "Tchad (le)", "TD", "TCD", "148"},
- {"Chile", "Chili (le)", "CL", "CHL", "152"},
- {"China", "Chine (la)", "CN", "CHN", "156"},
- {"Taiwan (Province of China)", "Taïwan (Province de Chine)", "TW", "TWN", "158"},
- {"Christmas Island", "Christmas (l'Île)", "CX", "CXR", "162"},
- {"Cocos (Keeling) Islands (the)", "Cocos (les Îles)/ Keeling (les Îles)", "CC", "CCK", "166"},
- {"Colombia", "Colombie (la)", "CO", "COL", "170"},
- {"Comoros (the)", "Comores (les)", "KM", "COM", "174"},
- {"Mayotte", "Mayotte", "YT", "MYT", "175"},
- {"Congo (the)", "Congo (le)", "CG", "COG", "178"},
- {"Congo (the Democratic Republic of the)", "Congo (la République démocratique du)", "CD", "COD", "180"},
- {"Cook Islands (the)", "Cook (les Îles)", "CK", "COK", "184"},
- {"Costa Rica", "Costa Rica (le)", "CR", "CRI", "188"},
- {"Croatia", "Croatie (la)", "HR", "HRV", "191"},
- {"Cuba", "Cuba", "CU", "CUB", "192"},
- {"Cyprus", "Chypre", "CY", "CYP", "196"},
- {"Czech Republic (the)", "tchèque (la République)", "CZ", "CZE", "203"},
- {"Benin", "Bénin (le)", "BJ", "BEN", "204"},
- {"Denmark", "Danemark (le)", "DK", "DNK", "208"},
- {"Dominica", "Dominique (la)", "DM", "DMA", "212"},
- {"Dominican Republic (the)", "dominicaine (la République)", "DO", "DOM", "214"},
- {"Ecuador", "Équateur (l')", "EC", "ECU", "218"},
- {"El Salvador", "El Salvador", "SV", "SLV", "222"},
- {"Equatorial Guinea", "Guinée équatoriale (la)", "GQ", "GNQ", "226"},
- {"Ethiopia", "Éthiopie (l')", "ET", "ETH", "231"},
- {"Eritrea", "Érythrée (l')", "ER", "ERI", "232"},
- {"Estonia", "Estonie (l')", "EE", "EST", "233"},
- {"Faroe Islands (the)", "Féroé (les Îles)", "FO", "FRO", "234"},
- {"Falkland Islands (the) [Malvinas]", "Falkland (les Îles)/Malouines (les Îles)", "FK", "FLK", "238"},
- {"South Georgia and the South Sandwich Islands", "Géorgie du Sud-et-les Îles Sandwich du Sud (la)", "GS", "SGS", "239"},
- {"Fiji", "Fidji (les)", "FJ", "FJI", "242"},
- {"Finland", "Finlande (la)", "FI", "FIN", "246"},
- {"Åland Islands", "Åland(les Îles)", "AX", "ALA", "248"},
- {"France", "France (la)", "FR", "FRA", "250"},
- {"French Guiana", "Guyane française (la )", "GF", "GUF", "254"},
- {"French Polynesia", "Polynésie française (la)", "PF", "PYF", "258"},
- {"French Southern Territories (the)", "Terres australes françaises (les)", "TF", "ATF", "260"},
- {"Djibouti", "Djibouti", "DJ", "DJI", "262"},
- {"Gabon", "Gabon (le)", "GA", "GAB", "266"},
- {"Georgia", "Géorgie (la)", "GE", "GEO", "268"},
- {"Gambia (the)", "Gambie (la)", "GM", "GMB", "270"},
- {"Palestine, State of", "Palestine, État de", "PS", "PSE", "275"},
- {"Germany", "Allemagne (l')", "DE", "DEU", "276"},
- {"Ghana", "Ghana (le)", "GH", "GHA", "288"},
- {"Gibraltar", "Gibraltar", "GI", "GIB", "292"},
- {"Kiribati", "Kiribati", "KI", "KIR", "296"},
- {"Greece", "Grèce (la)", "GR", "GRC", "300"},
- {"Greenland", "Groenland (le)", "GL", "GRL", "304"},
- {"Grenada", "Grenade (la)", "GD", "GRD", "308"},
- {"Guadeloupe", "Guadeloupe (la)", "GP", "GLP", "312"},
- {"Guam", "Guam", "GU", "GUM", "316"},
- {"Guatemala", "Guatemala (le)", "GT", "GTM", "320"},
- {"Guinea", "Guinée (la)", "GN", "GIN", "324"},
- {"Guyana", "Guyana (le)", "GY", "GUY", "328"},
- {"Haiti", "Haïti", "HT", "HTI", "332"},
- {"Heard Island and McDonald Islands", "Heard-et-Îles MacDonald (l'Île)", "HM", "HMD", "334"},
- {"Holy See (the)", "Saint-Siège (le)", "VA", "VAT", "336"},
- {"Honduras", "Honduras (le)", "HN", "HND", "340"},
- {"Hong Kong", "Hong Kong", "HK", "HKG", "344"},
- {"Hungary", "Hongrie (la)", "HU", "HUN", "348"},
- {"Iceland", "Islande (l')", "IS", "ISL", "352"},
- {"India", "Inde (l')", "IN", "IND", "356"},
- {"Indonesia", "Indonésie (l')", "ID", "IDN", "360"},
- {"Iran (Islamic Republic of)", "Iran (République Islamique d')", "IR", "IRN", "364"},
- {"Iraq", "Iraq (l')", "IQ", "IRQ", "368"},
- {"Ireland", "Irlande (l')", "IE", "IRL", "372"},
- {"Israel", "Israël", "IL", "ISR", "376"},
- {"Italy", "Italie (l')", "IT", "ITA", "380"},
- {"Côte d'Ivoire", "Côte d'Ivoire (la)", "CI", "CIV", "384"},
- {"Jamaica", "Jamaïque (la)", "JM", "JAM", "388"},
- {"Japan", "Japon (le)", "JP", "JPN", "392"},
- {"Kazakhstan", "Kazakhstan (le)", "KZ", "KAZ", "398"},
- {"Jordan", "Jordanie (la)", "JO", "JOR", "400"},
- {"Kenya", "Kenya (le)", "KE", "KEN", "404"},
- {"Korea (the Democratic People's Republic of)", "Corée (la République populaire démocratique de)", "KP", "PRK", "408"},
- {"Korea (the Republic of)", "Corée (la République de)", "KR", "KOR", "410"},
- {"Kuwait", "Koweït (le)", "KW", "KWT", "414"},
- {"Kyrgyzstan", "Kirghizistan (le)", "KG", "KGZ", "417"},
- {"Lao People's Democratic Republic (the)", "Lao, République démocratique populaire", "LA", "LAO", "418"},
- {"Lebanon", "Liban (le)", "LB", "LBN", "422"},
- {"Lesotho", "Lesotho (le)", "LS", "LSO", "426"},
- {"Latvia", "Lettonie (la)", "LV", "LVA", "428"},
- {"Liberia", "Libéria (le)", "LR", "LBR", "430"},
- {"Libya", "Libye (la)", "LY", "LBY", "434"},
- {"Liechtenstein", "Liechtenstein (le)", "LI", "LIE", "438"},
- {"Lithuania", "Lituanie (la)", "LT", "LTU", "440"},
- {"Luxembourg", "Luxembourg (le)", "LU", "LUX", "442"},
- {"Macao", "Macao", "MO", "MAC", "446"},
- {"Madagascar", "Madagascar", "MG", "MDG", "450"},
- {"Malawi", "Malawi (le)", "MW", "MWI", "454"},
- {"Malaysia", "Malaisie (la)", "MY", "MYS", "458"},
- {"Maldives", "Maldives (les)", "MV", "MDV", "462"},
- {"Mali", "Mali (le)", "ML", "MLI", "466"},
- {"Malta", "Malte", "MT", "MLT", "470"},
- {"Martinique", "Martinique (la)", "MQ", "MTQ", "474"},
- {"Mauritania", "Mauritanie (la)", "MR", "MRT", "478"},
- {"Mauritius", "Maurice", "MU", "MUS", "480"},
- {"Mexico", "Mexique (le)", "MX", "MEX", "484"},
- {"Monaco", "Monaco", "MC", "MCO", "492"},
- {"Mongolia", "Mongolie (la)", "MN", "MNG", "496"},
- {"Moldova (the Republic of)", "Moldova , République de", "MD", "MDA", "498"},
- {"Montenegro", "Monténégro (le)", "ME", "MNE", "499"},
- {"Montserrat", "Montserrat", "MS", "MSR", "500"},
- {"Morocco", "Maroc (le)", "MA", "MAR", "504"},
- {"Mozambique", "Mozambique (le)", "MZ", "MOZ", "508"},
- {"Oman", "Oman", "OM", "OMN", "512"},
- {"Namibia", "Namibie (la)", "NA", "NAM", "516"},
- {"Nauru", "Nauru", "NR", "NRU", "520"},
- {"Nepal", "Népal (le)", "NP", "NPL", "524"},
- {"Netherlands (the)", "Pays-Bas (les)", "NL", "NLD", "528"},
- {"Curaçao", "Curaçao", "CW", "CUW", "531"},
- {"Aruba", "Aruba", "AW", "ABW", "533"},
- {"Sint Maarten (Dutch part)", "Saint-Martin (partie néerlandaise)", "SX", "SXM", "534"},
- {"Bonaire, Sint Eustatius and Saba", "Bonaire, Saint-Eustache et Saba", "BQ", "BES", "535"},
- {"New Caledonia", "Nouvelle-Calédonie (la)", "NC", "NCL", "540"},
- {"Vanuatu", "Vanuatu (le)", "VU", "VUT", "548"},
- {"New Zealand", "Nouvelle-Zélande (la)", "NZ", "NZL", "554"},
- {"Nicaragua", "Nicaragua (le)", "NI", "NIC", "558"},
- {"Niger (the)", "Niger (le)", "NE", "NER", "562"},
- {"Nigeria", "Nigéria (le)", "NG", "NGA", "566"},
- {"Niue", "Niue", "NU", "NIU", "570"},
- {"Norfolk Island", "Norfolk (l'Île)", "NF", "NFK", "574"},
- {"Norway", "Norvège (la)", "NO", "NOR", "578"},
- {"Northern Mariana Islands (the)", "Mariannes du Nord (les Îles)", "MP", "MNP", "580"},
- {"United States Minor Outlying Islands (the)", "Îles mineures éloignées des États-Unis (les)", "UM", "UMI", "581"},
- {"Micronesia (Federated States of)", "Micronésie (États fédérés de)", "FM", "FSM", "583"},
- {"Marshall Islands (the)", "Marshall (Îles)", "MH", "MHL", "584"},
- {"Palau", "Palaos (les)", "PW", "PLW", "585"},
- {"Pakistan", "Pakistan (le)", "PK", "PAK", "586"},
- {"Panama", "Panama (le)", "PA", "PAN", "591"},
- {"Papua New Guinea", "Papouasie-Nouvelle-Guinée (la)", "PG", "PNG", "598"},
- {"Paraguay", "Paraguay (le)", "PY", "PRY", "600"},
- {"Peru", "Pérou (le)", "PE", "PER", "604"},
- {"Philippines (the)", "Philippines (les)", "PH", "PHL", "608"},
- {"Pitcairn", "Pitcairn", "PN", "PCN", "612"},
- {"Poland", "Pologne (la)", "PL", "POL", "616"},
- {"Portugal", "Portugal (le)", "PT", "PRT", "620"},
- {"Guinea-Bissau", "Guinée-Bissau (la)", "GW", "GNB", "624"},
- {"Timor-Leste", "Timor-Leste (le)", "TL", "TLS", "626"},
- {"Puerto Rico", "Porto Rico", "PR", "PRI", "630"},
- {"Qatar", "Qatar (le)", "QA", "QAT", "634"},
- {"Réunion", "Réunion (La)", "RE", "REU", "638"},
- {"Romania", "Roumanie (la)", "RO", "ROU", "642"},
- {"Russian Federation (the)", "Russie (la Fédération de)", "RU", "RUS", "643"},
- {"Rwanda", "Rwanda (le)", "RW", "RWA", "646"},
- {"Saint Barthélemy", "Saint-Barthélemy", "BL", "BLM", "652"},
- {"Saint Helena, Ascension and Tristan da Cunha", "Sainte-Hélène, Ascension et Tristan da Cunha", "SH", "SHN", "654"},
- {"Saint Kitts and Nevis", "Saint-Kitts-et-Nevis", "KN", "KNA", "659"},
- {"Anguilla", "Anguilla", "AI", "AIA", "660"},
- {"Saint Lucia", "Sainte-Lucie", "LC", "LCA", "662"},
- {"Saint Martin (French part)", "Saint-Martin (partie française)", "MF", "MAF", "663"},
- {"Saint Pierre and Miquelon", "Saint-Pierre-et-Miquelon", "PM", "SPM", "666"},
- {"Saint Vincent and the Grenadines", "Saint-Vincent-et-les Grenadines", "VC", "VCT", "670"},
- {"San Marino", "Saint-Marin", "SM", "SMR", "674"},
- {"Sao Tome and Principe", "Sao Tomé-et-Principe", "ST", "STP", "678"},
- {"Saudi Arabia", "Arabie saoudite (l')", "SA", "SAU", "682"},
- {"Senegal", "Sénégal (le)", "SN", "SEN", "686"},
- {"Serbia", "Serbie (la)", "RS", "SRB", "688"},
- {"Seychelles", "Seychelles (les)", "SC", "SYC", "690"},
- {"Sierra Leone", "Sierra Leone (la)", "SL", "SLE", "694"},
- {"Singapore", "Singapour", "SG", "SGP", "702"},
- {"Slovakia", "Slovaquie (la)", "SK", "SVK", "703"},
- {"Viet Nam", "Viet Nam (le)", "VN", "VNM", "704"},
- {"Slovenia", "Slovénie (la)", "SI", "SVN", "705"},
- {"Somalia", "Somalie (la)", "SO", "SOM", "706"},
- {"South Africa", "Afrique du Sud (l')", "ZA", "ZAF", "710"},
- {"Zimbabwe", "Zimbabwe (le)", "ZW", "ZWE", "716"},
- {"Spain", "Espagne (l')", "ES", "ESP", "724"},
- {"South Sudan", "Soudan du Sud (le)", "SS", "SSD", "728"},
- {"Sudan (the)", "Soudan (le)", "SD", "SDN", "729"},
- {"Western Sahara*", "Sahara occidental (le)*", "EH", "ESH", "732"},
- {"Suriname", "Suriname (le)", "SR", "SUR", "740"},
- {"Svalbard and Jan Mayen", "Svalbard et l'Île Jan Mayen (le)", "SJ", "SJM", "744"},
- {"Swaziland", "Swaziland (le)", "SZ", "SWZ", "748"},
- {"Sweden", "Suède (la)", "SE", "SWE", "752"},
- {"Switzerland", "Suisse (la)", "CH", "CHE", "756"},
- {"Syrian Arab Republic", "République arabe syrienne (la)", "SY", "SYR", "760"},
- {"Tajikistan", "Tadjikistan (le)", "TJ", "TJK", "762"},
- {"Thailand", "Thaïlande (la)", "TH", "THA", "764"},
- {"Togo", "Togo (le)", "TG", "TGO", "768"},
- {"Tokelau", "Tokelau (les)", "TK", "TKL", "772"},
- {"Tonga", "Tonga (les)", "TO", "TON", "776"},
- {"Trinidad and Tobago", "Trinité-et-Tobago (la)", "TT", "TTO", "780"},
- {"United Arab Emirates (the)", "Émirats arabes unis (les)", "AE", "ARE", "784"},
- {"Tunisia", "Tunisie (la)", "TN", "TUN", "788"},
- {"Turkey", "Turquie (la)", "TR", "TUR", "792"},
- {"Turkmenistan", "Turkménistan (le)", "TM", "TKM", "795"},
- {"Turks and Caicos Islands (the)", "Turks-et-Caïcos (les Îles)", "TC", "TCA", "796"},
- {"Tuvalu", "Tuvalu (les)", "TV", "TUV", "798"},
- {"Uganda", "Ouganda (l')", "UG", "UGA", "800"},
- {"Ukraine", "Ukraine (l')", "UA", "UKR", "804"},
- {"Macedonia (the former Yugoslav Republic of)", "Macédoine (l'ex‑République yougoslave de)", "MK", "MKD", "807"},
- {"Egypt", "Égypte (l')", "EG", "EGY", "818"},
- {"United Kingdom of Great Britain and Northern Ireland (the)", "Royaume-Uni de Grande-Bretagne et d'Irlande du Nord (le)", "GB", "GBR", "826"},
- {"Guernsey", "Guernesey", "GG", "GGY", "831"},
- {"Jersey", "Jersey", "JE", "JEY", "832"},
- {"Isle of Man", "Île de Man", "IM", "IMN", "833"},
- {"Tanzania, United Republic of", "Tanzanie, République-Unie de", "TZ", "TZA", "834"},
- {"United States of America (the)", "États-Unis d'Amérique (les)", "US", "USA", "840"},
- {"Virgin Islands (U.S.)", "Vierges des États-Unis (les Îles)", "VI", "VIR", "850"},
- {"Burkina Faso", "Burkina Faso (le)", "BF", "BFA", "854"},
- {"Uruguay", "Uruguay (l')", "UY", "URY", "858"},
- {"Uzbekistan", "Ouzbékistan (l')", "UZ", "UZB", "860"},
- {"Venezuela (Bolivarian Republic of)", "Venezuela (République bolivarienne du)", "VE", "VEN", "862"},
- {"Wallis and Futuna", "Wallis-et-Futuna", "WF", "WLF", "876"},
- {"Samoa", "Samoa (le)", "WS", "WSM", "882"},
- {"Yemen", "Yémen (le)", "YE", "YEM", "887"},
- {"Zambia", "Zambie (la)", "ZM", "ZMB", "894"},
-}
-
-// ISO4217List is the list of ISO currency codes
-var ISO4217List = []string{
- "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN",
- "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD",
- "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK",
- "DJF", "DKK", "DOP", "DZD",
- "EGP", "ERN", "ETB", "EUR",
- "FJD", "FKP",
- "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD",
- "HKD", "HNL", "HRK", "HTG", "HUF",
- "IDR", "ILS", "INR", "IQD", "IRR", "ISK",
- "JMD", "JOD", "JPY",
- "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT",
- "LAK", "LBP", "LKR", "LRD", "LSL", "LYD",
- "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN",
- "NAD", "NGN", "NIO", "NOK", "NPR", "NZD",
- "OMR",
- "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG",
- "QAR",
- "RON", "RSD", "RUB", "RWF",
- "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "STN", "SVC", "SYP", "SZL",
- "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS",
- "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", "UZS",
- "VEF", "VES", "VND", "VUV",
- "WST",
- "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX",
- "YER",
- "ZAR", "ZMW", "ZWL",
-}
-
-// ISO693Entry stores ISO language codes
-type ISO693Entry struct {
- Alpha3bCode string
- Alpha2Code string
- English string
-}
-
-//ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json
-var ISO693List = []ISO693Entry{
- {Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"},
- {Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"},
- {Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"},
- {Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"},
- {Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"},
- {Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"},
- {Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"},
- {Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"},
- {Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"},
- {Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"},
- {Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"},
- {Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"},
- {Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"},
- {Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"},
- {Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"},
- {Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"},
- {Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"},
- {Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"},
- {Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"},
- {Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"},
- {Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"},
- {Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"},
- {Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"},
- {Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"},
- {Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"},
- {Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"},
- {Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"},
- {Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"},
- {Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"},
- {Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"},
- {Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"},
- {Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"},
- {Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"},
- {Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"},
- {Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"},
- {Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"},
- {Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"},
- {Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"},
- {Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"},
- {Alpha3bCode: "eng", Alpha2Code: "en", English: "English"},
- {Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"},
- {Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"},
- {Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"},
- {Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"},
- {Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"},
- {Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"},
- {Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"},
- {Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"},
- {Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"},
- {Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"},
- {Alpha3bCode: "ger", Alpha2Code: "de", English: "German"},
- {Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"},
- {Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"},
- {Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"},
- {Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"},
- {Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"},
- {Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"},
- {Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"},
- {Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"},
- {Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"},
- {Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"},
- {Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"},
- {Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"},
- {Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"},
- {Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"},
- {Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"},
- {Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"},
- {Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"},
- {Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"},
- {Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"},
- {Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"},
- {Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"},
- {Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"},
- {Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"},
- {Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"},
- {Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"},
- {Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"},
- {Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"},
- {Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"},
- {Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"},
- {Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"},
- {Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"},
- {Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"},
- {Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"},
- {Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"},
- {Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"},
- {Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"},
- {Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"},
- {Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"},
- {Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"},
- {Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"},
- {Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"},
- {Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"},
- {Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"},
- {Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"},
- {Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"},
- {Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"},
- {Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"},
- {Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"},
- {Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"},
- {Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"},
- {Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"},
- {Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"},
- {Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"},
- {Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"},
- {Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"},
- {Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"},
- {Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"},
- {Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"},
- {Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"},
- {Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"},
- {Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"},
- {Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"},
- {Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"},
- {Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"},
- {Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"},
- {Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"},
- {Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"},
- {Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"},
- {Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"},
- {Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"},
- {Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"},
- {Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"},
- {Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"},
- {Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"},
- {Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"},
- {Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"},
- {Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"},
- {Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"},
- {Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"},
- {Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"},
- {Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"},
- {Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"},
- {Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"},
- {Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"},
- {Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"},
- {Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"},
- {Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"},
- {Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"},
- {Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"},
- {Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"},
- {Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"},
- {Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"},
- {Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"},
- {Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"},
- {Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"},
- {Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"},
- {Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"},
- {Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"},
- {Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"},
- {Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"},
- {Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"},
- {Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"},
- {Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"},
- {Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"},
- {Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"},
- {Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"},
- {Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"},
- {Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"},
- {Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"},
- {Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"},
- {Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"},
- {Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"},
- {Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"},
- {Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"},
- {Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"},
- {Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"},
- {Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"},
- {Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"},
- {Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"},
- {Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"},
- {Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"},
- {Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"},
- {Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"},
- {Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"},
- {Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"},
- {Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"},
- {Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"},
- {Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"},
- {Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"},
- {Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"},
- {Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"},
- {Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"},
- {Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"},
-}
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/utils.go b/test/tools/vendor/github.com/asaskevich/govalidator/utils.go
deleted file mode 100644
index f4c30f824a..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/utils.go
+++ /dev/null
@@ -1,270 +0,0 @@
-package govalidator
-
-import (
- "errors"
- "fmt"
- "html"
- "math"
- "path"
- "regexp"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-// Contains checks if the string contains the substring.
-func Contains(str, substring string) bool {
- return strings.Contains(str, substring)
-}
-
-// Matches checks if string matches the pattern (pattern is regular expression)
-// In case of error return false
-func Matches(str, pattern string) bool {
- match, _ := regexp.MatchString(pattern, str)
- return match
-}
-
-// LeftTrim trims characters from the left side of the input.
-// If second argument is empty, it will remove leading spaces.
-func LeftTrim(str, chars string) string {
- if chars == "" {
- return strings.TrimLeftFunc(str, unicode.IsSpace)
- }
- r, _ := regexp.Compile("^[" + chars + "]+")
- return r.ReplaceAllString(str, "")
-}
-
-// RightTrim trims characters from the right side of the input.
-// If second argument is empty, it will remove trailing spaces.
-func RightTrim(str, chars string) string {
- if chars == "" {
- return strings.TrimRightFunc(str, unicode.IsSpace)
- }
- r, _ := regexp.Compile("[" + chars + "]+$")
- return r.ReplaceAllString(str, "")
-}
-
-// Trim trims characters from both sides of the input.
-// If second argument is empty, it will remove spaces.
-func Trim(str, chars string) string {
- return LeftTrim(RightTrim(str, chars), chars)
-}
-
-// WhiteList removes characters that do not appear in the whitelist.
-func WhiteList(str, chars string) string {
- pattern := "[^" + chars + "]+"
- r, _ := regexp.Compile(pattern)
- return r.ReplaceAllString(str, "")
-}
-
-// BlackList removes characters that appear in the blacklist.
-func BlackList(str, chars string) string {
- pattern := "[" + chars + "]+"
- r, _ := regexp.Compile(pattern)
- return r.ReplaceAllString(str, "")
-}
-
-// StripLow removes characters with a numerical value < 32 and 127, mostly control characters.
-// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD).
-func StripLow(str string, keepNewLines bool) string {
- chars := ""
- if keepNewLines {
- chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F"
- } else {
- chars = "\x00-\x1F\x7F"
- }
- return BlackList(str, chars)
-}
-
-// ReplacePattern replaces regular expression pattern in string
-func ReplacePattern(str, pattern, replace string) string {
- r, _ := regexp.Compile(pattern)
- return r.ReplaceAllString(str, replace)
-}
-
-// Escape replaces <, >, & and " with HTML entities.
-var Escape = html.EscapeString
-
-func addSegment(inrune, segment []rune) []rune {
- if len(segment) == 0 {
- return inrune
- }
- if len(inrune) != 0 {
- inrune = append(inrune, '_')
- }
- inrune = append(inrune, segment...)
- return inrune
-}
-
-// UnderscoreToCamelCase converts from underscore separated form to camel case form.
-// Ex.: my_func => MyFunc
-func UnderscoreToCamelCase(s string) string {
- return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1)
-}
-
-// CamelCaseToUnderscore converts from camel case form to underscore separated form.
-// Ex.: MyFunc => my_func
-func CamelCaseToUnderscore(str string) string {
- var output []rune
- var segment []rune
- for _, r := range str {
-
- // not treat number as separate segment
- if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) {
- output = addSegment(output, segment)
- segment = nil
- }
- segment = append(segment, unicode.ToLower(r))
- }
- output = addSegment(output, segment)
- return string(output)
-}
-
-// Reverse returns reversed string
-func Reverse(s string) string {
- r := []rune(s)
- for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
- r[i], r[j] = r[j], r[i]
- }
- return string(r)
-}
-
-// GetLines splits string by "\n" and return array of lines
-func GetLines(s string) []string {
- return strings.Split(s, "\n")
-}
-
-// GetLine returns specified line of multiline string
-func GetLine(s string, index int) (string, error) {
- lines := GetLines(s)
- if index < 0 || index >= len(lines) {
- return "", errors.New("line index out of bounds")
- }
- return lines[index], nil
-}
-
-// RemoveTags removes all tags from HTML string
-func RemoveTags(s string) string {
- return ReplacePattern(s, "<[^>]*>", "")
-}
-
-// SafeFileName returns safe string that can be used in file names
-func SafeFileName(str string) string {
- name := strings.ToLower(str)
- name = path.Clean(path.Base(name))
- name = strings.Trim(name, " ")
- separators, err := regexp.Compile(`[ &_=+:]`)
- if err == nil {
- name = separators.ReplaceAllString(name, "-")
- }
- legal, err := regexp.Compile(`[^[:alnum:]-.]`)
- if err == nil {
- name = legal.ReplaceAllString(name, "")
- }
- for strings.Contains(name, "--") {
- name = strings.Replace(name, "--", "-", -1)
- }
- return name
-}
-
-// NormalizeEmail canonicalize an email address.
-// The local part of the email address is lowercased for all domains; the hostname is always lowercased and
-// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail).
-// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and
-// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are
-// normalized to @gmail.com.
-func NormalizeEmail(str string) (string, error) {
- if !IsEmail(str) {
- return "", fmt.Errorf("%s is not an email", str)
- }
- parts := strings.Split(str, "@")
- parts[0] = strings.ToLower(parts[0])
- parts[1] = strings.ToLower(parts[1])
- if parts[1] == "gmail.com" || parts[1] == "googlemail.com" {
- parts[1] = "gmail.com"
- parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0]
- }
- return strings.Join(parts, "@"), nil
-}
-
-// Truncate a string to the closest length without breaking words.
-func Truncate(str string, length int, ending string) string {
- var aftstr, befstr string
- if len(str) > length {
- words := strings.Fields(str)
- before, present := 0, 0
- for i := range words {
- befstr = aftstr
- before = present
- aftstr = aftstr + words[i] + " "
- present = len(aftstr)
- if present > length && i != 0 {
- if (length - before) < (present - length) {
- return Trim(befstr, " /\\.,\"'#!?&@+-") + ending
- }
- return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending
- }
- }
- }
-
- return str
-}
-
-// PadLeft pads left side of a string if size of string is less then indicated pad length
-func PadLeft(str string, padStr string, padLen int) string {
- return buildPadStr(str, padStr, padLen, true, false)
-}
-
-// PadRight pads right side of a string if size of string is less then indicated pad length
-func PadRight(str string, padStr string, padLen int) string {
- return buildPadStr(str, padStr, padLen, false, true)
-}
-
-// PadBoth pads both sides of a string if size of string is less then indicated pad length
-func PadBoth(str string, padStr string, padLen int) string {
- return buildPadStr(str, padStr, padLen, true, true)
-}
-
-// PadString either left, right or both sides.
-// Note that padding string can be unicode and more then one character
-func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string {
-
- // When padded length is less then the current string size
- if padLen < utf8.RuneCountInString(str) {
- return str
- }
-
- padLen -= utf8.RuneCountInString(str)
-
- targetLen := padLen
-
- targetLenLeft := targetLen
- targetLenRight := targetLen
- if padLeft && padRight {
- targetLenLeft = padLen / 2
- targetLenRight = padLen - targetLenLeft
- }
-
- strToRepeatLen := utf8.RuneCountInString(padStr)
-
- repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen)))
- repeatedString := strings.Repeat(padStr, repeatTimes)
-
- leftSide := ""
- if padLeft {
- leftSide = repeatedString[0:targetLenLeft]
- }
-
- rightSide := ""
- if padRight {
- rightSide = repeatedString[0:targetLenRight]
- }
-
- return leftSide + str + rightSide
-}
-
-// TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object
-func TruncatingErrorf(str string, args ...interface{}) error {
- n := strings.Count(str, "%s")
- return fmt.Errorf(str, args[:n]...)
-}
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/validator.go b/test/tools/vendor/github.com/asaskevich/govalidator/validator.go
deleted file mode 100644
index c9c4fac065..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/validator.go
+++ /dev/null
@@ -1,1768 +0,0 @@
-// Package govalidator is package of validators and sanitizers for strings, structs and collections.
-package govalidator
-
-import (
- "bytes"
- "crypto/rsa"
- "crypto/x509"
- "encoding/base64"
- "encoding/json"
- "encoding/pem"
- "fmt"
- "io/ioutil"
- "net"
- "net/url"
- "reflect"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "time"
- "unicode"
- "unicode/utf8"
-)
-
-var (
- fieldsRequiredByDefault bool
- nilPtrAllowedByRequired = false
- notNumberRegexp = regexp.MustCompile("[^0-9]+")
- whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`)
- paramsRegexp = regexp.MustCompile(`\(.*\)$`)
-)
-
-const maxURLRuneCount = 2083
-const minURLRuneCount = 3
-const rfc3339WithoutZone = "2006-01-02T15:04:05"
-
-// SetFieldsRequiredByDefault causes validation to fail when struct fields
-// do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`).
-// This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
-// type exampleStruct struct {
-// Name string ``
-// Email string `valid:"email"`
-// This, however, will only fail when Email is empty or an invalid email address:
-// type exampleStruct2 struct {
-// Name string `valid:"-"`
-// Email string `valid:"email"`
-// Lastly, this will only fail when Email is an invalid email address but not when it's empty:
-// type exampleStruct2 struct {
-// Name string `valid:"-"`
-// Email string `valid:"email,optional"`
-func SetFieldsRequiredByDefault(value bool) {
- fieldsRequiredByDefault = value
-}
-
-// SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required.
-// The validation will still reject ptr fields in their zero value state. Example with this enabled:
-// type exampleStruct struct {
-// Name *string `valid:"required"`
-// With `Name` set to "", this will be considered invalid input and will cause a validation error.
-// With `Name` set to nil, this will be considered valid by validation.
-// By default this is disabled.
-func SetNilPtrAllowedByRequired(value bool) {
- nilPtrAllowedByRequired = value
-}
-
-// IsEmail checks if the string is an email.
-func IsEmail(str string) bool {
- // TODO uppercase letters are not supported
- return rxEmail.MatchString(str)
-}
-
-// IsExistingEmail checks if the string is an email of existing domain
-func IsExistingEmail(email string) bool {
-
- if len(email) < 6 || len(email) > 254 {
- return false
- }
- at := strings.LastIndex(email, "@")
- if at <= 0 || at > len(email)-3 {
- return false
- }
- user := email[:at]
- host := email[at+1:]
- if len(user) > 64 {
- return false
- }
- switch host {
- case "localhost", "example.com":
- return true
- }
- if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) {
- return false
- }
- if _, err := net.LookupMX(host); err != nil {
- if _, err := net.LookupIP(host); err != nil {
- return false
- }
- }
-
- return true
-}
-
-// IsURL checks if the string is an URL.
-func IsURL(str string) bool {
- if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") {
- return false
- }
- strTemp := str
- if strings.Contains(str, ":") && !strings.Contains(str, "://") {
- // support no indicated urlscheme but with colon for port number
- // http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString
- strTemp = "http://" + str
- }
- u, err := url.Parse(strTemp)
- if err != nil {
- return false
- }
- if strings.HasPrefix(u.Host, ".") {
- return false
- }
- if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) {
- return false
- }
- return rxURL.MatchString(str)
-}
-
-// IsRequestURL checks if the string rawurl, assuming
-// it was received in an HTTP request, is a valid
-// URL confirm to RFC 3986
-func IsRequestURL(rawurl string) bool {
- url, err := url.ParseRequestURI(rawurl)
- if err != nil {
- return false //Couldn't even parse the rawurl
- }
- if len(url.Scheme) == 0 {
- return false //No Scheme found
- }
- return true
-}
-
-// IsRequestURI checks if the string rawurl, assuming
-// it was received in an HTTP request, is an
-// absolute URI or an absolute path.
-func IsRequestURI(rawurl string) bool {
- _, err := url.ParseRequestURI(rawurl)
- return err == nil
-}
-
-// IsAlpha checks if the string contains only letters (a-zA-Z). Empty string is valid.
-func IsAlpha(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxAlpha.MatchString(str)
-}
-
-//IsUTFLetter checks if the string contains only unicode letter characters.
-//Similar to IsAlpha but for all languages. Empty string is valid.
-func IsUTFLetter(str string) bool {
- if IsNull(str) {
- return true
- }
-
- for _, c := range str {
- if !unicode.IsLetter(c) {
- return false
- }
- }
- return true
-
-}
-
-// IsAlphanumeric checks if the string contains only letters and numbers. Empty string is valid.
-func IsAlphanumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxAlphanumeric.MatchString(str)
-}
-
-// IsUTFLetterNumeric checks if the string contains only unicode letters and numbers. Empty string is valid.
-func IsUTFLetterNumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- for _, c := range str {
- if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok
- return false
- }
- }
- return true
-
-}
-
-// IsNumeric checks if the string contains only numbers. Empty string is valid.
-func IsNumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxNumeric.MatchString(str)
-}
-
-// IsUTFNumeric checks if the string contains only unicode numbers of any kind.
-// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid.
-func IsUTFNumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- if strings.IndexAny(str, "+-") > 0 {
- return false
- }
- if len(str) > 1 {
- str = strings.TrimPrefix(str, "-")
- str = strings.TrimPrefix(str, "+")
- }
- for _, c := range str {
- if !unicode.IsNumber(c) { //numbers && minus sign are ok
- return false
- }
- }
- return true
-
-}
-
-// IsUTFDigit checks if the string contains only unicode radix-10 decimal digits. Empty string is valid.
-func IsUTFDigit(str string) bool {
- if IsNull(str) {
- return true
- }
- if strings.IndexAny(str, "+-") > 0 {
- return false
- }
- if len(str) > 1 {
- str = strings.TrimPrefix(str, "-")
- str = strings.TrimPrefix(str, "+")
- }
- for _, c := range str {
- if !unicode.IsDigit(c) { //digits && minus sign are ok
- return false
- }
- }
- return true
-
-}
-
-// IsHexadecimal checks if the string is a hexadecimal number.
-func IsHexadecimal(str string) bool {
- return rxHexadecimal.MatchString(str)
-}
-
-// IsHexcolor checks if the string is a hexadecimal color.
-func IsHexcolor(str string) bool {
- return rxHexcolor.MatchString(str)
-}
-
-// IsRGBcolor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB).
-func IsRGBcolor(str string) bool {
- return rxRGBcolor.MatchString(str)
-}
-
-// IsLowerCase checks if the string is lowercase. Empty string is valid.
-func IsLowerCase(str string) bool {
- if IsNull(str) {
- return true
- }
- return str == strings.ToLower(str)
-}
-
-// IsUpperCase checks if the string is uppercase. Empty string is valid.
-func IsUpperCase(str string) bool {
- if IsNull(str) {
- return true
- }
- return str == strings.ToUpper(str)
-}
-
-// HasLowerCase checks if the string contains at least 1 lowercase. Empty string is valid.
-func HasLowerCase(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxHasLowerCase.MatchString(str)
-}
-
-// HasUpperCase checks if the string contains as least 1 uppercase. Empty string is valid.
-func HasUpperCase(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxHasUpperCase.MatchString(str)
-}
-
-// IsInt checks if the string is an integer. Empty string is valid.
-func IsInt(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxInt.MatchString(str)
-}
-
-// IsFloat checks if the string is a float.
-func IsFloat(str string) bool {
- return str != "" && rxFloat.MatchString(str)
-}
-
-// IsDivisibleBy checks if the string is a number that's divisible by another.
-// If second argument is not valid integer or zero, it's return false.
-// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero).
-func IsDivisibleBy(str, num string) bool {
- f, _ := ToFloat(str)
- p := int64(f)
- q, _ := ToInt(num)
- if q == 0 {
- return false
- }
- return (p == 0) || (p%q == 0)
-}
-
-// IsNull checks if the string is null.
-func IsNull(str string) bool {
- return len(str) == 0
-}
-
-// IsNotNull checks if the string is not null.
-func IsNotNull(str string) bool {
- return !IsNull(str)
-}
-
-// HasWhitespaceOnly checks the string only contains whitespace
-func HasWhitespaceOnly(str string) bool {
- return len(str) > 0 && rxHasWhitespaceOnly.MatchString(str)
-}
-
-// HasWhitespace checks if the string contains any whitespace
-func HasWhitespace(str string) bool {
- return len(str) > 0 && rxHasWhitespace.MatchString(str)
-}
-
-// IsByteLength checks if the string's length (in bytes) falls in a range.
-func IsByteLength(str string, min, max int) bool {
- return len(str) >= min && len(str) <= max
-}
-
-// IsUUIDv3 checks if the string is a UUID version 3.
-func IsUUIDv3(str string) bool {
- return rxUUID3.MatchString(str)
-}
-
-// IsUUIDv4 checks if the string is a UUID version 4.
-func IsUUIDv4(str string) bool {
- return rxUUID4.MatchString(str)
-}
-
-// IsUUIDv5 checks if the string is a UUID version 5.
-func IsUUIDv5(str string) bool {
- return rxUUID5.MatchString(str)
-}
-
-// IsUUID checks if the string is a UUID (version 3, 4 or 5).
-func IsUUID(str string) bool {
- return rxUUID.MatchString(str)
-}
-
-// Byte to index table for O(1) lookups when unmarshaling.
-// We use 0xFF as sentinel value for invalid indexes.
-var ulidDec = [...]byte{
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01,
- 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
- 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF,
- 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E,
- 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C,
- 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14,
- 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C,
- 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-}
-
-// EncodedSize is the length of a text encoded ULID.
-const ulidEncodedSize = 26
-
-// IsULID checks if the string is a ULID.
-//
-// Implementation got from:
-// https://github.com/oklog/ulid (Apache-2.0 License)
-//
-func IsULID(str string) bool {
- // Check if a base32 encoded ULID is the right length.
- if len(str) != ulidEncodedSize {
- return false
- }
-
- // Check if all the characters in a base32 encoded ULID are part of the
- // expected base32 character set.
- if ulidDec[str[0]] == 0xFF ||
- ulidDec[str[1]] == 0xFF ||
- ulidDec[str[2]] == 0xFF ||
- ulidDec[str[3]] == 0xFF ||
- ulidDec[str[4]] == 0xFF ||
- ulidDec[str[5]] == 0xFF ||
- ulidDec[str[6]] == 0xFF ||
- ulidDec[str[7]] == 0xFF ||
- ulidDec[str[8]] == 0xFF ||
- ulidDec[str[9]] == 0xFF ||
- ulidDec[str[10]] == 0xFF ||
- ulidDec[str[11]] == 0xFF ||
- ulidDec[str[12]] == 0xFF ||
- ulidDec[str[13]] == 0xFF ||
- ulidDec[str[14]] == 0xFF ||
- ulidDec[str[15]] == 0xFF ||
- ulidDec[str[16]] == 0xFF ||
- ulidDec[str[17]] == 0xFF ||
- ulidDec[str[18]] == 0xFF ||
- ulidDec[str[19]] == 0xFF ||
- ulidDec[str[20]] == 0xFF ||
- ulidDec[str[21]] == 0xFF ||
- ulidDec[str[22]] == 0xFF ||
- ulidDec[str[23]] == 0xFF ||
- ulidDec[str[24]] == 0xFF ||
- ulidDec[str[25]] == 0xFF {
- return false
- }
-
- // Check if the first character in a base32 encoded ULID will overflow. This
- // happens because the base32 representation encodes 130 bits, while the
- // ULID is only 128 bits.
- //
- // See https://github.com/oklog/ulid/issues/9 for details.
- if str[0] > '7' {
- return false
- }
- return true
-}
-
-// IsCreditCard checks if the string is a credit card.
-func IsCreditCard(str string) bool {
- sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "")
- if !rxCreditCard.MatchString(sanitized) {
- return false
- }
-
- number, _ := ToInt(sanitized)
- number, lastDigit := number / 10, number % 10
-
- var sum int64
- for i:=0; number > 0; i++ {
- digit := number % 10
-
- if i % 2 == 0 {
- digit *= 2
- if digit > 9 {
- digit -= 9
- }
- }
-
- sum += digit
- number = number / 10
- }
-
- return (sum + lastDigit) % 10 == 0
-}
-
-// IsISBN10 checks if the string is an ISBN version 10.
-func IsISBN10(str string) bool {
- return IsISBN(str, 10)
-}
-
-// IsISBN13 checks if the string is an ISBN version 13.
-func IsISBN13(str string) bool {
- return IsISBN(str, 13)
-}
-
-// IsISBN checks if the string is an ISBN (version 10 or 13).
-// If version value is not equal to 10 or 13, it will be checks both variants.
-func IsISBN(str string, version int) bool {
- sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "")
- var checksum int32
- var i int32
- if version == 10 {
- if !rxISBN10.MatchString(sanitized) {
- return false
- }
- for i = 0; i < 9; i++ {
- checksum += (i + 1) * int32(sanitized[i]-'0')
- }
- if sanitized[9] == 'X' {
- checksum += 10 * 10
- } else {
- checksum += 10 * int32(sanitized[9]-'0')
- }
- if checksum%11 == 0 {
- return true
- }
- return false
- } else if version == 13 {
- if !rxISBN13.MatchString(sanitized) {
- return false
- }
- factor := []int32{1, 3}
- for i = 0; i < 12; i++ {
- checksum += factor[i%2] * int32(sanitized[i]-'0')
- }
- return (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0
- }
- return IsISBN(str, 10) || IsISBN(str, 13)
-}
-
-// IsJSON checks if the string is valid JSON (note: uses json.Unmarshal).
-func IsJSON(str string) bool {
- var js json.RawMessage
- return json.Unmarshal([]byte(str), &js) == nil
-}
-
-// IsMultibyte checks if the string contains one or more multibyte chars. Empty string is valid.
-func IsMultibyte(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxMultibyte.MatchString(str)
-}
-
-// IsASCII checks if the string contains ASCII chars only. Empty string is valid.
-func IsASCII(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxASCII.MatchString(str)
-}
-
-// IsPrintableASCII checks if the string contains printable ASCII chars only. Empty string is valid.
-func IsPrintableASCII(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxPrintableASCII.MatchString(str)
-}
-
-// IsFullWidth checks if the string contains any full-width chars. Empty string is valid.
-func IsFullWidth(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxFullWidth.MatchString(str)
-}
-
-// IsHalfWidth checks if the string contains any half-width chars. Empty string is valid.
-func IsHalfWidth(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxHalfWidth.MatchString(str)
-}
-
-// IsVariableWidth checks if the string contains a mixture of full and half-width chars. Empty string is valid.
-func IsVariableWidth(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str)
-}
-
-// IsBase64 checks if a string is base64 encoded.
-func IsBase64(str string) bool {
- return rxBase64.MatchString(str)
-}
-
-// IsFilePath checks is a string is Win or Unix file path and returns it's type.
-func IsFilePath(str string) (bool, int) {
- if rxWinPath.MatchString(str) {
- //check windows path limit see:
- // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
- if len(str[3:]) > 32767 {
- return false, Win
- }
- return true, Win
- } else if rxUnixPath.MatchString(str) {
- return true, Unix
- }
- return false, Unknown
-}
-
-//IsWinFilePath checks both relative & absolute paths in Windows
-func IsWinFilePath(str string) bool {
- if rxARWinPath.MatchString(str) {
- //check windows path limit see:
- // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
- if len(str[3:]) > 32767 {
- return false
- }
- return true
- }
- return false
-}
-
-//IsUnixFilePath checks both relative & absolute paths in Unix
-func IsUnixFilePath(str string) bool {
- if rxARUnixPath.MatchString(str) {
- return true
- }
- return false
-}
-
-// IsDataURI checks if a string is base64 encoded data URI such as an image
-func IsDataURI(str string) bool {
- dataURI := strings.Split(str, ",")
- if !rxDataURI.MatchString(dataURI[0]) {
- return false
- }
- return IsBase64(dataURI[1])
-}
-
-// IsMagnetURI checks if a string is valid magnet URI
-func IsMagnetURI(str string) bool {
- return rxMagnetURI.MatchString(str)
-}
-
-// IsISO3166Alpha2 checks if a string is valid two-letter country code
-func IsISO3166Alpha2(str string) bool {
- for _, entry := range ISO3166List {
- if str == entry.Alpha2Code {
- return true
- }
- }
- return false
-}
-
-// IsISO3166Alpha3 checks if a string is valid three-letter country code
-func IsISO3166Alpha3(str string) bool {
- for _, entry := range ISO3166List {
- if str == entry.Alpha3Code {
- return true
- }
- }
- return false
-}
-
-// IsISO693Alpha2 checks if a string is valid two-letter language code
-func IsISO693Alpha2(str string) bool {
- for _, entry := range ISO693List {
- if str == entry.Alpha2Code {
- return true
- }
- }
- return false
-}
-
-// IsISO693Alpha3b checks if a string is valid three-letter language code
-func IsISO693Alpha3b(str string) bool {
- for _, entry := range ISO693List {
- if str == entry.Alpha3bCode {
- return true
- }
- }
- return false
-}
-
-// IsDNSName will validate the given string as a DNS name
-func IsDNSName(str string) bool {
- if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 {
- // constraints already violated
- return false
- }
- return !IsIP(str) && rxDNSName.MatchString(str)
-}
-
-// IsHash checks if a string is a hash of type algorithm.
-// Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']
-func IsHash(str string, algorithm string) bool {
- var len string
- algo := strings.ToLower(algorithm)
-
- if algo == "crc32" || algo == "crc32b" {
- len = "8"
- } else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" {
- len = "32"
- } else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" {
- len = "40"
- } else if algo == "tiger192" {
- len = "48"
- } else if algo == "sha3-224" {
- len = "56"
- } else if algo == "sha256" || algo == "sha3-256" {
- len = "64"
- } else if algo == "sha384" || algo == "sha3-384" {
- len = "96"
- } else if algo == "sha512" || algo == "sha3-512" {
- len = "128"
- } else {
- return false
- }
-
- return Matches(str, "^[a-f0-9]{"+len+"}$")
-}
-
-// IsSHA3224 checks is a string is a SHA3-224 hash. Alias for `IsHash(str, "sha3-224")`
-func IsSHA3224(str string) bool {
- return IsHash(str, "sha3-224")
-}
-
-// IsSHA3256 checks is a string is a SHA3-256 hash. Alias for `IsHash(str, "sha3-256")`
-func IsSHA3256(str string) bool {
- return IsHash(str, "sha3-256")
-}
-
-// IsSHA3384 checks is a string is a SHA3-384 hash. Alias for `IsHash(str, "sha3-384")`
-func IsSHA3384(str string) bool {
- return IsHash(str, "sha3-384")
-}
-
-// IsSHA3512 checks is a string is a SHA3-512 hash. Alias for `IsHash(str, "sha3-512")`
-func IsSHA3512(str string) bool {
- return IsHash(str, "sha3-512")
-}
-
-// IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(str, "sha512")`
-func IsSHA512(str string) bool {
- return IsHash(str, "sha512")
-}
-
-// IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(str, "sha384")`
-func IsSHA384(str string) bool {
- return IsHash(str, "sha384")
-}
-
-// IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(str, "sha256")`
-func IsSHA256(str string) bool {
- return IsHash(str, "sha256")
-}
-
-// IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")`
-func IsTiger192(str string) bool {
- return IsHash(str, "tiger192")
-}
-
-// IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")`
-func IsTiger160(str string) bool {
- return IsHash(str, "tiger160")
-}
-
-// IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")`
-func IsRipeMD160(str string) bool {
- return IsHash(str, "ripemd160")
-}
-
-// IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(str, "sha1")`
-func IsSHA1(str string) bool {
- return IsHash(str, "sha1")
-}
-
-// IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")`
-func IsTiger128(str string) bool {
- return IsHash(str, "tiger128")
-}
-
-// IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(str, "ripemd128")`
-func IsRipeMD128(str string) bool {
- return IsHash(str, "ripemd128")
-}
-
-// IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")`
-func IsCRC32(str string) bool {
- return IsHash(str, "crc32")
-}
-
-// IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(str, "crc32b")`
-func IsCRC32b(str string) bool {
- return IsHash(str, "crc32b")
-}
-
-// IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(str, "md5")`
-func IsMD5(str string) bool {
- return IsHash(str, "md5")
-}
-
-// IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(str, "md4")`
-func IsMD4(str string) bool {
- return IsHash(str, "md4")
-}
-
-// IsDialString validates the given string for usage with the various Dial() functions
-func IsDialString(str string) bool {
- if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) {
- return true
- }
-
- return false
-}
-
-// IsIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP`
-func IsIP(str string) bool {
- return net.ParseIP(str) != nil
-}
-
-// IsPort checks if a string represents a valid port
-func IsPort(str string) bool {
- if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 {
- return true
- }
- return false
-}
-
-// IsIPv4 checks if the string is an IP version 4.
-func IsIPv4(str string) bool {
- ip := net.ParseIP(str)
- return ip != nil && strings.Contains(str, ".")
-}
-
-// IsIPv6 checks if the string is an IP version 6.
-func IsIPv6(str string) bool {
- ip := net.ParseIP(str)
- return ip != nil && strings.Contains(str, ":")
-}
-
-// IsCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6)
-func IsCIDR(str string) bool {
- _, _, err := net.ParseCIDR(str)
- return err == nil
-}
-
-// IsMAC checks if a string is valid MAC address.
-// Possible MAC formats:
-// 01:23:45:67:89:ab
-// 01:23:45:67:89:ab:cd:ef
-// 01-23-45-67-89-ab
-// 01-23-45-67-89-ab-cd-ef
-// 0123.4567.89ab
-// 0123.4567.89ab.cdef
-func IsMAC(str string) bool {
- _, err := net.ParseMAC(str)
- return err == nil
-}
-
-// IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name
-func IsHost(str string) bool {
- return IsIP(str) || IsDNSName(str)
-}
-
-// IsMongoID checks if the string is a valid hex-encoded representation of a MongoDB ObjectId.
-func IsMongoID(str string) bool {
- return rxHexadecimal.MatchString(str) && (len(str) == 24)
-}
-
-// IsLatitude checks if a string is valid latitude.
-func IsLatitude(str string) bool {
- return rxLatitude.MatchString(str)
-}
-
-// IsLongitude checks if a string is valid longitude.
-func IsLongitude(str string) bool {
- return rxLongitude.MatchString(str)
-}
-
-// IsIMEI checks if a string is valid IMEI
-func IsIMEI(str string) bool {
- return rxIMEI.MatchString(str)
-}
-
-// IsIMSI checks if a string is valid IMSI
-func IsIMSI(str string) bool {
- if !rxIMSI.MatchString(str) {
- return false
- }
-
- mcc, err := strconv.ParseInt(str[0:3], 10, 32)
- if err != nil {
- return false
- }
-
- switch mcc {
- case 202, 204, 206, 208, 212, 213, 214, 216, 218, 219:
- case 220, 221, 222, 226, 228, 230, 231, 232, 234, 235:
- case 238, 240, 242, 244, 246, 247, 248, 250, 255, 257:
- case 259, 260, 262, 266, 268, 270, 272, 274, 276, 278:
- case 280, 282, 283, 284, 286, 288, 289, 290, 292, 293:
- case 294, 295, 297, 302, 308, 310, 311, 312, 313, 314:
- case 315, 316, 330, 332, 334, 338, 340, 342, 344, 346:
- case 348, 350, 352, 354, 356, 358, 360, 362, 363, 364:
- case 365, 366, 368, 370, 372, 374, 376, 400, 401, 402:
- case 404, 405, 406, 410, 412, 413, 414, 415, 416, 417:
- case 418, 419, 420, 421, 422, 424, 425, 426, 427, 428:
- case 429, 430, 431, 432, 434, 436, 437, 438, 440, 441:
- case 450, 452, 454, 455, 456, 457, 460, 461, 466, 467:
- case 470, 472, 502, 505, 510, 514, 515, 520, 525, 528:
- case 530, 536, 537, 539, 540, 541, 542, 543, 544, 545:
- case 546, 547, 548, 549, 550, 551, 552, 553, 554, 555:
- case 602, 603, 604, 605, 606, 607, 608, 609, 610, 611:
- case 612, 613, 614, 615, 616, 617, 618, 619, 620, 621:
- case 622, 623, 624, 625, 626, 627, 628, 629, 630, 631:
- case 632, 633, 634, 635, 636, 637, 638, 639, 640, 641:
- case 642, 643, 645, 646, 647, 648, 649, 650, 651, 652:
- case 653, 654, 655, 657, 658, 659, 702, 704, 706, 708:
- case 710, 712, 714, 716, 722, 724, 730, 732, 734, 736:
- case 738, 740, 742, 744, 746, 748, 750, 995:
- return true
- default:
- return false
- }
- return true
-}
-
-// IsRsaPublicKey checks if a string is valid public key with provided length
-func IsRsaPublicKey(str string, keylen int) bool {
- bb := bytes.NewBufferString(str)
- pemBytes, err := ioutil.ReadAll(bb)
- if err != nil {
- return false
- }
- block, _ := pem.Decode(pemBytes)
- if block != nil && block.Type != "PUBLIC KEY" {
- return false
- }
- var der []byte
-
- if block != nil {
- der = block.Bytes
- } else {
- der, err = base64.StdEncoding.DecodeString(str)
- if err != nil {
- return false
- }
- }
-
- key, err := x509.ParsePKIXPublicKey(der)
- if err != nil {
- return false
- }
- pubkey, ok := key.(*rsa.PublicKey)
- if !ok {
- return false
- }
- bitlen := len(pubkey.N.Bytes()) * 8
- return bitlen == int(keylen)
-}
-
-// IsRegex checks if a give string is a valid regex with RE2 syntax or not
-func IsRegex(str string) bool {
- if _, err := regexp.Compile(str); err == nil {
- return true
- }
- return false
-}
-
-func toJSONName(tag string) string {
- if tag == "" {
- return ""
- }
-
- // JSON name always comes first. If there's no options then split[0] is
- // JSON name, if JSON name is not set, then split[0] is an empty string.
- split := strings.SplitN(tag, ",", 2)
-
- name := split[0]
-
- // However it is possible that the field is skipped when
- // (de-)serializing from/to JSON, in which case assume that there is no
- // tag name to use
- if name == "-" {
- return ""
- }
- return name
-}
-
-func prependPathToErrors(err error, path string) error {
- switch err2 := err.(type) {
- case Error:
- err2.Path = append([]string{path}, err2.Path...)
- return err2
- case Errors:
- errors := err2.Errors()
- for i, err3 := range errors {
- errors[i] = prependPathToErrors(err3, path)
- }
- return err2
- }
- return err
-}
-
-// ValidateArray performs validation according to condition iterator that validates every element of the array
-func ValidateArray(array []interface{}, iterator ConditionIterator) bool {
- return Every(array, iterator)
-}
-
-// ValidateMap use validation map for fields.
-// result will be equal to `false` if there are any errors.
-// s is the map containing the data to be validated.
-// m is the validation map in the form:
-// map[string]interface{}{"name":"required,alpha","address":map[string]interface{}{"line1":"required,alphanum"}}
-func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, error) {
- if s == nil {
- return true, nil
- }
- result := true
- var err error
- var errs Errors
- var index int
- val := reflect.ValueOf(s)
- for key, value := range s {
- presentResult := true
- validator, ok := m[key]
- if !ok {
- presentResult = false
- var err error
- err = fmt.Errorf("all map keys has to be present in the validation map; got %s", key)
- err = prependPathToErrors(err, key)
- errs = append(errs, err)
- }
- valueField := reflect.ValueOf(value)
- mapResult := true
- typeResult := true
- structResult := true
- resultField := true
- switch subValidator := validator.(type) {
- case map[string]interface{}:
- var err error
- if v, ok := value.(map[string]interface{}); !ok {
- mapResult = false
- err = fmt.Errorf("map validator has to be for the map type only; got %s", valueField.Type().String())
- err = prependPathToErrors(err, key)
- errs = append(errs, err)
- } else {
- mapResult, err = ValidateMap(v, subValidator)
- if err != nil {
- mapResult = false
- err = prependPathToErrors(err, key)
- errs = append(errs, err)
- }
- }
- case string:
- if (valueField.Kind() == reflect.Struct ||
- (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) &&
- subValidator != "-" {
- var err error
- structResult, err = ValidateStruct(valueField.Interface())
- if err != nil {
- err = prependPathToErrors(err, key)
- errs = append(errs, err)
- }
- }
- resultField, err = typeCheck(valueField, reflect.StructField{
- Name: key,
- PkgPath: "",
- Type: val.Type(),
- Tag: reflect.StructTag(fmt.Sprintf("%s:%q", tagName, subValidator)),
- Offset: 0,
- Index: []int{index},
- Anonymous: false,
- }, val, nil)
- if err != nil {
- errs = append(errs, err)
- }
- case nil:
- // already handlerd when checked before
- default:
- typeResult = false
- err = fmt.Errorf("map validator has to be either map[string]interface{} or string; got %s", valueField.Type().String())
- err = prependPathToErrors(err, key)
- errs = append(errs, err)
- }
- result = result && presentResult && typeResult && resultField && structResult && mapResult
- index++
- }
- // checks required keys
- requiredResult := true
- for key, value := range m {
- if schema, ok := value.(string); ok {
- tags := parseTagIntoMap(schema)
- if required, ok := tags["required"]; ok {
- if _, ok := s[key]; !ok {
- requiredResult = false
- if required.customErrorMessage != "" {
- err = Error{key, fmt.Errorf(required.customErrorMessage), true, "required", []string{}}
- } else {
- err = Error{key, fmt.Errorf("required field missing"), false, "required", []string{}}
- }
- errs = append(errs, err)
- }
- }
- }
- }
-
- if len(errs) > 0 {
- err = errs
- }
- return result && requiredResult, err
-}
-
-// ValidateStruct use tags for fields.
-// result will be equal to `false` if there are any errors.
-// todo currently there is no guarantee that errors will be returned in predictable order (tests may to fail)
-func ValidateStruct(s interface{}) (bool, error) {
- if s == nil {
- return true, nil
- }
- result := true
- var err error
- val := reflect.ValueOf(s)
- if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
- val = val.Elem()
- }
- // we only accept structs
- if val.Kind() != reflect.Struct {
- return false, fmt.Errorf("function only accepts structs; got %s", val.Kind())
- }
- var errs Errors
- for i := 0; i < val.NumField(); i++ {
- valueField := val.Field(i)
- typeField := val.Type().Field(i)
- if typeField.PkgPath != "" {
- continue // Private field
- }
- structResult := true
- if valueField.Kind() == reflect.Interface {
- valueField = valueField.Elem()
- }
- if (valueField.Kind() == reflect.Struct ||
- (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) &&
- typeField.Tag.Get(tagName) != "-" {
- var err error
- structResult, err = ValidateStruct(valueField.Interface())
- if err != nil {
- err = prependPathToErrors(err, typeField.Name)
- errs = append(errs, err)
- }
- }
- resultField, err2 := typeCheck(valueField, typeField, val, nil)
- if err2 != nil {
-
- // Replace structure name with JSON name if there is a tag on the variable
- jsonTag := toJSONName(typeField.Tag.Get("json"))
- if jsonTag != "" {
- switch jsonError := err2.(type) {
- case Error:
- jsonError.Name = jsonTag
- err2 = jsonError
- case Errors:
- for i2, err3 := range jsonError {
- switch customErr := err3.(type) {
- case Error:
- customErr.Name = jsonTag
- jsonError[i2] = customErr
- }
- }
-
- err2 = jsonError
- }
- }
-
- errs = append(errs, err2)
- }
- result = result && resultField && structResult
- }
- if len(errs) > 0 {
- err = errs
- }
- return result, err
-}
-
-// ValidateStructAsync performs async validation of the struct and returns results through the channels
-func ValidateStructAsync(s interface{}) (<-chan bool, <-chan error) {
- res := make(chan bool)
- errors := make(chan error)
-
- go func() {
- defer close(res)
- defer close(errors)
-
- isValid, isFailed := ValidateStruct(s)
-
- res <- isValid
- errors <- isFailed
- }()
-
- return res, errors
-}
-
-// ValidateMapAsync performs async validation of the map and returns results through the channels
-func ValidateMapAsync(s map[string]interface{}, m map[string]interface{}) (<-chan bool, <-chan error) {
- res := make(chan bool)
- errors := make(chan error)
-
- go func() {
- defer close(res)
- defer close(errors)
-
- isValid, isFailed := ValidateMap(s, m)
-
- res <- isValid
- errors <- isFailed
- }()
-
- return res, errors
-}
-
-// parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""}
-func parseTagIntoMap(tag string) tagOptionsMap {
- optionsMap := make(tagOptionsMap)
- options := strings.Split(tag, ",")
-
- for i, option := range options {
- option = strings.TrimSpace(option)
-
- validationOptions := strings.Split(option, "~")
- if !isValidTag(validationOptions[0]) {
- continue
- }
- if len(validationOptions) == 2 {
- optionsMap[validationOptions[0]] = tagOption{validationOptions[0], validationOptions[1], i}
- } else {
- optionsMap[validationOptions[0]] = tagOption{validationOptions[0], "", i}
- }
- }
- return optionsMap
-}
-
-func isValidTag(s string) bool {
- if s == "" {
- return false
- }
- for _, c := range s {
- switch {
- case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
- // Backslash and quote chars are reserved, but
- // otherwise any punctuation chars are allowed
- // in a tag name.
- default:
- if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
- return false
- }
- }
- }
- return true
-}
-
-// 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
- }
- return rxSSN.MatchString(str)
-}
-
-// IsSemver checks if string is valid semantic version
-func IsSemver(str string) bool {
- return rxSemver.MatchString(str)
-}
-
-// IsType checks if interface is of some type
-func IsType(v interface{}, params ...string) bool {
- if len(params) == 1 {
- typ := params[0]
- return strings.Replace(reflect.TypeOf(v).String(), " ", "", -1) == strings.Replace(typ, " ", "", -1)
- }
- return false
-}
-
-// IsTime checks if string is valid according to given format
-func IsTime(str string, format string) bool {
- _, err := time.Parse(format, str)
- return err == nil
-}
-
-// IsUnixTime checks if string is valid unix timestamp value
-func IsUnixTime(str string) bool {
- if _, err := strconv.Atoi(str); err == nil {
- return true
- }
- return false
-}
-
-// IsRFC3339 checks if string is valid timestamp value according to RFC3339
-func IsRFC3339(str string) bool {
- return IsTime(str, time.RFC3339)
-}
-
-// IsRFC3339WithoutZone checks if string is valid timestamp value according to RFC3339 which excludes the timezone.
-func IsRFC3339WithoutZone(str string) bool {
- return IsTime(str, rfc3339WithoutZone)
-}
-
-// IsISO4217 checks if string is valid ISO currency code
-func IsISO4217(str string) bool {
- for _, currency := range ISO4217List {
- if str == currency {
- return true
- }
- }
-
- return false
-}
-
-// ByteLength checks string's length
-func ByteLength(str string, params ...string) bool {
- if len(params) == 2 {
- min, _ := ToInt(params[0])
- max, _ := ToInt(params[1])
- return len(str) >= int(min) && len(str) <= int(max)
- }
-
- return false
-}
-
-// RuneLength checks string's length
-// Alias for StringLength
-func RuneLength(str string, params ...string) bool {
- return StringLength(str, params...)
-}
-
-// IsRsaPub checks whether string is valid RSA key
-// Alias for IsRsaPublicKey
-func IsRsaPub(str string, params ...string) bool {
- if len(params) == 1 {
- len, _ := ToInt(params[0])
- return IsRsaPublicKey(str, int(len))
- }
-
- return false
-}
-
-// StringMatches checks if a string matches a given pattern.
-func StringMatches(s string, params ...string) bool {
- if len(params) == 1 {
- pattern := params[0]
- return Matches(s, pattern)
- }
- return false
-}
-
-// StringLength checks string's length (including multi byte strings)
-func StringLength(str string, params ...string) bool {
-
- if len(params) == 2 {
- strLength := utf8.RuneCountInString(str)
- min, _ := ToInt(params[0])
- max, _ := ToInt(params[1])
- return strLength >= int(min) && strLength <= int(max)
- }
-
- return false
-}
-
-// MinStringLength checks string's minimum length (including multi byte strings)
-func MinStringLength(str string, params ...string) bool {
-
- if len(params) == 1 {
- strLength := utf8.RuneCountInString(str)
- min, _ := ToInt(params[0])
- return strLength >= int(min)
- }
-
- return false
-}
-
-// MaxStringLength checks string's maximum length (including multi byte strings)
-func MaxStringLength(str string, params ...string) bool {
-
- if len(params) == 1 {
- strLength := utf8.RuneCountInString(str)
- max, _ := ToInt(params[0])
- return strLength <= int(max)
- }
-
- return false
-}
-
-// Range checks string's length
-func Range(str string, params ...string) bool {
- if len(params) == 2 {
- value, _ := ToFloat(str)
- min, _ := ToFloat(params[0])
- max, _ := ToFloat(params[1])
- return InRange(value, min, max)
- }
-
- return false
-}
-
-// IsInRaw checks if string is in list of allowed values
-func IsInRaw(str string, params ...string) bool {
- if len(params) == 1 {
- rawParams := params[0]
-
- parsedParams := strings.Split(rawParams, "|")
-
- return IsIn(str, parsedParams...)
- }
-
- return false
-}
-
-// IsIn checks if string str is a member of the set of strings params
-func IsIn(str string, params ...string) bool {
- for _, param := range params {
- if str == param {
- return true
- }
- }
-
- return false
-}
-
-func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) {
- if nilPtrAllowedByRequired {
- k := v.Kind()
- if (k == reflect.Ptr || k == reflect.Interface) && v.IsNil() {
- return true, nil
- }
- }
-
- if requiredOption, isRequired := options["required"]; isRequired {
- if len(requiredOption.customErrorMessage) > 0 {
- return false, Error{t.Name, fmt.Errorf(requiredOption.customErrorMessage), true, "required", []string{}}
- }
- return false, Error{t.Name, fmt.Errorf("non zero value required"), false, "required", []string{}}
- } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional {
- return false, Error{t.Name, fmt.Errorf("Missing required field"), false, "required", []string{}}
- }
- // not required and empty is valid
- return true, nil
-}
-
-func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) {
- if !v.IsValid() {
- return false, nil
- }
-
- tag := t.Tag.Get(tagName)
-
- // checks if the field should be ignored
- switch tag {
- case "":
- if v.Kind() != reflect.Slice && v.Kind() != reflect.Map {
- if !fieldsRequiredByDefault {
- return true, nil
- }
- return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false, "required", []string{}}
- }
- case "-":
- return true, nil
- }
-
- isRootType := false
- if options == nil {
- isRootType = true
- options = parseTagIntoMap(tag)
- }
-
- if isEmptyValue(v) {
- // an empty value is not validated, checks only required
- isValid, resultErr = checkRequired(v, t, options)
- for key := range options {
- delete(options, key)
- }
- return isValid, resultErr
- }
-
- var customTypeErrors Errors
- optionsOrder := options.orderedKeys()
- for _, validatorName := range optionsOrder {
- validatorStruct := options[validatorName]
- if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok {
- delete(options, validatorName)
-
- if result := validatefunc(v.Interface(), o.Interface()); !result {
- if len(validatorStruct.customErrorMessage) > 0 {
- customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: TruncatingErrorf(validatorStruct.customErrorMessage, fmt.Sprint(v), validatorName), CustomErrorMessageExists: true, Validator: stripParams(validatorName)})
- continue
- }
- customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false, Validator: stripParams(validatorName)})
- }
- }
- }
-
- if len(customTypeErrors.Errors()) > 0 {
- return false, customTypeErrors
- }
-
- if isRootType {
- // Ensure that we've checked the value by all specified validators before report that the value is valid
- defer func() {
- delete(options, "optional")
- delete(options, "required")
-
- if isValid && resultErr == nil && len(options) != 0 {
- optionsOrder := options.orderedKeys()
- for _, validator := range optionsOrder {
- isValid = false
- resultErr = Error{t.Name, fmt.Errorf(
- "The following validator is invalid or can't be applied to the field: %q", validator), false, stripParams(validator), []string{}}
- return
- }
- }
- }()
- }
-
- for _, validatorSpec := range optionsOrder {
- validatorStruct := options[validatorSpec]
- var negate bool
- validator := validatorSpec
- customMsgExists := len(validatorStruct.customErrorMessage) > 0
-
- // checks whether the tag looks like '!something' or 'something'
- if validator[0] == '!' {
- validator = validator[1:]
- negate = true
- }
-
- // checks for interface param validators
- for key, value := range InterfaceParamTagRegexMap {
- ps := value.FindStringSubmatch(validator)
- if len(ps) == 0 {
- continue
- }
-
- validatefunc, ok := InterfaceParamTagMap[key]
- if !ok {
- continue
- }
-
- delete(options, validatorSpec)
-
- field := fmt.Sprint(v)
- if result := validatefunc(v.Interface(), ps[1:]...); (!result && !negate) || (result && negate) {
- if customMsgExists {
- return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- if negate {
- return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- }
- }
-
- switch v.Kind() {
- case reflect.Bool,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
- reflect.Float32, reflect.Float64,
- reflect.String:
- // for each tag option checks the map of validator functions
- for _, validatorSpec := range optionsOrder {
- validatorStruct := options[validatorSpec]
- var negate bool
- validator := validatorSpec
- customMsgExists := len(validatorStruct.customErrorMessage) > 0
-
- // checks whether the tag looks like '!something' or 'something'
- if validator[0] == '!' {
- validator = validator[1:]
- negate = true
- }
-
- // checks for param validators
- for key, value := range ParamTagRegexMap {
- ps := value.FindStringSubmatch(validator)
- if len(ps) == 0 {
- continue
- }
-
- validatefunc, ok := ParamTagMap[key]
- if !ok {
- continue
- }
-
- delete(options, validatorSpec)
-
- switch v.Kind() {
- case reflect.String,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
- reflect.Float32, reflect.Float64:
-
- field := fmt.Sprint(v) // make value into string, then validate with regex
- if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) {
- if customMsgExists {
- return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- if negate {
- return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- default:
- // type not yet supported, fail
- return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false, stripParams(validatorSpec), []string{}}
- }
- }
-
- if validatefunc, ok := TagMap[validator]; ok {
- delete(options, validatorSpec)
-
- switch v.Kind() {
- case reflect.String,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
- reflect.Float32, reflect.Float64:
- field := fmt.Sprint(v) // make value into string, then validate with regex
- if result := validatefunc(field); !result && !negate || result && negate {
- if customMsgExists {
- return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- if negate {
- return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}}
- }
- default:
- //Not Yet Supported Types (Fail here!)
- err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v)
- return false, Error{t.Name, err, false, stripParams(validatorSpec), []string{}}
- }
- }
- }
- return true, nil
- case reflect.Map:
- if v.Type().Key().Kind() != reflect.String {
- return false, &UnsupportedTypeError{v.Type()}
- }
- var sv stringValues
- sv = v.MapKeys()
- sort.Sort(sv)
- result := true
- for i, k := range sv {
- var resultItem bool
- var err error
- if v.MapIndex(k).Kind() != reflect.Struct {
- resultItem, err = typeCheck(v.MapIndex(k), t, o, options)
- if err != nil {
- return false, err
- }
- } else {
- resultItem, err = ValidateStruct(v.MapIndex(k).Interface())
- if err != nil {
- err = prependPathToErrors(err, t.Name+"."+sv[i].Interface().(string))
- return false, err
- }
- }
- result = result && resultItem
- }
- return result, nil
- case reflect.Slice, reflect.Array:
- result := true
- for i := 0; i < v.Len(); i++ {
- var resultItem bool
- var err error
- if v.Index(i).Kind() != reflect.Struct {
- resultItem, err = typeCheck(v.Index(i), t, o, options)
- if err != nil {
- return false, err
- }
- } else {
- resultItem, err = ValidateStruct(v.Index(i).Interface())
- if err != nil {
- err = prependPathToErrors(err, t.Name+"."+strconv.Itoa(i))
- return false, err
- }
- }
- result = result && resultItem
- }
- return result, nil
- case reflect.Interface:
- // If the value is an interface then encode its element
- if v.IsNil() {
- return true, nil
- }
- return ValidateStruct(v.Interface())
- case reflect.Ptr:
- // If the value is a pointer then checks its element
- if v.IsNil() {
- return true, nil
- }
- return typeCheck(v.Elem(), t, o, options)
- case reflect.Struct:
- return true, nil
- default:
- return false, &UnsupportedTypeError{v.Type()}
- }
-}
-
-func stripParams(validatorString string) string {
- return paramsRegexp.ReplaceAllString(validatorString, "")
-}
-
-// isEmptyValue checks whether value empty or not
-func isEmptyValue(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.String, reflect.Array:
- return v.Len() == 0
- case reflect.Map, reflect.Slice:
- return v.Len() == 0 || v.IsNil()
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.Interface, reflect.Ptr:
- return v.IsNil()
- }
-
- return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
-}
-
-// ErrorByField returns error for specified field of the struct
-// validated by ValidateStruct or empty string if there are no errors
-// or this field doesn't exists or doesn't have any errors.
-func ErrorByField(e error, field string) string {
- if e == nil {
- return ""
- }
- return ErrorsByField(e)[field]
-}
-
-// ErrorsByField returns map of errors of the struct validated
-// by ValidateStruct or empty map if there are no errors.
-func ErrorsByField(e error) map[string]string {
- m := make(map[string]string)
- if e == nil {
- return m
- }
- // prototype for ValidateStruct
-
- switch e := e.(type) {
- case Error:
- m[e.Name] = e.Err.Error()
- case Errors:
- for _, item := range e.Errors() {
- n := ErrorsByField(item)
- for k, v := range n {
- m[k] = v
- }
- }
- }
-
- return m
-}
-
-// Error returns string equivalent for reflect.Type
-func (e *UnsupportedTypeError) Error() string {
- return "validator: unsupported type: " + e.Type.String()
-}
-
-func (sv stringValues) Len() int { return len(sv) }
-func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
-func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
-func (sv stringValues) get(i int) string { return sv[i].String() }
-
-func IsE164(str string) bool {
- return rxE164.MatchString(str)
-}
diff --git a/test/tools/vendor/github.com/asaskevich/govalidator/wercker.yml b/test/tools/vendor/github.com/asaskevich/govalidator/wercker.yml
deleted file mode 100644
index bc5f7b0864..0000000000
--- a/test/tools/vendor/github.com/asaskevich/govalidator/wercker.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-box: golang
-build:
- steps:
- - setup-go-workspace
-
- - script:
- name: go get
- code: |
- go version
- go get -t ./...
-
- - script:
- name: go test
- code: |
- go test -race -v ./...
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/.cirrus.yml b/test/tools/vendor/github.com/fsnotify/fsnotify/.cirrus.yml
index ffc7b992b3..7f257e99ac 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/.cirrus.yml
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/.cirrus.yml
@@ -1,7 +1,7 @@
freebsd_task:
name: 'FreeBSD'
freebsd_instance:
- image_family: freebsd-13-2
+ image_family: freebsd-14-2
install_script:
- pkg update -f
- pkg install -y go
@@ -9,5 +9,6 @@ freebsd_task:
# run tests as user "cirrus" instead of root
- pw useradd cirrus -m
- chown -R cirrus:cirrus .
- - FSNOTIFY_BUFFER=4096 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./...
- - sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./...
+ - FSNOTIFY_BUFFER=4096 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./...
+ - sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./...
+ - FSNOTIFY_DEBUG=1 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race -v ./...
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/.gitattributes b/test/tools/vendor/github.com/fsnotify/fsnotify/.gitattributes
deleted file mode 100644
index 32f1001be0..0000000000
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-go.sum linguist-generated
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/.gitignore b/test/tools/vendor/github.com/fsnotify/fsnotify/.gitignore
index 391cc076b1..daea9dd6d6 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/.gitignore
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/.gitignore
@@ -5,3 +5,6 @@
# Output of go build ./cmd/fsnotify
/fsnotify
/fsnotify.exe
+
+/test/kqueue
+/test/a.out
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/test/tools/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
index e0e5757549..6468d2cf40 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
@@ -1,8 +1,69 @@
# Changelog
-Unreleased
-----------
-Nothing yet.
+1.9.0 2024-04-04
+----------------
+
+### Changes and fixes
+
+- all: make BufferedWatcher buffered again ([#657])
+
+- inotify: fix race when adding/removing watches while a watched path is being
+ deleted ([#678], [#686])
+
+- inotify: don't send empty event if a watched path is unmounted ([#655])
+
+- inotify: don't register duplicate watches when watching both a symlink and its
+ target; previously that would get "half-added" and removing the second would
+ panic ([#679])
+
+- kqueue: fix watching relative symlinks ([#681])
+
+- kqueue: correctly mark pre-existing entries when watching a link to a dir on
+ kqueue ([#682])
+
+- illumos: don't send error if changed file is deleted while processing the
+ event ([#678])
+
+
+[#657]: https://github.com/fsnotify/fsnotify/pull/657
+[#678]: https://github.com/fsnotify/fsnotify/pull/678
+[#686]: https://github.com/fsnotify/fsnotify/pull/686
+[#655]: https://github.com/fsnotify/fsnotify/pull/655
+[#681]: https://github.com/fsnotify/fsnotify/pull/681
+[#679]: https://github.com/fsnotify/fsnotify/pull/679
+[#682]: https://github.com/fsnotify/fsnotify/pull/682
+
+1.8.0 2024-10-31
+----------------
+
+### Additions
+
+- all: add `FSNOTIFY_DEBUG` to print debug logs to stderr ([#619])
+
+### Changes and fixes
+
+- windows: fix behaviour of `WatchList()` to be consistent with other platforms ([#610])
+
+- kqueue: ignore events with Ident=0 ([#590])
+
+- kqueue: set O_CLOEXEC to prevent passing file descriptors to children ([#617])
+
+- kqueue: emit events as "/path/dir/file" instead of "path/link/file" when watching a symlink ([#625])
+
+- inotify: don't send event for IN_DELETE_SELF when also watching the parent ([#620])
+
+- inotify: fix panic when calling Remove() in a goroutine ([#650])
+
+- fen: allow watching subdirectories of watched directories ([#621])
+
+[#590]: https://github.com/fsnotify/fsnotify/pull/590
+[#610]: https://github.com/fsnotify/fsnotify/pull/610
+[#617]: https://github.com/fsnotify/fsnotify/pull/617
+[#619]: https://github.com/fsnotify/fsnotify/pull/619
+[#620]: https://github.com/fsnotify/fsnotify/pull/620
+[#621]: https://github.com/fsnotify/fsnotify/pull/621
+[#625]: https://github.com/fsnotify/fsnotify/pull/625
+[#650]: https://github.com/fsnotify/fsnotify/pull/650
1.7.0 - 2023-10-22
------------------
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/test/tools/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
index ea379759d5..4cc40fa597 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
@@ -1,7 +1,7 @@
Thank you for your interest in contributing to fsnotify! We try to review and
merge PRs in a reasonable timeframe, but please be aware that:
-- To avoid "wasted" work, please discus changes on the issue tracker first. You
+- To avoid "wasted" work, please discuss changes on the issue tracker first. You
can just send PRs, but they may end up being rejected for one reason or the
other.
@@ -20,6 +20,125 @@ platforms. Testing different platforms locally can be done with something like
Use the `-short` flag to make the "stress test" run faster.
+Writing new tests
+-----------------
+Scripts in the testdata directory allow creating test cases in a "shell-like"
+syntax. The basic format is:
+
+ script
+
+ Output:
+ desired output
+
+For example:
+
+ # Create a new empty file with some data.
+ watch /
+ echo data >/file
+
+ Output:
+ create /file
+ write /file
+
+Just create a new file to add a new test; select which tests to run with
+`-run TestScript/[path]`.
+
+script
+------
+The script is a "shell-like" script:
+
+ cmd arg arg
+
+Comments are supported with `#`:
+
+ # Comment
+ cmd arg arg # Comment
+
+All operations are done in a temp directory; a path like "/foo" is rewritten to
+"/tmp/TestFoo/foo".
+
+Arguments can be quoted with `"` or `'`; there are no escapes and they're
+functionally identical right now, but this may change in the future, so best to
+assume shell-like rules.
+
+ touch "/file with spaces"
+
+End-of-line escapes with `\` are not supported.
+
+### Supported commands
+
+ watch path [ops] # Watch the path, reporting events for it. Nothing is
+ # watched by default. Optionally a list of ops can be
+ # given, as with AddWith(path, WithOps(...)).
+ unwatch path # Stop watching the path.
+ watchlist n # Assert watchlist length.
+
+ stop # Stop running the script; for debugging.
+ debug [yes/no] # Enable/disable FSNOTIFY_DEBUG (tests are run in
+ parallel by default, so -parallel=1 is probably a good
+ idea).
+ print [any strings] # Print text to stdout; for debugging.
+
+ touch path
+ mkdir [-p] dir
+ ln -s target link # Only ln -s supported.
+ mkfifo path
+ mknod dev path
+ mv src dst
+ rm [-r] path
+ chmod mode path # Octal only
+ sleep time-in-ms
+
+ cat path # Read path (does nothing with the data; just reads it).
+ echo str >>path # Append "str" to "path".
+ echo str >path # Truncate "path" and write "str".
+
+ require reason # Skip the test if "reason" is true; "skip" and
+ skip reason # "require" behave identical; it supports both for
+ # readability. Possible reasons are:
+ #
+ # always Always skip this test.
+ # symlink Symlinks are supported (requires admin
+ # permissions on Windows).
+ # mkfifo Platform doesn't support FIFO named sockets.
+ # mknod Platform doesn't support device nodes.
+
+
+output
+------
+After `Output:` the desired output is given; this is indented by convention, but
+that's not required.
+
+The format of that is:
+
+ # Comment
+ event path # Comment
+
+ system:
+ event path
+ system2:
+ event path
+
+Every event is one line, and any whitespace between the event and path are
+ignored. The path can optionally be surrounded in ". Anything after a "#" is
+ignored.
+
+Platform-specific tests can be added after GOOS; for example:
+
+ watch /
+ touch /file
+
+ Output:
+ # Tested if nothing else matches
+ create /file
+
+ # Windows-specific test.
+ windows:
+ write /file
+
+You can specify multiple platforms with a comma (e.g. "windows, linux:").
+"kqueue" is a shortcut for all kqueue systems (BSD, macOS).
+
[goon]: https://github.com/arp242/goon
[Vagrant]: https://www.vagrantup.com/
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/README.md b/test/tools/vendor/github.com/fsnotify/fsnotify/README.md
index e480733d16..1f4eb583d5 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/README.md
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/README.md
@@ -15,7 +15,6 @@ Platform support:
| ReadDirectoryChangesW | Windows | Supported |
| FEN | illumos | Supported |
| fanotify | Linux 5.9+ | [Not yet](https://github.com/fsnotify/fsnotify/issues/114) |
-| AHAFS | AIX | [aix branch]; experimental due to lack of maintainer and test environment |
| FSEvents | macOS | [Needs support in x/sys/unix][fsevents] |
| USN Journals | Windows | [Needs support in x/sys/windows][usn] |
| Polling | *All* | [Not yet](https://github.com/fsnotify/fsnotify/issues/9) |
@@ -25,7 +24,6 @@ untested.
[fsevents]: https://github.com/fsnotify/fsnotify/issues/11#issuecomment-1279133120
[usn]: https://github.com/fsnotify/fsnotify/issues/53#issuecomment-1279829847
-[aix branch]: https://github.com/fsnotify/fsnotify/issues/353#issuecomment-1284590129
Usage
-----
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_fen.go b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_fen.go
index 28497f1dd8..57fc692848 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_fen.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_fen.go
@@ -1,162 +1,44 @@
//go:build solaris
-// +build solaris
-// Note: the documentation on the Watcher type and methods is generated from
-// mkdoc.zsh
+// FEN backend for illumos (supported) and Solaris (untested, but should work).
+//
+// See port_create(3c) etc. for docs. https://www.illumos.org/man/3C/port_create
package fsnotify
import (
"errors"
"fmt"
+ "io/fs"
"os"
"path/filepath"
"sync"
+ "time"
+ "github.com/fsnotify/fsnotify/internal"
"golang.org/x/sys/unix"
)
-// Watcher watches a set of paths, delivering events on a channel.
-//
-// A watcher should not be copied (e.g. pass it by pointer, rather than by
-// value).
-//
-// # Linux notes
-//
-// When a file is removed a Remove event won't be emitted until all file
-// descriptors are closed, and deletes will always emit a Chmod. For example:
-//
-// fp := os.Open("file")
-// os.Remove("file") // Triggers Chmod
-// fp.Close() // Triggers Remove
-//
-// This is the event that inotify sends, so not much can be changed about this.
-//
-// The fs.inotify.max_user_watches sysctl variable specifies the upper limit
-// for the number of watches per user, and fs.inotify.max_user_instances
-// specifies the maximum number of inotify instances per user. Every Watcher you
-// create is an "instance", and every path you add is a "watch".
-//
-// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and
-// /proc/sys/fs/inotify/max_user_instances
-//
-// To increase them you can use sysctl or write the value to the /proc file:
-//
-// # Default values on Linux 5.18
-// sysctl fs.inotify.max_user_watches=124983
-// sysctl fs.inotify.max_user_instances=128
-//
-// To make the changes persist on reboot edit /etc/sysctl.conf or
-// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check
-// your distro's documentation):
-//
-// fs.inotify.max_user_watches=124983
-// fs.inotify.max_user_instances=128
-//
-// Reaching the limit will result in a "no space left on device" or "too many open
-// files" error.
-//
-// # kqueue notes (macOS, BSD)
-//
-// kqueue requires opening a file descriptor for every file that's being watched;
-// so if you're watching a directory with five files then that's six file
-// descriptors. You will run in to your system's "max open files" limit faster on
-// these platforms.
-//
-// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to
-// control the maximum number of open files, as well as /etc/login.conf on BSD
-// systems.
-//
-// # Windows notes
-//
-// Paths can be added as "C:\path\to\dir", but forward slashes
-// ("C:/path/to/dir") will also work.
-//
-// When a watched directory is removed it will always send an event for the
-// directory itself, but may not send events for all files in that directory.
-// Sometimes it will send events for all times, sometimes it will send no
-// events, and often only for some files.
-//
-// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest
-// value that is guaranteed to work with SMB filesystems. If you have many
-// events in quick succession this may not be enough, and you will have to use
-// [WithBufferSize] to increase the value.
-type Watcher struct {
- // Events sends the filesystem change events.
- //
- // fsnotify can send the following events; a "path" here can refer to a
- // file, directory, symbolic link, or special file like a FIFO.
- //
- // fsnotify.Create A new path was created; this may be followed by one
- // or more Write events if data also gets written to a
- // file.
- //
- // fsnotify.Remove A path was removed.
- //
- // fsnotify.Rename A path was renamed. A rename is always sent with the
- // old path as Event.Name, and a Create event will be
- // sent with the new name. Renames are only sent for
- // paths that are currently watched; e.g. moving an
- // unmonitored file into a monitored directory will
- // show up as just a Create. Similarly, renaming a file
- // to outside a monitored directory will show up as
- // only a Rename.
- //
- // fsnotify.Write A file or named pipe was written to. A Truncate will
- // also trigger a Write. A single "write action"
- // initiated by the user may show up as one or multiple
- // writes, depending on when the system syncs things to
- // disk. For example when compiling a large Go program
- // you may get hundreds of Write events, and you may
- // want to wait until you've stopped receiving them
- // (see the dedup example in cmd/fsnotify).
- //
- // Some systems may send Write event for directories
- // when the directory content changes.
- //
- // fsnotify.Chmod Attributes were changed. On Linux this is also sent
- // when a file is removed (or more accurately, when a
- // link to an inode is removed). On kqueue it's sent
- // when a file is truncated. On Windows it's never
- // sent.
+type fen struct {
+ *shared
Events chan Event
-
- // Errors sends any errors.
- //
- // ErrEventOverflow is used to indicate there are too many events:
- //
- // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl)
- // - windows: The buffer size is too small; WithBufferSize() can be used to increase it.
- // - kqueue, fen: Not used.
Errors chan error
mu sync.Mutex
port *unix.EventPort
- done chan struct{} // Channel for sending a "quit message" to the reader goroutine
- dirs map[string]struct{} // Explicitly watched directories
- watches map[string]struct{} // Explicitly watched non-directories
+ dirs map[string]Op // Explicitly watched directories
+ watches map[string]Op // Explicitly watched non-directories
}
-// NewWatcher creates a new Watcher.
-func NewWatcher() (*Watcher, error) {
- return NewBufferedWatcher(0)
-}
+var defaultBufferSize = 0
-// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events
-// channel.
-//
-// The main use case for this is situations with a very large number of events
-// where the kernel buffer size can't be increased (e.g. due to lack of
-// permissions). An unbuffered Watcher will perform better for almost all use
-// cases, and whenever possible you will be better off increasing the kernel
-// buffers instead of adding a large userspace buffer.
-func NewBufferedWatcher(sz uint) (*Watcher, error) {
- w := &Watcher{
- Events: make(chan Event, sz),
- Errors: make(chan error),
- dirs: make(map[string]struct{}),
- watches: make(map[string]struct{}),
- done: make(chan struct{}),
+func newBackend(ev chan Event, errs chan error) (backend, error) {
+ w := &fen{
+ shared: newShared(ev, errs),
+ Events: ev,
+ Errors: errs,
+ dirs: make(map[string]Op),
+ watches: make(map[string]Op),
}
var err error
@@ -169,104 +51,28 @@ func NewBufferedWatcher(sz uint) (*Watcher, error) {
return w, nil
}
-// sendEvent attempts to send an event to the user, returning true if the event
-// was put in the channel successfully and false if the watcher has been closed.
-func (w *Watcher) sendEvent(name string, op Op) (sent bool) {
- select {
- case w.Events <- Event{Name: name, Op: op}:
- return true
- case <-w.done:
- return false
- }
-}
-
-// sendError attempts to send an error to the user, returning true if the error
-// was put in the channel successfully and false if the watcher has been closed.
-func (w *Watcher) sendError(err error) (sent bool) {
- select {
- case w.Errors <- err:
- return true
- case <-w.done:
- return false
- }
-}
-
-func (w *Watcher) isClosed() bool {
- select {
- case <-w.done:
- return true
- default:
- return false
- }
-}
-
-// Close removes all watches and closes the Events channel.
-func (w *Watcher) Close() error {
- // Take the lock used by associateFile to prevent lingering events from
- // being processed after the close
- w.mu.Lock()
- defer w.mu.Unlock()
- if w.isClosed() {
+func (w *fen) Close() error {
+ if w.shared.close() {
return nil
}
- close(w.done)
return w.port.Close()
}
-// Add starts monitoring the path for changes.
-//
-// A path can only be watched once; watching it more than once is a no-op and will
-// not return an error. Paths that do not yet exist on the filesystem cannot be
-// watched.
-//
-// A watch will be automatically removed if the watched path is deleted or
-// renamed. The exception is the Windows backend, which doesn't remove the
-// watcher on renames.
-//
-// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
-// filesystems (/proc, /sys, etc.) generally don't work.
-//
-// Returns [ErrClosed] if [Watcher.Close] was called.
-//
-// See [Watcher.AddWith] for a version that allows adding options.
-//
-// # Watching directories
-//
-// All files in a directory are monitored, including new files that are created
-// after the watcher is started. Subdirectories are not watched (i.e. it's
-// non-recursive).
-//
-// # Watching files
-//
-// Watching individual files (rather than directories) is generally not
-// recommended as many programs (especially editors) update files atomically: it
-// will write to a temporary file which is then moved to to destination,
-// overwriting the original (or some variant thereof). The watcher on the
-// original file is now lost, as that no longer exists.
-//
-// The upshot of this is that a power failure or crash won't leave a
-// half-written file.
-//
-// Watch the parent directory and use Event.Name to filter out files you're not
-// interested in. There is an example of this in cmd/fsnotify/file.go.
-func (w *Watcher) Add(name string) error { return w.AddWith(name) }
+func (w *fen) Add(name string) error { return w.AddWith(name) }
-// AddWith is like [Watcher.Add], but allows adding options. When using Add()
-// the defaults described below are used.
-//
-// Possible options are:
-//
-// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on
-// other platforms. The default is 64K (65536 bytes).
-func (w *Watcher) AddWith(name string, opts ...addOpt) error {
+func (w *fen) AddWith(name string, opts ...addOpt) error {
if w.isClosed() {
return ErrClosed
}
- if w.port.PathIsWatched(name) {
- return nil
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n",
+ time.Now().Format("15:04:05.000000000"), name)
}
- _ = getOptions(opts...)
+ with := getOptions(opts...)
+ if !w.xSupports(with.op) {
+ return fmt.Errorf("%w: %s", xErrUnsupported, with.op)
+ }
// Currently we resolve symlinks that were explicitly requested to be
// watched. Otherwise we would use LStat here.
@@ -283,7 +89,7 @@ func (w *Watcher) AddWith(name string, opts ...addOpt) error {
}
w.mu.Lock()
- w.dirs[name] = struct{}{}
+ w.dirs[name] = with.op
w.mu.Unlock()
return nil
}
@@ -294,26 +100,22 @@ func (w *Watcher) AddWith(name string, opts ...addOpt) error {
}
w.mu.Lock()
- w.watches[name] = struct{}{}
+ w.watches[name] = with.op
w.mu.Unlock()
return nil
}
-// Remove stops monitoring the path for changes.
-//
-// Directories are always removed non-recursively. For example, if you added
-// /tmp/dir and /tmp/dir/subdir then you will need to remove both.
-//
-// Removing a path that has not yet been added returns [ErrNonExistentWatch].
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) Remove(name string) error {
+func (w *fen) Remove(name string) error {
if w.isClosed() {
return nil
}
if !w.port.PathIsWatched(name) {
return fmt.Errorf("%w: %s", ErrNonExistentWatch, name)
}
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n",
+ time.Now().Format("15:04:05.000000000"), name)
+ }
// The user has expressed an intent. Immediately remove this name from
// whichever watch list it might be in. If it's not in there the delete
@@ -346,7 +148,7 @@ func (w *Watcher) Remove(name string) error {
}
// readEvents contains the main loop that runs in a goroutine watching for events.
-func (w *Watcher) readEvents() {
+func (w *fen) readEvents() {
// If this function returns, the watcher has been closed and we can close
// these channels
defer func() {
@@ -367,7 +169,7 @@ func (w *Watcher) readEvents() {
return
}
// There was an error not caused by calling w.Close()
- if !w.sendError(err) {
+ if !w.sendError(fmt.Errorf("port.Get: %w", err)) {
return
}
}
@@ -382,17 +184,19 @@ func (w *Watcher) readEvents() {
continue
}
+ if debug {
+ internal.Debug(pevent.Path, pevent.Events)
+ }
+
err = w.handleEvent(&pevent)
- if err != nil {
- if !w.sendError(err) {
- return
- }
+ if !w.sendError(err) {
+ return
}
}
}
}
-func (w *Watcher) handleDirectory(path string, stat os.FileInfo, follow bool, handler func(string, os.FileInfo, bool) error) error {
+func (w *fen) handleDirectory(path string, stat os.FileInfo, follow bool, handler func(string, os.FileInfo, bool) error) error {
files, err := os.ReadDir(path)
if err != nil {
return err
@@ -418,7 +222,7 @@ func (w *Watcher) handleDirectory(path string, stat os.FileInfo, follow bool, ha
// bitmap matches more than one event type (e.g. the file was both modified and
// had the attributes changed between when the association was created and the
// when event was returned)
-func (w *Watcher) handleEvent(event *unix.PortEvent) error {
+func (w *fen) handleEvent(event *unix.PortEvent) error {
var (
events = event.Events
path = event.Path
@@ -433,13 +237,13 @@ func (w *Watcher) handleEvent(event *unix.PortEvent) error {
isWatched := watchedDir || watchedPath
if events&unix.FILE_DELETE != 0 {
- if !w.sendEvent(path, Remove) {
+ if !w.sendEvent(Event{Name: path, Op: Remove}) {
return nil
}
reRegister = false
}
if events&unix.FILE_RENAME_FROM != 0 {
- if !w.sendEvent(path, Rename) {
+ if !w.sendEvent(Event{Name: path, Op: Rename}) {
return nil
}
// Don't keep watching the new file name
@@ -453,7 +257,7 @@ func (w *Watcher) handleEvent(event *unix.PortEvent) error {
// inotify reports a Remove event in this case, so we simulate this
// here.
- if !w.sendEvent(path, Remove) {
+ if !w.sendEvent(Event{Name: path, Op: Remove}) {
return nil
}
// Don't keep watching the file that was removed
@@ -487,7 +291,7 @@ func (w *Watcher) handleEvent(event *unix.PortEvent) error {
// get here, the sudirectory is already gone. Clearly we were watching
// this path but now it is gone. Let's tell the user that it was
// removed.
- if !w.sendEvent(path, Remove) {
+ if !w.sendEvent(Event{Name: path, Op: Remove}) {
return nil
}
// Suppress extra write events on removed directories; they are not
@@ -502,7 +306,7 @@ func (w *Watcher) handleEvent(event *unix.PortEvent) error {
if err != nil {
// The symlink still exists, but the target is gone. Report the
// Remove similar to above.
- if !w.sendEvent(path, Remove) {
+ if !w.sendEvent(Event{Name: path, Op: Remove}) {
return nil
}
// Don't return the error
@@ -510,18 +314,12 @@ func (w *Watcher) handleEvent(event *unix.PortEvent) error {
}
if events&unix.FILE_MODIFIED != 0 {
- if fmode.IsDir() {
- if watchedDir {
- if err := w.updateDirectory(path); err != nil {
- return err
- }
- } else {
- if !w.sendEvent(path, Write) {
- return nil
- }
+ if fmode.IsDir() && watchedDir {
+ if err := w.updateDirectory(path); err != nil {
+ return err
}
} else {
- if !w.sendEvent(path, Write) {
+ if !w.sendEvent(Event{Name: path, Op: Write}) {
return nil
}
}
@@ -529,7 +327,7 @@ func (w *Watcher) handleEvent(event *unix.PortEvent) error {
if events&unix.FILE_ATTRIB != 0 && stat != nil {
// Only send Chmod if perms changed
if stat.Mode().Perm() != fmode.Perm() {
- if !w.sendEvent(path, Chmod) {
+ if !w.sendEvent(Event{Name: path, Op: Chmod}) {
return nil
}
}
@@ -538,17 +336,27 @@ func (w *Watcher) handleEvent(event *unix.PortEvent) error {
if stat != nil {
// If we get here, it means we've hit an event above that requires us to
// continue watching the file or directory
- return w.associateFile(path, stat, isWatched)
+ err := w.associateFile(path, stat, isWatched)
+ if errors.Is(err, fs.ErrNotExist) {
+ // Path may have been removed since the stat.
+ err = nil
+ }
+ return err
}
return nil
}
-func (w *Watcher) updateDirectory(path string) error {
- // The directory was modified, so we must find unwatched entities and watch
- // them. If something was removed from the directory, nothing will happen,
- // as everything else should still be watched.
+// The directory was modified, so we must find unwatched entities and watch
+// them. If something was removed from the directory, nothing will happen, as
+// everything else should still be watched.
+func (w *fen) updateDirectory(path string) error {
files, err := os.ReadDir(path)
if err != nil {
+ // Directory no longer exists: probably just deleted since we got the
+ // event.
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
return err
}
@@ -563,19 +371,22 @@ func (w *Watcher) updateDirectory(path string) error {
return err
}
err = w.associateFile(path, finfo, false)
- if err != nil {
- if !w.sendError(err) {
- return nil
- }
+ if errors.Is(err, fs.ErrNotExist) {
+ // File may have disappeared between getting the dir listing and
+ // adding the port: that's okay to ignore.
+ continue
}
- if !w.sendEvent(path, Create) {
+ if !w.sendError(err) {
+ return nil
+ }
+ if !w.sendEvent(Event{Name: path, Op: Create}) {
return nil
}
}
return nil
}
-func (w *Watcher) associateFile(path string, stat os.FileInfo, follow bool) error {
+func (w *fen) associateFile(path string, stat os.FileInfo, follow bool) error {
if w.isClosed() {
return ErrClosed
}
@@ -593,34 +404,42 @@ func (w *Watcher) associateFile(path string, stat os.FileInfo, follow bool) erro
// cleared up that discrepancy. The most likely cause is that the event
// has fired but we haven't processed it yet.
err := w.port.DissociatePath(path)
- if err != nil && err != unix.ENOENT {
- return err
+ if err != nil && !errors.Is(err, unix.ENOENT) {
+ return fmt.Errorf("port.DissociatePath(%q): %w", path, err)
}
}
- // FILE_NOFOLLOW means we watch symlinks themselves rather than their
- // targets.
- events := unix.FILE_MODIFIED | unix.FILE_ATTRIB | unix.FILE_NOFOLLOW
- if follow {
- // We *DO* follow symlinks for explicitly watched entries.
- events = unix.FILE_MODIFIED | unix.FILE_ATTRIB
+
+ var events int
+ if !follow {
+ // Watch symlinks themselves rather than their targets unless this entry
+ // is explicitly watched.
+ events |= unix.FILE_NOFOLLOW
}
- return w.port.AssociatePath(path, stat,
- events,
- stat.Mode())
+ if true { // TODO: implement withOps()
+ events |= unix.FILE_MODIFIED
+ }
+ if true {
+ events |= unix.FILE_ATTRIB
+ }
+ err := w.port.AssociatePath(path, stat, events, stat.Mode())
+ if err != nil {
+ return fmt.Errorf("port.AssociatePath(%q): %w", path, err)
+ }
+ return nil
}
-func (w *Watcher) dissociateFile(path string, stat os.FileInfo, unused bool) error {
+func (w *fen) dissociateFile(path string, stat os.FileInfo, unused bool) error {
if !w.port.PathIsWatched(path) {
return nil
}
- return w.port.DissociatePath(path)
+ err := w.port.DissociatePath(path)
+ if err != nil {
+ return fmt.Errorf("port.DissociatePath(%q): %w", path, err)
+ }
+ return nil
}
-// WatchList returns all paths explicitly added with [Watcher.Add] (and are not
-// yet removed).
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) WatchList() []string {
+func (w *fen) WatchList() []string {
if w.isClosed() {
return nil
}
@@ -638,3 +457,11 @@ func (w *Watcher) WatchList() []string {
return entries
}
+
+func (w *fen) xSupports(op Op) bool {
+ if op.Has(xUnportableOpen) || op.Has(xUnportableRead) ||
+ op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) {
+ return false
+ }
+ return true
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_inotify.go b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_inotify.go
index 921c1c1e40..a36cb89d73 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_inotify.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_inotify.go
@@ -1,8 +1,4 @@
//go:build linux && !appengine
-// +build linux,!appengine
-
-// Note: the documentation on the Watcher type and methods is generated from
-// mkdoc.zsh
package fsnotify
@@ -10,127 +6,21 @@ import (
"errors"
"fmt"
"io"
+ "io/fs"
"os"
"path/filepath"
"strings"
"sync"
+ "time"
"unsafe"
+ "github.com/fsnotify/fsnotify/internal"
"golang.org/x/sys/unix"
)
-// Watcher watches a set of paths, delivering events on a channel.
-//
-// A watcher should not be copied (e.g. pass it by pointer, rather than by
-// value).
-//
-// # Linux notes
-//
-// When a file is removed a Remove event won't be emitted until all file
-// descriptors are closed, and deletes will always emit a Chmod. For example:
-//
-// fp := os.Open("file")
-// os.Remove("file") // Triggers Chmod
-// fp.Close() // Triggers Remove
-//
-// This is the event that inotify sends, so not much can be changed about this.
-//
-// The fs.inotify.max_user_watches sysctl variable specifies the upper limit
-// for the number of watches per user, and fs.inotify.max_user_instances
-// specifies the maximum number of inotify instances per user. Every Watcher you
-// create is an "instance", and every path you add is a "watch".
-//
-// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and
-// /proc/sys/fs/inotify/max_user_instances
-//
-// To increase them you can use sysctl or write the value to the /proc file:
-//
-// # Default values on Linux 5.18
-// sysctl fs.inotify.max_user_watches=124983
-// sysctl fs.inotify.max_user_instances=128
-//
-// To make the changes persist on reboot edit /etc/sysctl.conf or
-// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check
-// your distro's documentation):
-//
-// fs.inotify.max_user_watches=124983
-// fs.inotify.max_user_instances=128
-//
-// Reaching the limit will result in a "no space left on device" or "too many open
-// files" error.
-//
-// # kqueue notes (macOS, BSD)
-//
-// kqueue requires opening a file descriptor for every file that's being watched;
-// so if you're watching a directory with five files then that's six file
-// descriptors. You will run in to your system's "max open files" limit faster on
-// these platforms.
-//
-// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to
-// control the maximum number of open files, as well as /etc/login.conf on BSD
-// systems.
-//
-// # Windows notes
-//
-// Paths can be added as "C:\path\to\dir", but forward slashes
-// ("C:/path/to/dir") will also work.
-//
-// When a watched directory is removed it will always send an event for the
-// directory itself, but may not send events for all files in that directory.
-// Sometimes it will send events for all times, sometimes it will send no
-// events, and often only for some files.
-//
-// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest
-// value that is guaranteed to work with SMB filesystems. If you have many
-// events in quick succession this may not be enough, and you will have to use
-// [WithBufferSize] to increase the value.
-type Watcher struct {
- // Events sends the filesystem change events.
- //
- // fsnotify can send the following events; a "path" here can refer to a
- // file, directory, symbolic link, or special file like a FIFO.
- //
- // fsnotify.Create A new path was created; this may be followed by one
- // or more Write events if data also gets written to a
- // file.
- //
- // fsnotify.Remove A path was removed.
- //
- // fsnotify.Rename A path was renamed. A rename is always sent with the
- // old path as Event.Name, and a Create event will be
- // sent with the new name. Renames are only sent for
- // paths that are currently watched; e.g. moving an
- // unmonitored file into a monitored directory will
- // show up as just a Create. Similarly, renaming a file
- // to outside a monitored directory will show up as
- // only a Rename.
- //
- // fsnotify.Write A file or named pipe was written to. A Truncate will
- // also trigger a Write. A single "write action"
- // initiated by the user may show up as one or multiple
- // writes, depending on when the system syncs things to
- // disk. For example when compiling a large Go program
- // you may get hundreds of Write events, and you may
- // want to wait until you've stopped receiving them
- // (see the dedup example in cmd/fsnotify).
- //
- // Some systems may send Write event for directories
- // when the directory content changes.
- //
- // fsnotify.Chmod Attributes were changed. On Linux this is also sent
- // when a file is removed (or more accurately, when a
- // link to an inode is removed). On kqueue it's sent
- // when a file is truncated. On Windows it's never
- // sent.
+type inotify struct {
+ *shared
Events chan Event
-
- // Errors sends any errors.
- //
- // ErrEventOverflow is used to indicate there are too many events:
- //
- // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl)
- // - windows: The buffer size is too small; WithBufferSize() can be used to increase it.
- // - kqueue, fen: Not used.
Errors chan error
// Store fd here as os.File.Read() will no longer return on close after
@@ -138,21 +28,41 @@ type Watcher struct {
fd int
inotifyFile *os.File
watches *watches
- done chan struct{} // Channel for sending a "quit message" to the reader goroutine
- closeMu sync.Mutex
doneResp chan struct{} // Channel to respond to Close
+
+ // Store rename cookies in an array, with the index wrapping to 0. Almost
+ // all of the time what we get is a MOVED_FROM to set the cookie and the
+ // next event inotify sends will be MOVED_TO to read it. However, this is
+ // not guaranteed – as described in inotify(7) – and we may get other events
+ // between the two MOVED_* events (including other MOVED_* ones).
+ //
+ // A second issue is that moving a file outside the watched directory will
+ // trigger a MOVED_FROM to set the cookie, but we never see the MOVED_TO to
+ // read and delete it. So just storing it in a map would slowly leak memory.
+ //
+ // Doing it like this gives us a simple fast LRU-cache that won't allocate.
+ // Ten items should be more than enough for our purpose, and a loop over
+ // such a short array is faster than a map access anyway (not that it hugely
+ // matters since we're talking about hundreds of ns at the most, but still).
+ cookies [10]koekje
+ cookieIndex uint8
+ cookiesMu sync.Mutex
}
type (
watches struct {
- mu sync.RWMutex
wd map[uint32]*watch // wd → watch
path map[string]uint32 // pathname → wd
}
watch struct {
- wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall)
- flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags)
- path string // Watch path.
+ wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall)
+ flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags)
+ path string // Watch path.
+ recurse bool // Recursion with ./...?
+ }
+ koekje struct {
+ cookie uint32
+ path string
}
)
@@ -163,57 +73,43 @@ func newWatches() *watches {
}
}
-func (w *watches) len() int {
- w.mu.RLock()
- defer w.mu.RUnlock()
- return len(w.wd)
-}
-
-func (w *watches) add(ww *watch) {
- w.mu.Lock()
- defer w.mu.Unlock()
- w.wd[ww.wd] = ww
- w.path[ww.path] = ww.wd
-}
-
-func (w *watches) remove(wd uint32) {
- w.mu.Lock()
- defer w.mu.Unlock()
- delete(w.path, w.wd[wd].path)
- delete(w.wd, wd)
-}
-
-func (w *watches) removePath(path string) (uint32, bool) {
- w.mu.Lock()
- defer w.mu.Unlock()
+func (w *watches) byPath(path string) *watch { return w.wd[w.path[path]] }
+func (w *watches) byWd(wd uint32) *watch { return w.wd[wd] }
+func (w *watches) len() int { return len(w.wd) }
+func (w *watches) add(ww *watch) { w.wd[ww.wd] = ww; w.path[ww.path] = ww.wd }
+func (w *watches) remove(watch *watch) { delete(w.path, watch.path); delete(w.wd, watch.wd) }
+func (w *watches) removePath(path string) ([]uint32, error) {
+ path, recurse := recursivePath(path)
wd, ok := w.path[path]
if !ok {
- return 0, false
+ return nil, fmt.Errorf("%w: %s", ErrNonExistentWatch, path)
+ }
+
+ watch := w.wd[wd]
+ if recurse && !watch.recurse {
+ return nil, fmt.Errorf("can't use /... with non-recursive watch %q", path)
}
delete(w.path, path)
delete(w.wd, wd)
+ if !watch.recurse {
+ return []uint32{wd}, nil
+ }
- return wd, true
-}
-
-func (w *watches) byPath(path string) *watch {
- w.mu.RLock()
- defer w.mu.RUnlock()
- return w.wd[w.path[path]]
-}
-
-func (w *watches) byWd(wd uint32) *watch {
- w.mu.RLock()
- defer w.mu.RUnlock()
- return w.wd[wd]
+ wds := make([]uint32, 0, 8)
+ wds = append(wds, wd)
+ for p, rwd := range w.path {
+ if strings.HasPrefix(p, path) {
+ delete(w.path, p)
+ delete(w.wd, rwd)
+ wds = append(wds, rwd)
+ }
+ }
+ return wds, nil
}
func (w *watches) updatePath(path string, f func(*watch) (*watch, error)) error {
- w.mu.Lock()
- defer w.mu.Unlock()
-
var existing *watch
wd, ok := w.path[path]
if ok {
@@ -236,20 +132,9 @@ func (w *watches) updatePath(path string, f func(*watch) (*watch, error)) error
return nil
}
-// NewWatcher creates a new Watcher.
-func NewWatcher() (*Watcher, error) {
- return NewBufferedWatcher(0)
-}
+var defaultBufferSize = 0
-// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events
-// channel.
-//
-// The main use case for this is situations with a very large number of events
-// where the kernel buffer size can't be increased (e.g. due to lack of
-// permissions). An unbuffered Watcher will perform better for almost all use
-// cases, and whenever possible you will be better off increasing the kernel
-// buffers instead of adding a large userspace buffer.
-func NewBufferedWatcher(sz uint) (*Watcher, error) {
+func newBackend(ev chan Event, errs chan error) (backend, error) {
// Need to set nonblocking mode for SetDeadline to work, otherwise blocking
// I/O operations won't terminate on close.
fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
@@ -257,13 +142,13 @@ func NewBufferedWatcher(sz uint) (*Watcher, error) {
return nil, errno
}
- w := &Watcher{
+ w := &inotify{
+ shared: newShared(ev, errs),
+ Events: ev,
+ Errors: errs,
fd: fd,
inotifyFile: os.NewFile(uintptr(fd), ""),
watches: newWatches(),
- Events: make(chan Event, sz),
- Errors: make(chan error),
- done: make(chan struct{}),
doneResp: make(chan struct{}),
}
@@ -271,44 +156,10 @@ func NewBufferedWatcher(sz uint) (*Watcher, error) {
return w, nil
}
-// Returns true if the event was sent, or false if watcher is closed.
-func (w *Watcher) sendEvent(e Event) bool {
- select {
- case w.Events <- e:
- return true
- case <-w.done:
- return false
- }
-}
-
-// Returns true if the error was sent, or false if watcher is closed.
-func (w *Watcher) sendError(err error) bool {
- select {
- case w.Errors <- err:
- return true
- case <-w.done:
- return false
- }
-}
-
-func (w *Watcher) isClosed() bool {
- select {
- case <-w.done:
- return true
- default:
- return false
- }
-}
-
-// Close removes all watches and closes the Events channel.
-func (w *Watcher) Close() error {
- w.closeMu.Lock()
- if w.isClosed() {
- w.closeMu.Unlock()
+func (w *inotify) Close() error {
+ if w.shared.close() {
return nil
}
- close(w.done)
- w.closeMu.Unlock()
// Causes any blocking reads to return with an error, provided the file
// still supports deadline operations.
@@ -317,84 +168,114 @@ func (w *Watcher) Close() error {
return err
}
- // Wait for goroutine to close
- <-w.doneResp
-
+ <-w.doneResp // Wait for readEvents() to finish.
return nil
}
-// Add starts monitoring the path for changes.
-//
-// A path can only be watched once; watching it more than once is a no-op and will
-// not return an error. Paths that do not yet exist on the filesystem cannot be
-// watched.
-//
-// A watch will be automatically removed if the watched path is deleted or
-// renamed. The exception is the Windows backend, which doesn't remove the
-// watcher on renames.
-//
-// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
-// filesystems (/proc, /sys, etc.) generally don't work.
-//
-// Returns [ErrClosed] if [Watcher.Close] was called.
-//
-// See [Watcher.AddWith] for a version that allows adding options.
-//
-// # Watching directories
-//
-// All files in a directory are monitored, including new files that are created
-// after the watcher is started. Subdirectories are not watched (i.e. it's
-// non-recursive).
-//
-// # Watching files
-//
-// Watching individual files (rather than directories) is generally not
-// recommended as many programs (especially editors) update files atomically: it
-// will write to a temporary file which is then moved to to destination,
-// overwriting the original (or some variant thereof). The watcher on the
-// original file is now lost, as that no longer exists.
-//
-// The upshot of this is that a power failure or crash won't leave a
-// half-written file.
-//
-// Watch the parent directory and use Event.Name to filter out files you're not
-// interested in. There is an example of this in cmd/fsnotify/file.go.
-func (w *Watcher) Add(name string) error { return w.AddWith(name) }
+func (w *inotify) Add(name string) error { return w.AddWith(name) }
-// AddWith is like [Watcher.Add], but allows adding options. When using Add()
-// the defaults described below are used.
-//
-// Possible options are:
-//
-// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on
-// other platforms. The default is 64K (65536 bytes).
-func (w *Watcher) AddWith(name string, opts ...addOpt) error {
+func (w *inotify) AddWith(path string, opts ...addOpt) error {
if w.isClosed() {
return ErrClosed
}
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n",
+ time.Now().Format("15:04:05.000000000"), path)
+ }
- name = filepath.Clean(name)
- _ = getOptions(opts...)
+ with := getOptions(opts...)
+ if !w.xSupports(with.op) {
+ return fmt.Errorf("%w: %s", xErrUnsupported, with.op)
+ }
- var flags uint32 = unix.IN_MOVED_TO | unix.IN_MOVED_FROM |
- unix.IN_CREATE | unix.IN_ATTRIB | unix.IN_MODIFY |
- unix.IN_MOVE_SELF | unix.IN_DELETE | unix.IN_DELETE_SELF
+ add := func(path string, with withOpts, recurse bool) error {
+ var flags uint32
+ if with.noFollow {
+ flags |= unix.IN_DONT_FOLLOW
+ }
+ if with.op.Has(Create) {
+ flags |= unix.IN_CREATE
+ }
+ if with.op.Has(Write) {
+ flags |= unix.IN_MODIFY
+ }
+ if with.op.Has(Remove) {
+ flags |= unix.IN_DELETE | unix.IN_DELETE_SELF
+ }
+ if with.op.Has(Rename) {
+ flags |= unix.IN_MOVED_TO | unix.IN_MOVED_FROM | unix.IN_MOVE_SELF
+ }
+ if with.op.Has(Chmod) {
+ flags |= unix.IN_ATTRIB
+ }
+ if with.op.Has(xUnportableOpen) {
+ flags |= unix.IN_OPEN
+ }
+ if with.op.Has(xUnportableRead) {
+ flags |= unix.IN_ACCESS
+ }
+ if with.op.Has(xUnportableCloseWrite) {
+ flags |= unix.IN_CLOSE_WRITE
+ }
+ if with.op.Has(xUnportableCloseRead) {
+ flags |= unix.IN_CLOSE_NOWRITE
+ }
+ return w.register(path, flags, recurse)
+ }
- return w.watches.updatePath(name, func(existing *watch) (*watch, error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ path, recurse := recursivePath(path)
+ if recurse {
+ return filepath.WalkDir(path, func(root string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if !d.IsDir() {
+ if root == path {
+ return fmt.Errorf("fsnotify: not a directory: %q", path)
+ }
+ return nil
+ }
+
+ // Send a Create event when adding new directory from a recursive
+ // watch; this is for "mkdir -p one/two/three". Usually all those
+ // directories will be created before we can set up watchers on the
+ // subdirectories, so only "one" would be sent as a Create event and
+ // not "one/two" and "one/two/three" (inotifywait -r has the same
+ // problem).
+ if with.sendCreate && root != path {
+ w.sendEvent(Event{Name: root, Op: Create})
+ }
+
+ return add(root, with, true)
+ })
+ }
+
+ return add(path, with, false)
+}
+
+func (w *inotify) register(path string, flags uint32, recurse bool) error {
+ return w.watches.updatePath(path, func(existing *watch) (*watch, error) {
if existing != nil {
flags |= existing.flags | unix.IN_MASK_ADD
}
- wd, err := unix.InotifyAddWatch(w.fd, name, flags)
+ wd, err := unix.InotifyAddWatch(w.fd, path, flags)
if wd == -1 {
return nil, err
}
+ if e, ok := w.watches.wd[uint32(wd)]; ok {
+ return e, nil
+ }
+
if existing == nil {
return &watch{
- wd: uint32(wd),
- path: name,
- flags: flags,
+ wd: uint32(wd),
+ path: path,
+ flags: flags,
+ recurse: recurse,
}, nil
}
@@ -404,87 +285,80 @@ func (w *Watcher) AddWith(name string, opts ...addOpt) error {
})
}
-// Remove stops monitoring the path for changes.
-//
-// Directories are always removed non-recursively. For example, if you added
-// /tmp/dir and /tmp/dir/subdir then you will need to remove both.
-//
-// Removing a path that has not yet been added returns [ErrNonExistentWatch].
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) Remove(name string) error {
+func (w *inotify) Remove(name string) error {
if w.isClosed() {
return nil
}
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n",
+ time.Now().Format("15:04:05.000000000"), name)
+ }
+
+ w.mu.Lock()
+ defer w.mu.Unlock()
return w.remove(filepath.Clean(name))
}
-func (w *Watcher) remove(name string) error {
- wd, ok := w.watches.removePath(name)
- if !ok {
- return fmt.Errorf("%w: %s", ErrNonExistentWatch, name)
+func (w *inotify) remove(name string) error {
+ wds, err := w.watches.removePath(name)
+ if err != nil {
+ return err
}
- success, errno := unix.InotifyRmWatch(w.fd, wd)
- if success == -1 {
- // TODO: Perhaps it's not helpful to return an error here in every case;
- // The only two possible errors are:
- //
- // - EBADF, which happens when w.fd is not a valid file descriptor
- // of any kind.
- // - EINVAL, which is when fd is not an inotify descriptor or wd
- // is not a valid watch descriptor. Watch descriptors are
- // invalidated when they are removed explicitly or implicitly;
- // explicitly by inotify_rm_watch, implicitly when the file they
- // are watching is deleted.
- return errno
+ for _, wd := range wds {
+ _, err := unix.InotifyRmWatch(w.fd, wd)
+ if err != nil {
+ // TODO: Perhaps it's not helpful to return an error here in every
+ // case; the only two possible errors are:
+ //
+ // EBADF, which happens when w.fd is not a valid file descriptor of
+ // any kind.
+ //
+ // EINVAL, which is when fd is not an inotify descriptor or wd is
+ // not a valid watch descriptor. Watch descriptors are invalidated
+ // when they are removed explicitly or implicitly; explicitly by
+ // inotify_rm_watch, implicitly when the file they are watching is
+ // deleted.
+ return err
+ }
}
return nil
}
-// WatchList returns all paths explicitly added with [Watcher.Add] (and are not
-// yet removed).
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) WatchList() []string {
+func (w *inotify) WatchList() []string {
if w.isClosed() {
return nil
}
+ w.mu.Lock()
+ defer w.mu.Unlock()
entries := make([]string, 0, w.watches.len())
- w.watches.mu.RLock()
for pathname := range w.watches.path {
entries = append(entries, pathname)
}
- w.watches.mu.RUnlock()
-
return entries
}
// readEvents reads from the inotify file descriptor, converts the
// received events into Event objects and sends them via the Events channel
-func (w *Watcher) readEvents() {
+func (w *inotify) readEvents() {
defer func() {
close(w.doneResp)
close(w.Errors)
close(w.Events)
}()
- var (
- buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events
- errno error // Syscall errno
- )
+ var buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events
for {
- // See if we have been closed.
if w.isClosed() {
return
}
n, err := w.inotifyFile.Read(buf[:])
- switch {
- case errors.Unwrap(err) == os.ErrClosed:
- return
- case err != nil:
+ if err != nil {
+ if errors.Is(err, os.ErrClosed) {
+ return
+ }
if !w.sendError(err) {
return
}
@@ -492,13 +366,9 @@ func (w *Watcher) readEvents() {
}
if n < unix.SizeofInotifyEvent {
- var err error
+ err := errors.New("notify: short read in readEvents()") // Read was too short.
if n == 0 {
err = io.EOF // If EOF is received. This should really never happen.
- } else if n < 0 {
- err = errno // If an error occurred while reading.
- } else {
- err = errors.New("notify: short read in readEvents()") // Read was too short.
}
if !w.sendError(err) {
return
@@ -506,74 +376,146 @@ func (w *Watcher) readEvents() {
continue
}
+ // We don't know how many events we just read into the buffer While the
+ // offset points to at least one whole event.
var offset uint32
- // We don't know how many events we just read into the buffer
- // While the offset points to at least one whole event...
for offset <= uint32(n-unix.SizeofInotifyEvent) {
- var (
- // Point "raw" to the event in the buffer
- raw = (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset]))
- mask = uint32(raw.Mask)
- nameLen = uint32(raw.Len)
- )
+ // Point to the event in the buffer.
+ inEvent := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset]))
- if mask&unix.IN_Q_OVERFLOW != 0 {
+ if inEvent.Mask&unix.IN_Q_OVERFLOW != 0 {
if !w.sendError(ErrEventOverflow) {
return
}
}
- // If the event happened to the watched directory or the watched file, the kernel
- // doesn't append the filename to the event, but we would like to always fill the
- // the "Name" field with a valid filename. We retrieve the path of the watch from
- // the "paths" map.
- watch := w.watches.byWd(uint32(raw.Wd))
-
- // inotify will automatically remove the watch on deletes; just need
- // to clean our state here.
- if watch != nil && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF {
- w.watches.remove(watch.wd)
+ ev, ok := w.handleEvent(inEvent, &buf, offset)
+ if !ok {
+ return
}
- // We can't really update the state when a watched path is moved;
- // only IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove
- // the watch.
- if watch != nil && mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF {
- err := w.remove(watch.path)
- if err != nil && !errors.Is(err, ErrNonExistentWatch) {
- if !w.sendError(err) {
- return
- }
- }
- }
-
- var name string
- if watch != nil {
- name = watch.path
- }
- if nameLen > 0 {
- // Point "bytes" at the first byte of the filename
- bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen]
- // The filename is padded with NULL bytes. TrimRight() gets rid of those.
- name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000")
- }
-
- event := w.newEvent(name, mask)
-
- // Send the events that are not ignored on the events channel
- if mask&unix.IN_IGNORED == 0 {
- if !w.sendEvent(event) {
- return
- }
+ if !w.sendEvent(ev) {
+ return
}
// Move to the next event in the buffer
- offset += unix.SizeofInotifyEvent + nameLen
+ offset += unix.SizeofInotifyEvent + inEvent.Len
}
}
}
-// newEvent returns an platform-independent Event based on an inotify mask.
-func (w *Watcher) newEvent(name string, mask uint32) Event {
+func (w *inotify) handleEvent(inEvent *unix.InotifyEvent, buf *[65536]byte, offset uint32) (Event, bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ /// If the event happened to the watched directory or the watched file, the
+ /// kernel doesn't append the filename to the event, but we would like to
+ /// always fill the the "Name" field with a valid filename. We retrieve the
+ /// path of the watch from the "paths" map.
+ ///
+ /// Can be nil if Remove() was called in another goroutine for this path
+ /// inbetween reading the events from the kernel and reading the internal
+ /// state. Not much we can do about it, so just skip. See #616.
+ watch := w.watches.byWd(uint32(inEvent.Wd))
+ if watch == nil {
+ return Event{}, true
+ }
+
+ var (
+ name = watch.path
+ nameLen = uint32(inEvent.Len)
+ )
+ if nameLen > 0 {
+ /// Point "bytes" at the first byte of the filename
+ bb := *buf
+ bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&bb[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen]
+ /// The filename is padded with NULL bytes. TrimRight() gets rid of those.
+ name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\x00")
+ }
+
+ if debug {
+ internal.Debug(name, inEvent.Mask, inEvent.Cookie)
+ }
+
+ if inEvent.Mask&unix.IN_IGNORED != 0 || inEvent.Mask&unix.IN_UNMOUNT != 0 {
+ w.watches.remove(watch)
+ return Event{}, true
+ }
+
+ // inotify will automatically remove the watch on deletes; just need
+ // to clean our state here.
+ if inEvent.Mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF {
+ w.watches.remove(watch)
+ }
+
+ // We can't really update the state when a watched path is moved; only
+ // IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove the watch.
+ if inEvent.Mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF {
+ if watch.recurse { // Do nothing
+ return Event{}, true
+ }
+
+ err := w.remove(watch.path)
+ if err != nil && !errors.Is(err, ErrNonExistentWatch) {
+ if !w.sendError(err) {
+ return Event{}, false
+ }
+ }
+ }
+
+ /// Skip if we're watching both this path and the parent; the parent will
+ /// already send a delete so no need to do it twice.
+ if inEvent.Mask&unix.IN_DELETE_SELF != 0 {
+ _, ok := w.watches.path[filepath.Dir(watch.path)]
+ if ok {
+ return Event{}, true
+ }
+ }
+
+ ev := w.newEvent(name, inEvent.Mask, inEvent.Cookie)
+ // Need to update watch path for recurse.
+ if watch.recurse {
+ isDir := inEvent.Mask&unix.IN_ISDIR == unix.IN_ISDIR
+ /// New directory created: set up watch on it.
+ if isDir && ev.Has(Create) {
+ err := w.register(ev.Name, watch.flags, true)
+ if !w.sendError(err) {
+ return Event{}, false
+ }
+
+ // This was a directory rename, so we need to update all the
+ // children.
+ //
+ // TODO: this is of course pretty slow; we should use a better data
+ // structure for storing all of this, e.g. store children in the
+ // watch. I have some code for this in my kqueue refactor we can use
+ // in the future. For now I'm okay with this as it's not publicly
+ // available. Correctness first, performance second.
+ if ev.renamedFrom != "" {
+ for k, ww := range w.watches.wd {
+ if k == watch.wd || ww.path == ev.Name {
+ continue
+ }
+ if strings.HasPrefix(ww.path, ev.renamedFrom) {
+ ww.path = strings.Replace(ww.path, ev.renamedFrom, ev.Name, 1)
+ w.watches.wd[k] = ww
+ }
+ }
+ }
+ }
+ }
+
+ return ev, true
+}
+
+func (w *inotify) isRecursive(path string) bool {
+ ww := w.watches.byPath(path)
+ if ww == nil { // path could be a file, so also check the Dir.
+ ww = w.watches.byPath(filepath.Dir(path))
+ }
+ return ww != nil && ww.recurse
+}
+
+func (w *inotify) newEvent(name string, mask, cookie uint32) Event {
e := Event{Name: name}
if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO {
e.Op |= Create
@@ -584,11 +526,58 @@ func (w *Watcher) newEvent(name string, mask uint32) Event {
if mask&unix.IN_MODIFY == unix.IN_MODIFY {
e.Op |= Write
}
+ if mask&unix.IN_OPEN == unix.IN_OPEN {
+ e.Op |= xUnportableOpen
+ }
+ if mask&unix.IN_ACCESS == unix.IN_ACCESS {
+ e.Op |= xUnportableRead
+ }
+ if mask&unix.IN_CLOSE_WRITE == unix.IN_CLOSE_WRITE {
+ e.Op |= xUnportableCloseWrite
+ }
+ if mask&unix.IN_CLOSE_NOWRITE == unix.IN_CLOSE_NOWRITE {
+ e.Op |= xUnportableCloseRead
+ }
if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM {
e.Op |= Rename
}
if mask&unix.IN_ATTRIB == unix.IN_ATTRIB {
e.Op |= Chmod
}
+
+ if cookie != 0 {
+ if mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM {
+ w.cookiesMu.Lock()
+ w.cookies[w.cookieIndex] = koekje{cookie: cookie, path: e.Name}
+ w.cookieIndex++
+ if w.cookieIndex > 9 {
+ w.cookieIndex = 0
+ }
+ w.cookiesMu.Unlock()
+ } else if mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO {
+ w.cookiesMu.Lock()
+ var prev string
+ for _, c := range w.cookies {
+ if c.cookie == cookie {
+ prev = c.path
+ break
+ }
+ }
+ w.cookiesMu.Unlock()
+ e.renamedFrom = prev
+ }
+ }
return e
}
+
+func (w *inotify) xSupports(op Op) bool {
+ return true // Supports everything.
+}
+
+func (w *inotify) state() {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ for wd, ww := range w.watches.wd {
+ fmt.Fprintf(os.Stderr, "%4d: recurse=%t %q\n", wd, ww.recurse, ww.path)
+ }
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go
index 063a0915a0..340aeec061 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go
@@ -1,8 +1,4 @@
//go:build freebsd || openbsd || netbsd || dragonfly || darwin
-// +build freebsd openbsd netbsd dragonfly darwin
-
-// Note: the documentation on the Watcher type and methods is generated from
-// mkdoc.zsh
package fsnotify
@@ -11,174 +7,196 @@ import (
"fmt"
"os"
"path/filepath"
+ "runtime"
"sync"
+ "time"
+ "github.com/fsnotify/fsnotify/internal"
"golang.org/x/sys/unix"
)
-// Watcher watches a set of paths, delivering events on a channel.
-//
-// A watcher should not be copied (e.g. pass it by pointer, rather than by
-// value).
-//
-// # Linux notes
-//
-// When a file is removed a Remove event won't be emitted until all file
-// descriptors are closed, and deletes will always emit a Chmod. For example:
-//
-// fp := os.Open("file")
-// os.Remove("file") // Triggers Chmod
-// fp.Close() // Triggers Remove
-//
-// This is the event that inotify sends, so not much can be changed about this.
-//
-// The fs.inotify.max_user_watches sysctl variable specifies the upper limit
-// for the number of watches per user, and fs.inotify.max_user_instances
-// specifies the maximum number of inotify instances per user. Every Watcher you
-// create is an "instance", and every path you add is a "watch".
-//
-// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and
-// /proc/sys/fs/inotify/max_user_instances
-//
-// To increase them you can use sysctl or write the value to the /proc file:
-//
-// # Default values on Linux 5.18
-// sysctl fs.inotify.max_user_watches=124983
-// sysctl fs.inotify.max_user_instances=128
-//
-// To make the changes persist on reboot edit /etc/sysctl.conf or
-// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check
-// your distro's documentation):
-//
-// fs.inotify.max_user_watches=124983
-// fs.inotify.max_user_instances=128
-//
-// Reaching the limit will result in a "no space left on device" or "too many open
-// files" error.
-//
-// # kqueue notes (macOS, BSD)
-//
-// kqueue requires opening a file descriptor for every file that's being watched;
-// so if you're watching a directory with five files then that's six file
-// descriptors. You will run in to your system's "max open files" limit faster on
-// these platforms.
-//
-// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to
-// control the maximum number of open files, as well as /etc/login.conf on BSD
-// systems.
-//
-// # Windows notes
-//
-// Paths can be added as "C:\path\to\dir", but forward slashes
-// ("C:/path/to/dir") will also work.
-//
-// When a watched directory is removed it will always send an event for the
-// directory itself, but may not send events for all files in that directory.
-// Sometimes it will send events for all times, sometimes it will send no
-// events, and often only for some files.
-//
-// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest
-// value that is guaranteed to work with SMB filesystems. If you have many
-// events in quick succession this may not be enough, and you will have to use
-// [WithBufferSize] to increase the value.
-type Watcher struct {
- // Events sends the filesystem change events.
- //
- // fsnotify can send the following events; a "path" here can refer to a
- // file, directory, symbolic link, or special file like a FIFO.
- //
- // fsnotify.Create A new path was created; this may be followed by one
- // or more Write events if data also gets written to a
- // file.
- //
- // fsnotify.Remove A path was removed.
- //
- // fsnotify.Rename A path was renamed. A rename is always sent with the
- // old path as Event.Name, and a Create event will be
- // sent with the new name. Renames are only sent for
- // paths that are currently watched; e.g. moving an
- // unmonitored file into a monitored directory will
- // show up as just a Create. Similarly, renaming a file
- // to outside a monitored directory will show up as
- // only a Rename.
- //
- // fsnotify.Write A file or named pipe was written to. A Truncate will
- // also trigger a Write. A single "write action"
- // initiated by the user may show up as one or multiple
- // writes, depending on when the system syncs things to
- // disk. For example when compiling a large Go program
- // you may get hundreds of Write events, and you may
- // want to wait until you've stopped receiving them
- // (see the dedup example in cmd/fsnotify).
- //
- // Some systems may send Write event for directories
- // when the directory content changes.
- //
- // fsnotify.Chmod Attributes were changed. On Linux this is also sent
- // when a file is removed (or more accurately, when a
- // link to an inode is removed). On kqueue it's sent
- // when a file is truncated. On Windows it's never
- // sent.
+type kqueue struct {
+ *shared
Events chan Event
-
- // Errors sends any errors.
- //
- // ErrEventOverflow is used to indicate there are too many events:
- //
- // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl)
- // - windows: The buffer size is too small; WithBufferSize() can be used to increase it.
- // - kqueue, fen: Not used.
Errors chan error
- done chan struct{}
- kq int // File descriptor (as returned by the kqueue() syscall).
- closepipe [2]int // Pipe used for closing.
- mu sync.Mutex // Protects access to watcher data
- watches map[string]int // Watched file descriptors (key: path).
- watchesByDir map[string]map[int]struct{} // Watched file descriptors indexed by the parent directory (key: dirname(path)).
- userWatches map[string]struct{} // Watches added with Watcher.Add()
- dirFlags map[string]uint32 // Watched directories to fflags used in kqueue.
- paths map[int]pathInfo // File descriptors to path names for processing kqueue events.
- fileExists map[string]struct{} // Keep track of if we know this file exists (to stop duplicate create events).
- isClosed bool // Set to true when Close() is first called
+ kq int // File descriptor (as returned by the kqueue() syscall).
+ closepipe [2]int // Pipe used for closing kq.
+ watches *watches
}
-type pathInfo struct {
- name string
- isDir bool
+type (
+ watches struct {
+ mu sync.RWMutex
+ wd map[int]watch // wd → watch
+ path map[string]int // pathname → wd
+ byDir map[string]map[int]struct{} // dirname(path) → wd
+ seen map[string]struct{} // Keep track of if we know this file exists.
+ byUser map[string]struct{} // Watches added with Watcher.Add()
+ }
+ watch struct {
+ wd int
+ name string
+ linkName string // In case of links; name is the target, and this is the link.
+ isDir bool
+ dirFlags uint32
+ }
+)
+
+func newWatches() *watches {
+ return &watches{
+ wd: make(map[int]watch),
+ path: make(map[string]int),
+ byDir: make(map[string]map[int]struct{}),
+ seen: make(map[string]struct{}),
+ byUser: make(map[string]struct{}),
+ }
}
-// NewWatcher creates a new Watcher.
-func NewWatcher() (*Watcher, error) {
- return NewBufferedWatcher(0)
+func (w *watches) listPaths(userOnly bool) []string {
+ w.mu.RLock()
+ defer w.mu.RUnlock()
+
+ if userOnly {
+ l := make([]string, 0, len(w.byUser))
+ for p := range w.byUser {
+ l = append(l, p)
+ }
+ return l
+ }
+
+ l := make([]string, 0, len(w.path))
+ for p := range w.path {
+ l = append(l, p)
+ }
+ return l
}
-// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events
-// channel.
-//
-// The main use case for this is situations with a very large number of events
-// where the kernel buffer size can't be increased (e.g. due to lack of
-// permissions). An unbuffered Watcher will perform better for almost all use
-// cases, and whenever possible you will be better off increasing the kernel
-// buffers instead of adding a large userspace buffer.
-func NewBufferedWatcher(sz uint) (*Watcher, error) {
+func (w *watches) watchesInDir(path string) []string {
+ w.mu.RLock()
+ defer w.mu.RUnlock()
+
+ l := make([]string, 0, 4)
+ for fd := range w.byDir[path] {
+ info := w.wd[fd]
+ if _, ok := w.byUser[info.name]; !ok {
+ l = append(l, info.name)
+ }
+ }
+ return l
+}
+
+// Mark path as added by the user.
+func (w *watches) addUserWatch(path string) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ w.byUser[path] = struct{}{}
+}
+
+func (w *watches) addLink(path string, fd int) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ w.path[path] = fd
+ w.seen[path] = struct{}{}
+}
+
+func (w *watches) add(path, linkPath string, fd int, isDir bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ w.path[path] = fd
+ w.wd[fd] = watch{wd: fd, name: path, linkName: linkPath, isDir: isDir}
+
+ parent := filepath.Dir(path)
+ byDir, ok := w.byDir[parent]
+ if !ok {
+ byDir = make(map[int]struct{}, 1)
+ w.byDir[parent] = byDir
+ }
+ byDir[fd] = struct{}{}
+}
+
+func (w *watches) byWd(fd int) (watch, bool) {
+ w.mu.RLock()
+ defer w.mu.RUnlock()
+ info, ok := w.wd[fd]
+ return info, ok
+}
+
+func (w *watches) byPath(path string) (watch, bool) {
+ w.mu.RLock()
+ defer w.mu.RUnlock()
+ info, ok := w.wd[w.path[path]]
+ return info, ok
+}
+
+func (w *watches) updateDirFlags(path string, flags uint32) bool {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ fd, ok := w.path[path]
+ if !ok { // Already deleted: don't re-set it here.
+ return false
+ }
+ info := w.wd[fd]
+ info.dirFlags = flags
+ w.wd[fd] = info
+ return true
+}
+
+func (w *watches) remove(fd int, path string) bool {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ isDir := w.wd[fd].isDir
+ delete(w.path, path)
+ delete(w.byUser, path)
+
+ parent := filepath.Dir(path)
+ delete(w.byDir[parent], fd)
+
+ if len(w.byDir[parent]) == 0 {
+ delete(w.byDir, parent)
+ }
+
+ delete(w.wd, fd)
+ delete(w.seen, path)
+ return isDir
+}
+
+func (w *watches) markSeen(path string, exists bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if exists {
+ w.seen[path] = struct{}{}
+ } else {
+ delete(w.seen, path)
+ }
+}
+
+func (w *watches) seenBefore(path string) bool {
+ w.mu.RLock()
+ defer w.mu.RUnlock()
+ _, ok := w.seen[path]
+ return ok
+}
+
+var defaultBufferSize = 0
+
+func newBackend(ev chan Event, errs chan error) (backend, error) {
kq, closepipe, err := newKqueue()
if err != nil {
return nil, err
}
- w := &Watcher{
- kq: kq,
- closepipe: closepipe,
- watches: make(map[string]int),
- watchesByDir: make(map[string]map[int]struct{}),
- dirFlags: make(map[string]uint32),
- paths: make(map[int]pathInfo),
- fileExists: make(map[string]struct{}),
- userWatches: make(map[string]struct{}),
- Events: make(chan Event, sz),
- Errors: make(chan error),
- done: make(chan struct{}),
+ w := &kqueue{
+ shared: newShared(ev, errs),
+ Events: ev,
+ Errors: errs,
+ kq: kq,
+ closepipe: closepipe,
+ watches: newWatches(),
}
go w.readEvents()
@@ -193,7 +211,7 @@ func NewBufferedWatcher(sz uint) (*Watcher, error) {
// all.
func newKqueue() (kq int, closepipe [2]int, err error) {
kq, err = unix.Kqueue()
- if kq == -1 {
+ if err != nil {
return kq, closepipe, err
}
@@ -203,6 +221,8 @@ func newKqueue() (kq int, closepipe [2]int, err error) {
unix.Close(kq)
return kq, closepipe, err
}
+ unix.CloseOnExec(closepipe[0])
+ unix.CloseOnExec(closepipe[1])
// Register changes to listen on the closepipe.
changes := make([]unix.Kevent_t, 1)
@@ -220,167 +240,72 @@ func newKqueue() (kq int, closepipe [2]int, err error) {
return kq, closepipe, nil
}
-// Returns true if the event was sent, or false if watcher is closed.
-func (w *Watcher) sendEvent(e Event) bool {
- select {
- case w.Events <- e:
- return true
- case <-w.done:
- return false
- }
-}
-
-// Returns true if the error was sent, or false if watcher is closed.
-func (w *Watcher) sendError(err error) bool {
- select {
- case w.Errors <- err:
- return true
- case <-w.done:
- return false
- }
-}
-
-// Close removes all watches and closes the Events channel.
-func (w *Watcher) Close() error {
- w.mu.Lock()
- if w.isClosed {
- w.mu.Unlock()
+func (w *kqueue) Close() error {
+ if w.shared.close() {
return nil
}
- w.isClosed = true
- // copy paths to remove while locked
- pathsToRemove := make([]string, 0, len(w.watches))
- for name := range w.watches {
- pathsToRemove = append(pathsToRemove, name)
- }
- w.mu.Unlock() // Unlock before calling Remove, which also locks
+ pathsToRemove := w.watches.listPaths(false)
for _, name := range pathsToRemove {
w.Remove(name)
}
- // Send "quit" message to the reader goroutine.
- unix.Close(w.closepipe[1])
- close(w.done)
-
+ unix.Close(w.closepipe[1]) // Send "quit" message to readEvents
return nil
}
-// Add starts monitoring the path for changes.
-//
-// A path can only be watched once; watching it more than once is a no-op and will
-// not return an error. Paths that do not yet exist on the filesystem cannot be
-// watched.
-//
-// A watch will be automatically removed if the watched path is deleted or
-// renamed. The exception is the Windows backend, which doesn't remove the
-// watcher on renames.
-//
-// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
-// filesystems (/proc, /sys, etc.) generally don't work.
-//
-// Returns [ErrClosed] if [Watcher.Close] was called.
-//
-// See [Watcher.AddWith] for a version that allows adding options.
-//
-// # Watching directories
-//
-// All files in a directory are monitored, including new files that are created
-// after the watcher is started. Subdirectories are not watched (i.e. it's
-// non-recursive).
-//
-// # Watching files
-//
-// Watching individual files (rather than directories) is generally not
-// recommended as many programs (especially editors) update files atomically: it
-// will write to a temporary file which is then moved to to destination,
-// overwriting the original (or some variant thereof). The watcher on the
-// original file is now lost, as that no longer exists.
-//
-// The upshot of this is that a power failure or crash won't leave a
-// half-written file.
-//
-// Watch the parent directory and use Event.Name to filter out files you're not
-// interested in. There is an example of this in cmd/fsnotify/file.go.
-func (w *Watcher) Add(name string) error { return w.AddWith(name) }
+func (w *kqueue) Add(name string) error { return w.AddWith(name) }
-// AddWith is like [Watcher.Add], but allows adding options. When using Add()
-// the defaults described below are used.
-//
-// Possible options are:
-//
-// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on
-// other platforms. The default is 64K (65536 bytes).
-func (w *Watcher) AddWith(name string, opts ...addOpt) error {
- _ = getOptions(opts...)
+func (w *kqueue) AddWith(name string, opts ...addOpt) error {
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n",
+ time.Now().Format("15:04:05.000000000"), name)
+ }
- w.mu.Lock()
- w.userWatches[name] = struct{}{}
- w.mu.Unlock()
- _, err := w.addWatch(name, noteAllEvents)
- return err
+ with := getOptions(opts...)
+ if !w.xSupports(with.op) {
+ return fmt.Errorf("%w: %s", xErrUnsupported, with.op)
+ }
+
+ _, err := w.addWatch(name, noteAllEvents, false)
+ if err != nil {
+ return err
+ }
+ w.watches.addUserWatch(name)
+ return nil
}
-// Remove stops monitoring the path for changes.
-//
-// Directories are always removed non-recursively. For example, if you added
-// /tmp/dir and /tmp/dir/subdir then you will need to remove both.
-//
-// Removing a path that has not yet been added returns [ErrNonExistentWatch].
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) Remove(name string) error {
+func (w *kqueue) Remove(name string) error {
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n",
+ time.Now().Format("15:04:05.000000000"), name)
+ }
return w.remove(name, true)
}
-func (w *Watcher) remove(name string, unwatchFiles bool) error {
- name = filepath.Clean(name)
- w.mu.Lock()
- if w.isClosed {
- w.mu.Unlock()
+func (w *kqueue) remove(name string, unwatchFiles bool) error {
+ if w.isClosed() {
return nil
}
- watchfd, ok := w.watches[name]
- w.mu.Unlock()
+
+ name = filepath.Clean(name)
+ info, ok := w.watches.byPath(name)
if !ok {
return fmt.Errorf("%w: %s", ErrNonExistentWatch, name)
}
- err := w.register([]int{watchfd}, unix.EV_DELETE, 0)
+ err := w.register([]int{info.wd}, unix.EV_DELETE, 0)
if err != nil {
return err
}
- unix.Close(watchfd)
+ unix.Close(info.wd)
- w.mu.Lock()
- isDir := w.paths[watchfd].isDir
- delete(w.watches, name)
- delete(w.userWatches, name)
-
- parentName := filepath.Dir(name)
- delete(w.watchesByDir[parentName], watchfd)
-
- if len(w.watchesByDir[parentName]) == 0 {
- delete(w.watchesByDir, parentName)
- }
-
- delete(w.paths, watchfd)
- delete(w.dirFlags, name)
- delete(w.fileExists, name)
- w.mu.Unlock()
+ isDir := w.watches.remove(info.wd, name)
// Find all watched paths that are in this directory that are not external.
if unwatchFiles && isDir {
- var pathsToRemove []string
- w.mu.Lock()
- for fd := range w.watchesByDir[name] {
- path := w.paths[fd]
- if _, ok := w.userWatches[path.name]; !ok {
- pathsToRemove = append(pathsToRemove, path.name)
- }
- }
- w.mu.Unlock()
+ pathsToRemove := w.watches.watchesInDir(name)
for _, name := range pathsToRemove {
// Since these are internal, not much sense in propagating error to
// the user, as that will just confuse them with an error about a
@@ -391,23 +316,11 @@ func (w *Watcher) remove(name string, unwatchFiles bool) error {
return nil
}
-// WatchList returns all paths explicitly added with [Watcher.Add] (and are not
-// yet removed).
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) WatchList() []string {
- w.mu.Lock()
- defer w.mu.Unlock()
- if w.isClosed {
+func (w *kqueue) WatchList() []string {
+ if w.isClosed() {
return nil
}
-
- entries := make([]string, 0, len(w.userWatches))
- for pathname := range w.userWatches {
- entries = append(entries, pathname)
- }
-
- return entries
+ return w.watches.listPaths(true)
}
// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE)
@@ -417,114 +330,93 @@ const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | un
// described in kevent(2).
//
// Returns the real path to the file which was added, with symlinks resolved.
-func (w *Watcher) addWatch(name string, flags uint32) (string, error) {
- var isDir bool
- name = filepath.Clean(name)
-
- w.mu.Lock()
- if w.isClosed {
- w.mu.Unlock()
+func (w *kqueue) addWatch(name string, flags uint32, listDir bool) (string, error) {
+ if w.isClosed() {
return "", ErrClosed
}
- watchfd, alreadyWatching := w.watches[name]
- // We already have a watch, but we can still override flags.
- if alreadyWatching {
- isDir = w.paths[watchfd].isDir
- }
- w.mu.Unlock()
+ name = filepath.Clean(name)
+
+ info, alreadyWatching := w.watches.byPath(name)
if !alreadyWatching {
fi, err := os.Lstat(name)
if err != nil {
return "", err
}
- // Don't watch sockets or named pipes
+ // Don't watch sockets or named pipes.
if (fi.Mode()&os.ModeSocket == os.ModeSocket) || (fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe) {
return "", nil
}
- // Follow Symlinks.
- if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
+ // Follow symlinks, but only for paths added with Add(), and not paths
+ // we're adding from internalWatch from a listdir.
+ if !listDir && fi.Mode()&os.ModeSymlink == os.ModeSymlink {
link, err := os.Readlink(name)
if err != nil {
- // Return nil because Linux can add unresolvable symlinks to the
- // watch list without problems, so maintain consistency with
- // that. There will be no file events for broken symlinks.
- // TODO: more specific check; returns os.PathError; ENOENT?
- return "", nil
+ return "", err
+ }
+ if !filepath.IsAbs(link) {
+ link = filepath.Join(filepath.Dir(name), link)
}
- w.mu.Lock()
- _, alreadyWatching = w.watches[link]
- w.mu.Unlock()
-
+ _, alreadyWatching = w.watches.byPath(link)
if alreadyWatching {
// Add to watches so we don't get spurious Create events later
// on when we diff the directories.
- w.watches[name] = 0
- w.fileExists[name] = struct{}{}
+ w.watches.addLink(name, 0)
return link, nil
}
+ info.linkName = name
name = link
fi, err = os.Lstat(name)
if err != nil {
- return "", nil
+ return "", err
}
}
// Retry on EINTR; open() can return EINTR in practice on macOS.
// See #354, and Go issues 11180 and 39237.
for {
- watchfd, err = unix.Open(name, openMode, 0)
+ info.wd, err = unix.Open(name, openMode, 0)
if err == nil {
break
}
if errors.Is(err, unix.EINTR) {
continue
}
-
return "", err
}
- isDir = fi.IsDir()
+ info.isDir = fi.IsDir()
}
- err := w.register([]int{watchfd}, unix.EV_ADD|unix.EV_CLEAR|unix.EV_ENABLE, flags)
+ err := w.register([]int{info.wd}, unix.EV_ADD|unix.EV_CLEAR|unix.EV_ENABLE, flags)
if err != nil {
- unix.Close(watchfd)
+ unix.Close(info.wd)
return "", err
}
if !alreadyWatching {
- w.mu.Lock()
- parentName := filepath.Dir(name)
- w.watches[name] = watchfd
-
- watchesByDir, ok := w.watchesByDir[parentName]
- if !ok {
- watchesByDir = make(map[int]struct{}, 1)
- w.watchesByDir[parentName] = watchesByDir
- }
- watchesByDir[watchfd] = struct{}{}
- w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
- w.mu.Unlock()
+ w.watches.add(name, info.linkName, info.wd, info.isDir)
}
- if isDir {
- // Watch the directory if it has not been watched before, or if it was
- // watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
- w.mu.Lock()
-
+ // Watch the directory if it has not been watched before, or if it was
+ // watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
+ if info.isDir {
watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE &&
- (!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE)
- // Store flags so this watch can be updated later
- w.dirFlags[name] = flags
- w.mu.Unlock()
+ (!alreadyWatching || (info.dirFlags&unix.NOTE_WRITE) != unix.NOTE_WRITE)
+ if !w.watches.updateDirFlags(name, flags) {
+ return "", nil
+ }
if watchDir {
- if err := w.watchDirectoryFiles(name); err != nil {
+ d := name
+ if info.linkName != "" {
+ d = info.linkName
+ }
+ if err := w.watchDirectoryFiles(d); err != nil {
return "", err
}
}
@@ -534,7 +426,7 @@ func (w *Watcher) addWatch(name string, flags uint32) (string, error) {
// readEvents reads from kqueue and converts the received kevents into
// Event values that it sends down the Events channel.
-func (w *Watcher) readEvents() {
+func (w *kqueue) readEvents() {
defer func() {
close(w.Events)
close(w.Errors)
@@ -543,50 +435,65 @@ func (w *Watcher) readEvents() {
}()
eventBuffer := make([]unix.Kevent_t, 10)
- for closed := false; !closed; {
+ for {
kevents, err := w.read(eventBuffer)
// EINTR is okay, the syscall was interrupted before timeout expired.
if err != nil && err != unix.EINTR {
if !w.sendError(fmt.Errorf("fsnotify.readEvents: %w", err)) {
- closed = true
+ return
}
- continue
}
- // Flush the events we received to the Events channel
for _, kevent := range kevents {
var (
- watchfd = int(kevent.Ident)
- mask = uint32(kevent.Fflags)
+ wd = int(kevent.Ident)
+ mask = uint32(kevent.Fflags)
)
// Shut down the loop when the pipe is closed, but only after all
// other events have been processed.
- if watchfd == w.closepipe[0] {
- closed = true
+ if wd == w.closepipe[0] {
+ return
+ }
+
+ path, ok := w.watches.byWd(wd)
+ if debug {
+ internal.Debug(path.name, &kevent)
+ }
+
+ // On macOS it seems that sometimes an event with Ident=0 is
+ // delivered, and no other flags/information beyond that, even
+ // though we never saw such a file descriptor. For example in
+ // TestWatchSymlink/277 (usually at the end, but sometimes sooner):
+ //
+ // fmt.Printf("READ: %2d %#v\n", kevent.Ident, kevent)
+ // unix.Kevent_t{Ident:0x2a, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)}
+ // unix.Kevent_t{Ident:0x0, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)}
+ //
+ // The first is a normal event, the second with Ident 0. No error
+ // flag, no data, no ... nothing.
+ //
+ // I read a bit through bsd/kern_event.c from the xnu source, but I
+ // don't really see an obvious location where this is triggered –
+ // this doesn't seem intentional, but idk...
+ //
+ // Technically fd 0 is a valid descriptor, so only skip it if
+ // there's no path, and if we're on macOS.
+ if !ok && kevent.Ident == 0 && runtime.GOOS == "darwin" {
continue
}
- w.mu.Lock()
- path := w.paths[watchfd]
- w.mu.Unlock()
-
- event := w.newEvent(path.name, mask)
+ event := w.newEvent(path.name, path.linkName, mask)
if event.Has(Rename) || event.Has(Remove) {
w.remove(event.Name, false)
- w.mu.Lock()
- delete(w.fileExists, event.Name)
- w.mu.Unlock()
+ w.watches.markSeen(event.Name, false)
}
if path.isDir && event.Has(Write) && !event.Has(Remove) {
- w.sendDirectoryChangeEvents(event.Name)
- } else {
- if !w.sendEvent(event) {
- closed = true
- continue
- }
+ w.dirChange(event.Name)
+ } else if !w.sendEvent(event) {
+ return
}
if event.Has(Remove) {
@@ -594,25 +501,34 @@ func (w *Watcher) readEvents() {
// mv f1 f2 will delete f2, then create f2.
if path.isDir {
fileDir := filepath.Clean(event.Name)
- w.mu.Lock()
- _, found := w.watches[fileDir]
- w.mu.Unlock()
+ _, found := w.watches.byPath(fileDir)
if found {
- err := w.sendDirectoryChangeEvents(fileDir)
- if err != nil {
- if !w.sendError(err) {
- closed = true
- }
+ // TODO: this branch is never triggered in any test.
+ // Added in d6220df (2012).
+ // isDir check added in 8611c35 (2016): https://github.com/fsnotify/fsnotify/pull/111
+ //
+ // I don't really get how this can be triggered either.
+ // And it wasn't triggered in the patch that added it,
+ // either.
+ //
+ // Original also had a comment:
+ // make sure the directory exists before we watch for
+ // changes. When we do a recursive watch and perform
+ // rm -rf, the parent directory might have gone
+ // missing, ignore the missing directory and let the
+ // upcoming delete event remove the watch from the
+ // parent directory.
+ err := w.dirChange(fileDir)
+ if !w.sendError(err) {
+ return
}
}
} else {
- filePath := filepath.Clean(event.Name)
- if fi, err := os.Lstat(filePath); err == nil {
- err := w.sendFileCreatedEventIfNew(filePath, fi)
- if err != nil {
- if !w.sendError(err) {
- closed = true
- }
+ path := filepath.Clean(event.Name)
+ if fi, err := os.Lstat(path); err == nil {
+ err := w.sendCreateIfNew(path, fi)
+ if !w.sendError(err) {
+ return
}
}
}
@@ -622,8 +538,14 @@ func (w *Watcher) readEvents() {
}
// newEvent returns an platform-independent Event based on kqueue Fflags.
-func (w *Watcher) newEvent(name string, mask uint32) Event {
+func (w *kqueue) newEvent(name, linkName string, mask uint32) Event {
e := Event{Name: name}
+ if linkName != "" {
+ // If the user watched "/path/link" then emit events as "/path/link"
+ // rather than "/path/target".
+ e.Name = linkName
+ }
+
if mask&unix.NOTE_DELETE == unix.NOTE_DELETE {
e.Op |= Remove
}
@@ -645,8 +567,7 @@ func (w *Watcher) newEvent(name string, mask uint32) Event {
}
// watchDirectoryFiles to mimic inotify when adding a watch on a directory
-func (w *Watcher) watchDirectoryFiles(dirPath string) error {
- // Get all files
+func (w *kqueue) watchDirectoryFiles(dirPath string) error {
files, err := os.ReadDir(dirPath)
if err != nil {
return err
@@ -674,9 +595,7 @@ func (w *Watcher) watchDirectoryFiles(dirPath string) error {
}
}
- w.mu.Lock()
- w.fileExists[cleanPath] = struct{}{}
- w.mu.Unlock()
+ w.watches.markSeen(cleanPath, true)
}
return nil
@@ -686,7 +605,7 @@ func (w *Watcher) watchDirectoryFiles(dirPath string) error {
//
// This functionality is to have the BSD watcher match the inotify, which sends
// a create event for files created in a watched directory.
-func (w *Watcher) sendDirectoryChangeEvents(dir string) error {
+func (w *kqueue) dirChange(dir string) error {
files, err := os.ReadDir(dir)
if err != nil {
// Directory no longer exists: we can ignore this safely. kqueue will
@@ -694,69 +613,62 @@ func (w *Watcher) sendDirectoryChangeEvents(dir string) error {
if errors.Is(err, os.ErrNotExist) {
return nil
}
- return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err)
+ return fmt.Errorf("fsnotify.dirChange %q: %w", dir, err)
}
for _, f := range files {
fi, err := f.Info()
if err != nil {
- return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err)
- }
-
- err = w.sendFileCreatedEventIfNew(filepath.Join(dir, fi.Name()), fi)
- if err != nil {
- // Don't need to send an error if this file isn't readable.
- if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) {
+ if errors.Is(err, os.ErrNotExist) {
return nil
}
- return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err)
+ return fmt.Errorf("fsnotify.dirChange: %w", err)
+ }
+
+ err = w.sendCreateIfNew(filepath.Join(dir, fi.Name()), fi)
+ if err != nil {
+ // Don't need to send an error if this file isn't readable.
+ if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) || errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return fmt.Errorf("fsnotify.dirChange: %w", err)
}
}
return nil
}
-// sendFileCreatedEvent sends a create event if the file isn't already being tracked.
-func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fi os.FileInfo) (err error) {
- w.mu.Lock()
- _, doesExist := w.fileExists[filePath]
- w.mu.Unlock()
- if !doesExist {
- if !w.sendEvent(Event{Name: filePath, Op: Create}) {
- return
+// Send a create event if the file isn't already being tracked, and start
+// watching this file.
+func (w *kqueue) sendCreateIfNew(path string, fi os.FileInfo) error {
+ if !w.watches.seenBefore(path) {
+ if !w.sendEvent(Event{Name: path, Op: Create}) {
+ return nil
}
}
- // like watchDirectoryFiles (but without doing another ReadDir)
- filePath, err = w.internalWatch(filePath, fi)
+ // Like watchDirectoryFiles, but without doing another ReadDir.
+ path, err := w.internalWatch(path, fi)
if err != nil {
return err
}
-
- w.mu.Lock()
- w.fileExists[filePath] = struct{}{}
- w.mu.Unlock()
-
+ w.watches.markSeen(path, true)
return nil
}
-func (w *Watcher) internalWatch(name string, fi os.FileInfo) (string, error) {
+func (w *kqueue) internalWatch(name string, fi os.FileInfo) (string, error) {
if fi.IsDir() {
// mimic Linux providing delete events for subdirectories, but preserve
// the flags used if currently watching subdirectory
- w.mu.Lock()
- flags := w.dirFlags[name]
- w.mu.Unlock()
-
- flags |= unix.NOTE_DELETE | unix.NOTE_RENAME
- return w.addWatch(name, flags)
+ info, _ := w.watches.byPath(name)
+ return w.addWatch(name, info.dirFlags|unix.NOTE_DELETE|unix.NOTE_RENAME, true)
}
- // watch file to mimic Linux inotify
- return w.addWatch(name, noteAllEvents)
+ // Watch file to mimic Linux inotify.
+ return w.addWatch(name, noteAllEvents, true)
}
// Register events with the queue.
-func (w *Watcher) register(fds []int, flags int, fflags uint32) error {
+func (w *kqueue) register(fds []int, flags int, fflags uint32) error {
changes := make([]unix.Kevent_t, len(fds))
for i, fd := range fds {
// SetKevent converts int to the platform-specific types.
@@ -773,10 +685,21 @@ func (w *Watcher) register(fds []int, flags int, fflags uint32) error {
}
// read retrieves pending events, or waits until an event occurs.
-func (w *Watcher) read(events []unix.Kevent_t) ([]unix.Kevent_t, error) {
+func (w *kqueue) read(events []unix.Kevent_t) ([]unix.Kevent_t, error) {
n, err := unix.Kevent(w.kq, nil, events, nil)
if err != nil {
return nil, err
}
return events[0:n], nil
}
+
+func (w *kqueue) xSupports(op Op) bool {
+ //if runtime.GOOS == "freebsd" {
+ // return true // Supports everything.
+ //}
+ if op.Has(xUnportableOpen) || op.Has(xUnportableRead) ||
+ op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) {
+ return false
+ }
+ return true
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_other.go b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_other.go
index d34a23c015..b8c0ad7226 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_other.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_other.go
@@ -1,205 +1,22 @@
//go:build appengine || (!darwin && !dragonfly && !freebsd && !openbsd && !linux && !netbsd && !solaris && !windows)
-// +build appengine !darwin,!dragonfly,!freebsd,!openbsd,!linux,!netbsd,!solaris,!windows
-
-// Note: the documentation on the Watcher type and methods is generated from
-// mkdoc.zsh
package fsnotify
import "errors"
-// Watcher watches a set of paths, delivering events on a channel.
-//
-// A watcher should not be copied (e.g. pass it by pointer, rather than by
-// value).
-//
-// # Linux notes
-//
-// When a file is removed a Remove event won't be emitted until all file
-// descriptors are closed, and deletes will always emit a Chmod. For example:
-//
-// fp := os.Open("file")
-// os.Remove("file") // Triggers Chmod
-// fp.Close() // Triggers Remove
-//
-// This is the event that inotify sends, so not much can be changed about this.
-//
-// The fs.inotify.max_user_watches sysctl variable specifies the upper limit
-// for the number of watches per user, and fs.inotify.max_user_instances
-// specifies the maximum number of inotify instances per user. Every Watcher you
-// create is an "instance", and every path you add is a "watch".
-//
-// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and
-// /proc/sys/fs/inotify/max_user_instances
-//
-// To increase them you can use sysctl or write the value to the /proc file:
-//
-// # Default values on Linux 5.18
-// sysctl fs.inotify.max_user_watches=124983
-// sysctl fs.inotify.max_user_instances=128
-//
-// To make the changes persist on reboot edit /etc/sysctl.conf or
-// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check
-// your distro's documentation):
-//
-// fs.inotify.max_user_watches=124983
-// fs.inotify.max_user_instances=128
-//
-// Reaching the limit will result in a "no space left on device" or "too many open
-// files" error.
-//
-// # kqueue notes (macOS, BSD)
-//
-// kqueue requires opening a file descriptor for every file that's being watched;
-// so if you're watching a directory with five files then that's six file
-// descriptors. You will run in to your system's "max open files" limit faster on
-// these platforms.
-//
-// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to
-// control the maximum number of open files, as well as /etc/login.conf on BSD
-// systems.
-//
-// # Windows notes
-//
-// Paths can be added as "C:\path\to\dir", but forward slashes
-// ("C:/path/to/dir") will also work.
-//
-// When a watched directory is removed it will always send an event for the
-// directory itself, but may not send events for all files in that directory.
-// Sometimes it will send events for all times, sometimes it will send no
-// events, and often only for some files.
-//
-// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest
-// value that is guaranteed to work with SMB filesystems. If you have many
-// events in quick succession this may not be enough, and you will have to use
-// [WithBufferSize] to increase the value.
-type Watcher struct {
- // Events sends the filesystem change events.
- //
- // fsnotify can send the following events; a "path" here can refer to a
- // file, directory, symbolic link, or special file like a FIFO.
- //
- // fsnotify.Create A new path was created; this may be followed by one
- // or more Write events if data also gets written to a
- // file.
- //
- // fsnotify.Remove A path was removed.
- //
- // fsnotify.Rename A path was renamed. A rename is always sent with the
- // old path as Event.Name, and a Create event will be
- // sent with the new name. Renames are only sent for
- // paths that are currently watched; e.g. moving an
- // unmonitored file into a monitored directory will
- // show up as just a Create. Similarly, renaming a file
- // to outside a monitored directory will show up as
- // only a Rename.
- //
- // fsnotify.Write A file or named pipe was written to. A Truncate will
- // also trigger a Write. A single "write action"
- // initiated by the user may show up as one or multiple
- // writes, depending on when the system syncs things to
- // disk. For example when compiling a large Go program
- // you may get hundreds of Write events, and you may
- // want to wait until you've stopped receiving them
- // (see the dedup example in cmd/fsnotify).
- //
- // Some systems may send Write event for directories
- // when the directory content changes.
- //
- // fsnotify.Chmod Attributes were changed. On Linux this is also sent
- // when a file is removed (or more accurately, when a
- // link to an inode is removed). On kqueue it's sent
- // when a file is truncated. On Windows it's never
- // sent.
+type other struct {
Events chan Event
-
- // Errors sends any errors.
- //
- // ErrEventOverflow is used to indicate there are too many events:
- //
- // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl)
- // - windows: The buffer size is too small; WithBufferSize() can be used to increase it.
- // - kqueue, fen: Not used.
Errors chan error
}
-// NewWatcher creates a new Watcher.
-func NewWatcher() (*Watcher, error) {
+var defaultBufferSize = 0
+
+func newBackend(ev chan Event, errs chan error) (backend, error) {
return nil, errors.New("fsnotify not supported on the current platform")
}
-
-// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events
-// channel.
-//
-// The main use case for this is situations with a very large number of events
-// where the kernel buffer size can't be increased (e.g. due to lack of
-// permissions). An unbuffered Watcher will perform better for almost all use
-// cases, and whenever possible you will be better off increasing the kernel
-// buffers instead of adding a large userspace buffer.
-func NewBufferedWatcher(sz uint) (*Watcher, error) { return NewWatcher() }
-
-// Close removes all watches and closes the Events channel.
-func (w *Watcher) Close() error { return nil }
-
-// WatchList returns all paths explicitly added with [Watcher.Add] (and are not
-// yet removed).
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) WatchList() []string { return nil }
-
-// Add starts monitoring the path for changes.
-//
-// A path can only be watched once; watching it more than once is a no-op and will
-// not return an error. Paths that do not yet exist on the filesystem cannot be
-// watched.
-//
-// A watch will be automatically removed if the watched path is deleted or
-// renamed. The exception is the Windows backend, which doesn't remove the
-// watcher on renames.
-//
-// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
-// filesystems (/proc, /sys, etc.) generally don't work.
-//
-// Returns [ErrClosed] if [Watcher.Close] was called.
-//
-// See [Watcher.AddWith] for a version that allows adding options.
-//
-// # Watching directories
-//
-// All files in a directory are monitored, including new files that are created
-// after the watcher is started. Subdirectories are not watched (i.e. it's
-// non-recursive).
-//
-// # Watching files
-//
-// Watching individual files (rather than directories) is generally not
-// recommended as many programs (especially editors) update files atomically: it
-// will write to a temporary file which is then moved to to destination,
-// overwriting the original (or some variant thereof). The watcher on the
-// original file is now lost, as that no longer exists.
-//
-// The upshot of this is that a power failure or crash won't leave a
-// half-written file.
-//
-// Watch the parent directory and use Event.Name to filter out files you're not
-// interested in. There is an example of this in cmd/fsnotify/file.go.
-func (w *Watcher) Add(name string) error { return nil }
-
-// AddWith is like [Watcher.Add], but allows adding options. When using Add()
-// the defaults described below are used.
-//
-// Possible options are:
-//
-// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on
-// other platforms. The default is 64K (65536 bytes).
-func (w *Watcher) AddWith(name string, opts ...addOpt) error { return nil }
-
-// Remove stops monitoring the path for changes.
-//
-// Directories are always removed non-recursively. For example, if you added
-// /tmp/dir and /tmp/dir/subdir then you will need to remove both.
-//
-// Removing a path that has not yet been added returns [ErrNonExistentWatch].
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) Remove(name string) error { return nil }
+func (w *other) Close() error { return nil }
+func (w *other) WatchList() []string { return nil }
+func (w *other) Add(name string) error { return nil }
+func (w *other) AddWith(name string, opts ...addOpt) error { return nil }
+func (w *other) Remove(name string) error { return nil }
+func (w *other) xSupports(op Op) bool { return false }
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_windows.go b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_windows.go
index 9bc91e5d61..3433642d64 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/backend_windows.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/backend_windows.go
@@ -1,12 +1,8 @@
//go:build windows
-// +build windows
// Windows backend based on ReadDirectoryChangesW()
//
// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw
-//
-// Note: the documentation on the Watcher type and methods is generated from
-// mkdoc.zsh
package fsnotify
@@ -19,196 +15,80 @@ import (
"runtime"
"strings"
"sync"
+ "time"
"unsafe"
+ "github.com/fsnotify/fsnotify/internal"
"golang.org/x/sys/windows"
)
-// Watcher watches a set of paths, delivering events on a channel.
-//
-// A watcher should not be copied (e.g. pass it by pointer, rather than by
-// value).
-//
-// # Linux notes
-//
-// When a file is removed a Remove event won't be emitted until all file
-// descriptors are closed, and deletes will always emit a Chmod. For example:
-//
-// fp := os.Open("file")
-// os.Remove("file") // Triggers Chmod
-// fp.Close() // Triggers Remove
-//
-// This is the event that inotify sends, so not much can be changed about this.
-//
-// The fs.inotify.max_user_watches sysctl variable specifies the upper limit
-// for the number of watches per user, and fs.inotify.max_user_instances
-// specifies the maximum number of inotify instances per user. Every Watcher you
-// create is an "instance", and every path you add is a "watch".
-//
-// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and
-// /proc/sys/fs/inotify/max_user_instances
-//
-// To increase them you can use sysctl or write the value to the /proc file:
-//
-// # Default values on Linux 5.18
-// sysctl fs.inotify.max_user_watches=124983
-// sysctl fs.inotify.max_user_instances=128
-//
-// To make the changes persist on reboot edit /etc/sysctl.conf or
-// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check
-// your distro's documentation):
-//
-// fs.inotify.max_user_watches=124983
-// fs.inotify.max_user_instances=128
-//
-// Reaching the limit will result in a "no space left on device" or "too many open
-// files" error.
-//
-// # kqueue notes (macOS, BSD)
-//
-// kqueue requires opening a file descriptor for every file that's being watched;
-// so if you're watching a directory with five files then that's six file
-// descriptors. You will run in to your system's "max open files" limit faster on
-// these platforms.
-//
-// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to
-// control the maximum number of open files, as well as /etc/login.conf on BSD
-// systems.
-//
-// # Windows notes
-//
-// Paths can be added as "C:\path\to\dir", but forward slashes
-// ("C:/path/to/dir") will also work.
-//
-// When a watched directory is removed it will always send an event for the
-// directory itself, but may not send events for all files in that directory.
-// Sometimes it will send events for all times, sometimes it will send no
-// events, and often only for some files.
-//
-// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest
-// value that is guaranteed to work with SMB filesystems. If you have many
-// events in quick succession this may not be enough, and you will have to use
-// [WithBufferSize] to increase the value.
-type Watcher struct {
- // Events sends the filesystem change events.
- //
- // fsnotify can send the following events; a "path" here can refer to a
- // file, directory, symbolic link, or special file like a FIFO.
- //
- // fsnotify.Create A new path was created; this may be followed by one
- // or more Write events if data also gets written to a
- // file.
- //
- // fsnotify.Remove A path was removed.
- //
- // fsnotify.Rename A path was renamed. A rename is always sent with the
- // old path as Event.Name, and a Create event will be
- // sent with the new name. Renames are only sent for
- // paths that are currently watched; e.g. moving an
- // unmonitored file into a monitored directory will
- // show up as just a Create. Similarly, renaming a file
- // to outside a monitored directory will show up as
- // only a Rename.
- //
- // fsnotify.Write A file or named pipe was written to. A Truncate will
- // also trigger a Write. A single "write action"
- // initiated by the user may show up as one or multiple
- // writes, depending on when the system syncs things to
- // disk. For example when compiling a large Go program
- // you may get hundreds of Write events, and you may
- // want to wait until you've stopped receiving them
- // (see the dedup example in cmd/fsnotify).
- //
- // Some systems may send Write event for directories
- // when the directory content changes.
- //
- // fsnotify.Chmod Attributes were changed. On Linux this is also sent
- // when a file is removed (or more accurately, when a
- // link to an inode is removed). On kqueue it's sent
- // when a file is truncated. On Windows it's never
- // sent.
+type readDirChangesW struct {
Events chan Event
-
- // Errors sends any errors.
- //
- // ErrEventOverflow is used to indicate there are too many events:
- //
- // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl)
- // - windows: The buffer size is too small; WithBufferSize() can be used to increase it.
- // - kqueue, fen: Not used.
Errors chan error
port windows.Handle // Handle to completion port
input chan *input // Inputs to the reader are sent on this channel
- quit chan chan<- error
+ done chan chan<- error
mu sync.Mutex // Protects access to watches, closed
watches watchMap // Map of watches (key: i-number)
closed bool // Set to true when Close() is first called
}
-// NewWatcher creates a new Watcher.
-func NewWatcher() (*Watcher, error) {
- return NewBufferedWatcher(50)
-}
+var defaultBufferSize = 50
-// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events
-// channel.
-//
-// The main use case for this is situations with a very large number of events
-// where the kernel buffer size can't be increased (e.g. due to lack of
-// permissions). An unbuffered Watcher will perform better for almost all use
-// cases, and whenever possible you will be better off increasing the kernel
-// buffers instead of adding a large userspace buffer.
-func NewBufferedWatcher(sz uint) (*Watcher, error) {
+func newBackend(ev chan Event, errs chan error) (backend, error) {
port, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 0)
if err != nil {
return nil, os.NewSyscallError("CreateIoCompletionPort", err)
}
- w := &Watcher{
+ w := &readDirChangesW{
+ Events: ev,
+ Errors: errs,
port: port,
watches: make(watchMap),
input: make(chan *input, 1),
- Events: make(chan Event, sz),
- Errors: make(chan error),
- quit: make(chan chan<- error, 1),
+ done: make(chan chan<- error, 1),
}
go w.readEvents()
return w, nil
}
-func (w *Watcher) isClosed() bool {
+func (w *readDirChangesW) isClosed() bool {
w.mu.Lock()
defer w.mu.Unlock()
return w.closed
}
-func (w *Watcher) sendEvent(name string, mask uint64) bool {
+func (w *readDirChangesW) sendEvent(name, renamedFrom string, mask uint64) bool {
if mask == 0 {
return false
}
event := w.newEvent(name, uint32(mask))
+ event.renamedFrom = renamedFrom
select {
- case ch := <-w.quit:
- w.quit <- ch
+ case ch := <-w.done:
+ w.done <- ch
case w.Events <- event:
}
return true
}
// Returns true if the error was sent, or false if watcher is closed.
-func (w *Watcher) sendError(err error) bool {
+func (w *readDirChangesW) sendError(err error) bool {
+ if err == nil {
+ return true
+ }
select {
+ case <-w.done:
+ return false
case w.Errors <- err:
return true
- case <-w.quit:
}
- return false
}
-// Close removes all watches and closes the Events channel.
-func (w *Watcher) Close() error {
+func (w *readDirChangesW) Close() error {
if w.isClosed() {
return nil
}
@@ -217,66 +97,30 @@ func (w *Watcher) Close() error {
w.closed = true
w.mu.Unlock()
- // Send "quit" message to the reader goroutine
+ // Send "done" message to the reader goroutine
ch := make(chan error)
- w.quit <- ch
+ w.done <- ch
if err := w.wakeupReader(); err != nil {
return err
}
return <-ch
}
-// Add starts monitoring the path for changes.
-//
-// A path can only be watched once; watching it more than once is a no-op and will
-// not return an error. Paths that do not yet exist on the filesystem cannot be
-// watched.
-//
-// A watch will be automatically removed if the watched path is deleted or
-// renamed. The exception is the Windows backend, which doesn't remove the
-// watcher on renames.
-//
-// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
-// filesystems (/proc, /sys, etc.) generally don't work.
-//
-// Returns [ErrClosed] if [Watcher.Close] was called.
-//
-// See [Watcher.AddWith] for a version that allows adding options.
-//
-// # Watching directories
-//
-// All files in a directory are monitored, including new files that are created
-// after the watcher is started. Subdirectories are not watched (i.e. it's
-// non-recursive).
-//
-// # Watching files
-//
-// Watching individual files (rather than directories) is generally not
-// recommended as many programs (especially editors) update files atomically: it
-// will write to a temporary file which is then moved to to destination,
-// overwriting the original (or some variant thereof). The watcher on the
-// original file is now lost, as that no longer exists.
-//
-// The upshot of this is that a power failure or crash won't leave a
-// half-written file.
-//
-// Watch the parent directory and use Event.Name to filter out files you're not
-// interested in. There is an example of this in cmd/fsnotify/file.go.
-func (w *Watcher) Add(name string) error { return w.AddWith(name) }
+func (w *readDirChangesW) Add(name string) error { return w.AddWith(name) }
-// AddWith is like [Watcher.Add], but allows adding options. When using Add()
-// the defaults described below are used.
-//
-// Possible options are:
-//
-// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on
-// other platforms. The default is 64K (65536 bytes).
-func (w *Watcher) AddWith(name string, opts ...addOpt) error {
+func (w *readDirChangesW) AddWith(name string, opts ...addOpt) error {
if w.isClosed() {
return ErrClosed
}
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n",
+ time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name))
+ }
with := getOptions(opts...)
+ if !w.xSupports(with.op) {
+ return fmt.Errorf("%w: %s", xErrUnsupported, with.op)
+ }
if with.bufsize < 4096 {
return fmt.Errorf("fsnotify.WithBufferSize: buffer size cannot be smaller than 4096 bytes")
}
@@ -295,18 +139,14 @@ func (w *Watcher) AddWith(name string, opts ...addOpt) error {
return <-in.reply
}
-// Remove stops monitoring the path for changes.
-//
-// Directories are always removed non-recursively. For example, if you added
-// /tmp/dir and /tmp/dir/subdir then you will need to remove both.
-//
-// Removing a path that has not yet been added returns [ErrNonExistentWatch].
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) Remove(name string) error {
+func (w *readDirChangesW) Remove(name string) error {
if w.isClosed() {
return nil
}
+ if debug {
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n",
+ time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name))
+ }
in := &input{
op: opRemoveWatch,
@@ -320,11 +160,7 @@ func (w *Watcher) Remove(name string) error {
return <-in.reply
}
-// WatchList returns all paths explicitly added with [Watcher.Add] (and are not
-// yet removed).
-//
-// Returns nil if [Watcher.Close] was called.
-func (w *Watcher) WatchList() []string {
+func (w *readDirChangesW) WatchList() []string {
if w.isClosed() {
return nil
}
@@ -335,7 +171,13 @@ func (w *Watcher) WatchList() []string {
entries := make([]string, 0, len(w.watches))
for _, entry := range w.watches {
for _, watchEntry := range entry {
- entries = append(entries, watchEntry.path)
+ for name := range watchEntry.names {
+ entries = append(entries, filepath.Join(watchEntry.path, name))
+ }
+ // the directory itself is being watched
+ if watchEntry.mask != 0 {
+ entries = append(entries, watchEntry.path)
+ }
}
}
@@ -361,7 +203,7 @@ const (
sysFSIGNORED = 0x8000
)
-func (w *Watcher) newEvent(name string, mask uint32) Event {
+func (w *readDirChangesW) newEvent(name string, mask uint32) Event {
e := Event{Name: name}
if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO {
e.Op |= Create
@@ -417,7 +259,7 @@ type (
watchMap map[uint32]indexMap
)
-func (w *Watcher) wakeupReader() error {
+func (w *readDirChangesW) wakeupReader() error {
err := windows.PostQueuedCompletionStatus(w.port, 0, 0, nil)
if err != nil {
return os.NewSyscallError("PostQueuedCompletionStatus", err)
@@ -425,7 +267,7 @@ func (w *Watcher) wakeupReader() error {
return nil
}
-func (w *Watcher) getDir(pathname string) (dir string, err error) {
+func (w *readDirChangesW) getDir(pathname string) (dir string, err error) {
attr, err := windows.GetFileAttributes(windows.StringToUTF16Ptr(pathname))
if err != nil {
return "", os.NewSyscallError("GetFileAttributes", err)
@@ -439,7 +281,7 @@ func (w *Watcher) getDir(pathname string) (dir string, err error) {
return
}
-func (w *Watcher) getIno(path string) (ino *inode, err error) {
+func (w *readDirChangesW) getIno(path string) (ino *inode, err error) {
h, err := windows.CreateFile(windows.StringToUTF16Ptr(path),
windows.FILE_LIST_DIRECTORY,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
@@ -482,9 +324,8 @@ func (m watchMap) set(ino *inode, watch *watch) {
}
// Must run within the I/O thread.
-func (w *Watcher) addWatch(pathname string, flags uint64, bufsize int) error {
- //pathname, recurse := recursivePath(pathname)
- recurse := false
+func (w *readDirChangesW) addWatch(pathname string, flags uint64, bufsize int) error {
+ pathname, recurse := recursivePath(pathname)
dir, err := w.getDir(pathname)
if err != nil {
@@ -538,7 +379,7 @@ func (w *Watcher) addWatch(pathname string, flags uint64, bufsize int) error {
}
// Must run within the I/O thread.
-func (w *Watcher) remWatch(pathname string) error {
+func (w *readDirChangesW) remWatch(pathname string) error {
pathname, recurse := recursivePath(pathname)
dir, err := w.getDir(pathname)
@@ -566,11 +407,11 @@ func (w *Watcher) remWatch(pathname string) error {
return fmt.Errorf("%w: %s", ErrNonExistentWatch, pathname)
}
if pathname == dir {
- w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
+ w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED)
watch.mask = 0
} else {
name := filepath.Base(pathname)
- w.sendEvent(filepath.Join(watch.path, name), watch.names[name]&sysFSIGNORED)
+ w.sendEvent(filepath.Join(watch.path, name), "", watch.names[name]&sysFSIGNORED)
delete(watch.names, name)
}
@@ -578,23 +419,23 @@ func (w *Watcher) remWatch(pathname string) error {
}
// Must run within the I/O thread.
-func (w *Watcher) deleteWatch(watch *watch) {
+func (w *readDirChangesW) deleteWatch(watch *watch) {
for name, mask := range watch.names {
if mask&provisional == 0 {
- w.sendEvent(filepath.Join(watch.path, name), mask&sysFSIGNORED)
+ w.sendEvent(filepath.Join(watch.path, name), "", mask&sysFSIGNORED)
}
delete(watch.names, name)
}
if watch.mask != 0 {
if watch.mask&provisional == 0 {
- w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
+ w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED)
}
watch.mask = 0
}
}
// Must run within the I/O thread.
-func (w *Watcher) startRead(watch *watch) error {
+func (w *readDirChangesW) startRead(watch *watch) error {
err := windows.CancelIo(watch.ino.handle)
if err != nil {
w.sendError(os.NewSyscallError("CancelIo", err))
@@ -624,7 +465,7 @@ func (w *Watcher) startRead(watch *watch) error {
err := os.NewSyscallError("ReadDirectoryChanges", rdErr)
if rdErr == windows.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 {
// Watched directory was probably removed
- w.sendEvent(watch.path, watch.mask&sysFSDELETESELF)
+ w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF)
err = nil
}
w.deleteWatch(watch)
@@ -637,7 +478,7 @@ func (w *Watcher) startRead(watch *watch) error {
// readEvents reads from the I/O completion port, converts the
// received events into Event objects and sends them via the Events channel.
// Entry point to the I/O thread.
-func (w *Watcher) readEvents() {
+func (w *readDirChangesW) readEvents() {
var (
n uint32
key uintptr
@@ -652,7 +493,7 @@ func (w *Watcher) readEvents() {
watch := (*watch)(unsafe.Pointer(ov))
if watch == nil {
select {
- case ch := <-w.quit:
+ case ch := <-w.done:
w.mu.Lock()
var indexes []indexMap
for _, index := range w.watches {
@@ -700,7 +541,7 @@ func (w *Watcher) readEvents() {
}
case windows.ERROR_ACCESS_DENIED:
// Watched directory was probably removed
- w.sendEvent(watch.path, watch.mask&sysFSDELETESELF)
+ w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF)
w.deleteWatch(watch)
w.startRead(watch)
continue
@@ -733,6 +574,10 @@ func (w *Watcher) readEvents() {
name := windows.UTF16ToString(buf)
fullname := filepath.Join(watch.path, name)
+ if debug {
+ internal.Debug(fullname, raw.Action)
+ }
+
var mask uint64
switch raw.Action {
case windows.FILE_ACTION_REMOVED:
@@ -761,21 +606,22 @@ func (w *Watcher) readEvents() {
}
}
- sendNameEvent := func() {
- w.sendEvent(fullname, watch.names[name]&mask)
- }
if raw.Action != windows.FILE_ACTION_RENAMED_NEW_NAME {
- sendNameEvent()
+ w.sendEvent(fullname, "", watch.names[name]&mask)
}
if raw.Action == windows.FILE_ACTION_REMOVED {
- w.sendEvent(fullname, watch.names[name]&sysFSIGNORED)
+ w.sendEvent(fullname, "", watch.names[name]&sysFSIGNORED)
delete(watch.names, name)
}
- w.sendEvent(fullname, watch.mask&w.toFSnotifyFlags(raw.Action))
+ if watch.rename != "" && raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME {
+ w.sendEvent(fullname, filepath.Join(watch.path, watch.rename), watch.mask&w.toFSnotifyFlags(raw.Action))
+ } else {
+ w.sendEvent(fullname, "", watch.mask&w.toFSnotifyFlags(raw.Action))
+ }
+
if raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME {
- fullname = filepath.Join(watch.path, watch.rename)
- sendNameEvent()
+ w.sendEvent(filepath.Join(watch.path, watch.rename), "", watch.names[name]&mask)
}
// Move to the next event in the buffer
@@ -787,8 +633,7 @@ func (w *Watcher) readEvents() {
// Error!
if offset >= n {
//lint:ignore ST1005 Windows should be capitalized
- w.sendError(errors.New(
- "Windows system assumed buffer larger than it is, events have likely been missed"))
+ w.sendError(errors.New("Windows system assumed buffer larger than it is, events have likely been missed"))
break
}
}
@@ -799,7 +644,7 @@ func (w *Watcher) readEvents() {
}
}
-func (w *Watcher) toWindowsFlags(mask uint64) uint32 {
+func (w *readDirChangesW) toWindowsFlags(mask uint64) uint32 {
var m uint32
if mask&sysFSMODIFY != 0 {
m |= windows.FILE_NOTIFY_CHANGE_LAST_WRITE
@@ -810,7 +655,7 @@ func (w *Watcher) toWindowsFlags(mask uint64) uint32 {
return m
}
-func (w *Watcher) toFSnotifyFlags(action uint32) uint64 {
+func (w *readDirChangesW) toFSnotifyFlags(action uint32) uint64 {
switch action {
case windows.FILE_ACTION_ADDED:
return sysFSCREATE
@@ -825,3 +670,11 @@ func (w *Watcher) toFSnotifyFlags(action uint32) uint64 {
}
return 0
}
+
+func (w *readDirChangesW) xSupports(op Op) bool {
+ if op.Has(xUnportableOpen) || op.Has(xUnportableRead) ||
+ op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) {
+ return false
+ }
+ return true
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/test/tools/vendor/github.com/fsnotify/fsnotify/fsnotify.go
index 24c99cc499..f64be4bf98 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/fsnotify.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/fsnotify.go
@@ -3,19 +3,146 @@
//
// Currently supported systems:
//
-// Linux 2.6.32+ via inotify
-// BSD, macOS via kqueue
-// Windows via ReadDirectoryChangesW
-// illumos via FEN
+// - Linux via inotify
+// - BSD, macOS via kqueue
+// - Windows via ReadDirectoryChangesW
+// - illumos via FEN
+//
+// # FSNOTIFY_DEBUG
+//
+// Set the FSNOTIFY_DEBUG environment variable to "1" to print debug messages to
+// stderr. This can be useful to track down some problems, especially in cases
+// where fsnotify is used as an indirect dependency.
+//
+// Every event will be printed as soon as there's something useful to print,
+// with as little processing from fsnotify.
+//
+// Example output:
+//
+// FSNOTIFY_DEBUG: 11:34:23.633087586 256:IN_CREATE → "/tmp/file-1"
+// FSNOTIFY_DEBUG: 11:34:23.633202319 4:IN_ATTRIB → "/tmp/file-1"
+// FSNOTIFY_DEBUG: 11:34:28.989728764 512:IN_DELETE → "/tmp/file-1"
package fsnotify
import (
"errors"
"fmt"
+ "os"
"path/filepath"
"strings"
)
+// Watcher watches a set of paths, delivering events on a channel.
+//
+// A watcher should not be copied (e.g. pass it by pointer, rather than by
+// value).
+//
+// # Linux notes
+//
+// When a file is removed a Remove event won't be emitted until all file
+// descriptors are closed, and deletes will always emit a Chmod. For example:
+//
+// fp := os.Open("file")
+// os.Remove("file") // Triggers Chmod
+// fp.Close() // Triggers Remove
+//
+// This is the event that inotify sends, so not much can be changed about this.
+//
+// The fs.inotify.max_user_watches sysctl variable specifies the upper limit
+// for the number of watches per user, and fs.inotify.max_user_instances
+// specifies the maximum number of inotify instances per user. Every Watcher you
+// create is an "instance", and every path you add is a "watch".
+//
+// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and
+// /proc/sys/fs/inotify/max_user_instances
+//
+// To increase them you can use sysctl or write the value to the /proc file:
+//
+// # Default values on Linux 5.18
+// sysctl fs.inotify.max_user_watches=124983
+// sysctl fs.inotify.max_user_instances=128
+//
+// To make the changes persist on reboot edit /etc/sysctl.conf or
+// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check
+// your distro's documentation):
+//
+// fs.inotify.max_user_watches=124983
+// fs.inotify.max_user_instances=128
+//
+// Reaching the limit will result in a "no space left on device" or "too many open
+// files" error.
+//
+// # kqueue notes (macOS, BSD)
+//
+// kqueue requires opening a file descriptor for every file that's being watched;
+// so if you're watching a directory with five files then that's six file
+// descriptors. You will run in to your system's "max open files" limit faster on
+// these platforms.
+//
+// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to
+// control the maximum number of open files, as well as /etc/login.conf on BSD
+// systems.
+//
+// # Windows notes
+//
+// Paths can be added as "C:\\path\\to\\dir", but forward slashes
+// ("C:/path/to/dir") will also work.
+//
+// When a watched directory is removed it will always send an event for the
+// directory itself, but may not send events for all files in that directory.
+// Sometimes it will send events for all files, sometimes it will send no
+// events, and often only for some files.
+//
+// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest
+// value that is guaranteed to work with SMB filesystems. If you have many
+// events in quick succession this may not be enough, and you will have to use
+// [WithBufferSize] to increase the value.
+type Watcher struct {
+ b backend
+
+ // Events sends the filesystem change events.
+ //
+ // fsnotify can send the following events; a "path" here can refer to a
+ // file, directory, symbolic link, or special file like a FIFO.
+ //
+ // fsnotify.Create A new path was created; this may be followed by one
+ // or more Write events if data also gets written to a
+ // file.
+ //
+ // fsnotify.Remove A path was removed.
+ //
+ // fsnotify.Rename A path was renamed. A rename is always sent with the
+ // old path as Event.Name, and a Create event will be
+ // sent with the new name. Renames are only sent for
+ // paths that are currently watched; e.g. moving an
+ // unmonitored file into a monitored directory will
+ // show up as just a Create. Similarly, renaming a file
+ // to outside a monitored directory will show up as
+ // only a Rename.
+ //
+ // fsnotify.Write A file or named pipe was written to. A Truncate will
+ // also trigger a Write. A single "write action"
+ // initiated by the user may show up as one or multiple
+ // writes, depending on when the system syncs things to
+ // disk. For example when compiling a large Go program
+ // you may get hundreds of Write events, and you may
+ // want to wait until you've stopped receiving them
+ // (see the dedup example in cmd/fsnotify).
+ //
+ // Some systems may send Write event for directories
+ // when the directory content changes.
+ //
+ // fsnotify.Chmod Attributes were changed. On Linux this is also sent
+ // when a file is removed (or more accurately, when a
+ // link to an inode is removed). On kqueue it's sent
+ // when a file is truncated. On Windows it's never
+ // sent.
+ Events chan Event
+
+ // Errors sends any errors.
+ Errors chan error
+}
+
// Event represents a file system notification.
type Event struct {
// Path to the file or directory.
@@ -30,6 +157,16 @@ type Event struct {
// This is a bitmask and some systems may send multiple operations at once.
// Use the Event.Has() method instead of comparing with ==.
Op Op
+
+ // Create events will have this set to the old path if it's a rename. This
+ // only works when both the source and destination are watched. It's not
+ // reliable when watching individual files, only directories.
+ //
+ // For example "mv /tmp/file /tmp/rename" will emit:
+ //
+ // Event{Op: Rename, Name: "/tmp/file"}
+ // Event{Op: Create, Name: "/tmp/rename", RenamedFrom: "/tmp/file"}
+ renamedFrom string
}
// Op describes a set of file operations.
@@ -50,7 +187,7 @@ const (
// example "remove to trash" is often a rename).
Remove
- // The path was renamed to something else; any watched on it will be
+ // The path was renamed to something else; any watches on it will be
// removed.
Rename
@@ -60,15 +197,157 @@ const (
// get triggered very frequently by some software. For example, Spotlight
// indexing on macOS, anti-virus software, backup software, etc.
Chmod
+
+ // File descriptor was opened.
+ //
+ // Only works on Linux and FreeBSD.
+ xUnportableOpen
+
+ // File was read from.
+ //
+ // Only works on Linux and FreeBSD.
+ xUnportableRead
+
+ // File opened for writing was closed.
+ //
+ // Only works on Linux and FreeBSD.
+ //
+ // The advantage of using this over Write is that it's more reliable than
+ // waiting for Write events to stop. It's also faster (if you're not
+ // listening to Write events): copying a file of a few GB can easily
+ // generate tens of thousands of Write events in a short span of time.
+ xUnportableCloseWrite
+
+ // File opened for reading was closed.
+ //
+ // Only works on Linux and FreeBSD.
+ xUnportableCloseRead
)
-// Common errors that can be reported.
var (
+ // ErrNonExistentWatch is used when Remove() is called on a path that's not
+ // added.
ErrNonExistentWatch = errors.New("fsnotify: can't remove non-existent watch")
- ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow")
- ErrClosed = errors.New("fsnotify: watcher already closed")
+
+ // ErrClosed is used when trying to operate on a closed Watcher.
+ ErrClosed = errors.New("fsnotify: watcher already closed")
+
+ // ErrEventOverflow is reported from the Errors channel when there are too
+ // many events:
+ //
+ // - inotify: inotify returns IN_Q_OVERFLOW – because there are too
+ // many queued events (the fs.inotify.max_queued_events
+ // sysctl can be used to increase this).
+ // - windows: The buffer size is too small; WithBufferSize() can be used to increase it.
+ // - kqueue, fen: Not used.
+ ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow")
+
+ // ErrUnsupported is returned by AddWith() when WithOps() specified an
+ // Unportable event that's not supported on this platform.
+ //lint:ignore ST1012 not relevant
+ xErrUnsupported = errors.New("fsnotify: not supported with this backend")
)
+// NewWatcher creates a new Watcher.
+func NewWatcher() (*Watcher, error) {
+ ev, errs := make(chan Event, defaultBufferSize), make(chan error)
+ b, err := newBackend(ev, errs)
+ if err != nil {
+ return nil, err
+ }
+ return &Watcher{b: b, Events: ev, Errors: errs}, nil
+}
+
+// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events
+// channel.
+//
+// The main use case for this is situations with a very large number of events
+// where the kernel buffer size can't be increased (e.g. due to lack of
+// permissions). An unbuffered Watcher will perform better for almost all use
+// cases, and whenever possible you will be better off increasing the kernel
+// buffers instead of adding a large userspace buffer.
+func NewBufferedWatcher(sz uint) (*Watcher, error) {
+ ev, errs := make(chan Event, sz), make(chan error)
+ b, err := newBackend(ev, errs)
+ if err != nil {
+ return nil, err
+ }
+ return &Watcher{b: b, Events: ev, Errors: errs}, nil
+}
+
+// Add starts monitoring the path for changes.
+//
+// A path can only be watched once; watching it more than once is a no-op and will
+// not return an error. Paths that do not yet exist on the filesystem cannot be
+// watched.
+//
+// A watch will be automatically removed if the watched path is deleted or
+// renamed. The exception is the Windows backend, which doesn't remove the
+// watcher on renames.
+//
+// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
+// filesystems (/proc, /sys, etc.) generally don't work.
+//
+// Returns [ErrClosed] if [Watcher.Close] was called.
+//
+// See [Watcher.AddWith] for a version that allows adding options.
+//
+// # Watching directories
+//
+// All files in a directory are monitored, including new files that are created
+// after the watcher is started. Subdirectories are not watched (i.e. it's
+// non-recursive).
+//
+// # Watching files
+//
+// Watching individual files (rather than directories) is generally not
+// recommended as many programs (especially editors) update files atomically: it
+// will write to a temporary file which is then moved to destination,
+// overwriting the original (or some variant thereof). The watcher on the
+// original file is now lost, as that no longer exists.
+//
+// The upshot of this is that a power failure or crash won't leave a
+// half-written file.
+//
+// Watch the parent directory and use Event.Name to filter out files you're not
+// interested in. There is an example of this in cmd/fsnotify/file.go.
+func (w *Watcher) Add(path string) error { return w.b.Add(path) }
+
+// AddWith is like [Watcher.Add], but allows adding options. When using Add()
+// the defaults described below are used.
+//
+// Possible options are:
+//
+// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on
+// other platforms. The default is 64K (65536 bytes).
+func (w *Watcher) AddWith(path string, opts ...addOpt) error { return w.b.AddWith(path, opts...) }
+
+// Remove stops monitoring the path for changes.
+//
+// Directories are always removed non-recursively. For example, if you added
+// /tmp/dir and /tmp/dir/subdir then you will need to remove both.
+//
+// Removing a path that has not yet been added returns [ErrNonExistentWatch].
+//
+// Returns nil if [Watcher.Close] was called.
+func (w *Watcher) Remove(path string) error { return w.b.Remove(path) }
+
+// Close removes all watches and closes the Events channel.
+func (w *Watcher) Close() error { return w.b.Close() }
+
+// WatchList returns all paths explicitly added with [Watcher.Add] (and are not
+// yet removed).
+//
+// The order is undefined, and may differ per call. Returns nil if
+// [Watcher.Close] was called.
+func (w *Watcher) WatchList() []string { return w.b.WatchList() }
+
+// Supports reports if all the listed operations are supported by this platform.
+//
+// Create, Write, Remove, Rename, and Chmod are always supported. It can only
+// return false for an Op starting with Unportable.
+func (w *Watcher) xSupports(op Op) bool { return w.b.xSupports(op) }
+
func (o Op) String() string {
var b strings.Builder
if o.Has(Create) {
@@ -80,6 +359,18 @@ func (o Op) String() string {
if o.Has(Write) {
b.WriteString("|WRITE")
}
+ if o.Has(xUnportableOpen) {
+ b.WriteString("|OPEN")
+ }
+ if o.Has(xUnportableRead) {
+ b.WriteString("|READ")
+ }
+ if o.Has(xUnportableCloseWrite) {
+ b.WriteString("|CLOSE_WRITE")
+ }
+ if o.Has(xUnportableCloseRead) {
+ b.WriteString("|CLOSE_READ")
+ }
if o.Has(Rename) {
b.WriteString("|RENAME")
}
@@ -100,24 +391,48 @@ func (e Event) Has(op Op) bool { return e.Op.Has(op) }
// String returns a string representation of the event with their path.
func (e Event) String() string {
+ if e.renamedFrom != "" {
+ return fmt.Sprintf("%-13s %q ← %q", e.Op.String(), e.Name, e.renamedFrom)
+ }
return fmt.Sprintf("%-13s %q", e.Op.String(), e.Name)
}
type (
+ backend interface {
+ Add(string) error
+ AddWith(string, ...addOpt) error
+ Remove(string) error
+ WatchList() []string
+ Close() error
+ xSupports(Op) bool
+ }
addOpt func(opt *withOpts)
withOpts struct {
- bufsize int
+ bufsize int
+ op Op
+ noFollow bool
+ sendCreate bool
}
)
+var debug = func() bool {
+ // Check for exactly "1" (rather than mere existence) so we can add
+ // options/flags in the future. I don't know if we ever want that, but it's
+ // nice to leave the option open.
+ return os.Getenv("FSNOTIFY_DEBUG") == "1"
+}()
+
var defaultOpts = withOpts{
bufsize: 65536, // 64K
+ op: Create | Write | Remove | Rename | Chmod,
}
func getOptions(opts ...addOpt) withOpts {
with := defaultOpts
for _, o := range opts {
- o(&with)
+ if o != nil {
+ o(&with)
+ }
}
return with
}
@@ -136,9 +451,44 @@ func WithBufferSize(bytes int) addOpt {
return func(opt *withOpts) { opt.bufsize = bytes }
}
+// WithOps sets which operations to listen for. The default is [Create],
+// [Write], [Remove], [Rename], and [Chmod].
+//
+// Excluding operations you're not interested in can save quite a bit of CPU
+// time; in some use cases there may be hundreds of thousands of useless Write
+// or Chmod operations per second.
+//
+// This can also be used to add unportable operations not supported by all
+// platforms; unportable operations all start with "Unportable":
+// [UnportableOpen], [UnportableRead], [UnportableCloseWrite], and
+// [UnportableCloseRead].
+//
+// AddWith returns an error when using an unportable operation that's not
+// supported. Use [Watcher.Support] to check for support.
+func withOps(op Op) addOpt {
+ return func(opt *withOpts) { opt.op = op }
+}
+
+// WithNoFollow disables following symlinks, so the symlinks themselves are
+// watched.
+func withNoFollow() addOpt {
+ return func(opt *withOpts) { opt.noFollow = true }
+}
+
+// "Internal" option for recursive watches on inotify.
+func withCreate() addOpt {
+ return func(opt *withOpts) { opt.sendCreate = true }
+}
+
+var enableRecurse = false
+
// Check if this path is recursive (ends with "/..." or "\..."), and return the
// path with the /... stripped.
func recursivePath(path string) (string, bool) {
+ path = filepath.Clean(path)
+ if !enableRecurse { // Only enabled in tests for now.
+ return path, false
+ }
if filepath.Base(path) == "..." {
return filepath.Dir(path), true
}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/darwin.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/darwin.go
new file mode 100644
index 0000000000..0b01bc182a
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/darwin.go
@@ -0,0 +1,39 @@
+//go:build darwin
+
+package internal
+
+import (
+ "syscall"
+
+ "golang.org/x/sys/unix"
+)
+
+var (
+ ErrSyscallEACCES = syscall.EACCES
+ ErrUnixEACCES = unix.EACCES
+)
+
+var maxfiles uint64
+
+func SetRlimit() {
+ // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/
+ var l syscall.Rlimit
+ err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l)
+ if err == nil && l.Cur != l.Max {
+ l.Cur = l.Max
+ syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l)
+ }
+ maxfiles = l.Cur
+
+ if n, err := syscall.SysctlUint32("kern.maxfiles"); err == nil && uint64(n) < maxfiles {
+ maxfiles = uint64(n)
+ }
+
+ if n, err := syscall.SysctlUint32("kern.maxfilesperproc"); err == nil && uint64(n) < maxfiles {
+ maxfiles = uint64(n)
+ }
+}
+
+func Maxfiles() uint64 { return maxfiles }
+func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) }
+func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) }
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go
new file mode 100644
index 0000000000..928319fb09
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go
@@ -0,0 +1,57 @@
+package internal
+
+import "golang.org/x/sys/unix"
+
+var names = []struct {
+ n string
+ m uint32
+}{
+ {"NOTE_ABSOLUTE", unix.NOTE_ABSOLUTE},
+ {"NOTE_ATTRIB", unix.NOTE_ATTRIB},
+ {"NOTE_BACKGROUND", unix.NOTE_BACKGROUND},
+ {"NOTE_CHILD", unix.NOTE_CHILD},
+ {"NOTE_CRITICAL", unix.NOTE_CRITICAL},
+ {"NOTE_DELETE", unix.NOTE_DELETE},
+ {"NOTE_EXEC", unix.NOTE_EXEC},
+ {"NOTE_EXIT", unix.NOTE_EXIT},
+ {"NOTE_EXITSTATUS", unix.NOTE_EXITSTATUS},
+ {"NOTE_EXIT_CSERROR", unix.NOTE_EXIT_CSERROR},
+ {"NOTE_EXIT_DECRYPTFAIL", unix.NOTE_EXIT_DECRYPTFAIL},
+ {"NOTE_EXIT_DETAIL", unix.NOTE_EXIT_DETAIL},
+ {"NOTE_EXIT_DETAIL_MASK", unix.NOTE_EXIT_DETAIL_MASK},
+ {"NOTE_EXIT_MEMORY", unix.NOTE_EXIT_MEMORY},
+ {"NOTE_EXIT_REPARENTED", unix.NOTE_EXIT_REPARENTED},
+ {"NOTE_EXTEND", unix.NOTE_EXTEND},
+ {"NOTE_FFAND", unix.NOTE_FFAND},
+ {"NOTE_FFCOPY", unix.NOTE_FFCOPY},
+ {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK},
+ {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK},
+ {"NOTE_FFNOP", unix.NOTE_FFNOP},
+ {"NOTE_FFOR", unix.NOTE_FFOR},
+ {"NOTE_FORK", unix.NOTE_FORK},
+ {"NOTE_FUNLOCK", unix.NOTE_FUNLOCK},
+ {"NOTE_LEEWAY", unix.NOTE_LEEWAY},
+ {"NOTE_LINK", unix.NOTE_LINK},
+ {"NOTE_LOWAT", unix.NOTE_LOWAT},
+ {"NOTE_MACHTIME", unix.NOTE_MACHTIME},
+ {"NOTE_MACH_CONTINUOUS_TIME", unix.NOTE_MACH_CONTINUOUS_TIME},
+ {"NOTE_NONE", unix.NOTE_NONE},
+ {"NOTE_NSECONDS", unix.NOTE_NSECONDS},
+ {"NOTE_OOB", unix.NOTE_OOB},
+ //{"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, -0x100000 (?!)
+ {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK},
+ {"NOTE_REAP", unix.NOTE_REAP},
+ {"NOTE_RENAME", unix.NOTE_RENAME},
+ {"NOTE_REVOKE", unix.NOTE_REVOKE},
+ {"NOTE_SECONDS", unix.NOTE_SECONDS},
+ {"NOTE_SIGNAL", unix.NOTE_SIGNAL},
+ {"NOTE_TRACK", unix.NOTE_TRACK},
+ {"NOTE_TRACKERR", unix.NOTE_TRACKERR},
+ {"NOTE_TRIGGER", unix.NOTE_TRIGGER},
+ {"NOTE_USECONDS", unix.NOTE_USECONDS},
+ {"NOTE_VM_ERROR", unix.NOTE_VM_ERROR},
+ {"NOTE_VM_PRESSURE", unix.NOTE_VM_PRESSURE},
+ {"NOTE_VM_PRESSURE_SUDDEN_TERMINATE", unix.NOTE_VM_PRESSURE_SUDDEN_TERMINATE},
+ {"NOTE_VM_PRESSURE_TERMINATE", unix.NOTE_VM_PRESSURE_TERMINATE},
+ {"NOTE_WRITE", unix.NOTE_WRITE},
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go
new file mode 100644
index 0000000000..3186b0c349
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go
@@ -0,0 +1,33 @@
+package internal
+
+import "golang.org/x/sys/unix"
+
+var names = []struct {
+ n string
+ m uint32
+}{
+ {"NOTE_ATTRIB", unix.NOTE_ATTRIB},
+ {"NOTE_CHILD", unix.NOTE_CHILD},
+ {"NOTE_DELETE", unix.NOTE_DELETE},
+ {"NOTE_EXEC", unix.NOTE_EXEC},
+ {"NOTE_EXIT", unix.NOTE_EXIT},
+ {"NOTE_EXTEND", unix.NOTE_EXTEND},
+ {"NOTE_FFAND", unix.NOTE_FFAND},
+ {"NOTE_FFCOPY", unix.NOTE_FFCOPY},
+ {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK},
+ {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK},
+ {"NOTE_FFNOP", unix.NOTE_FFNOP},
+ {"NOTE_FFOR", unix.NOTE_FFOR},
+ {"NOTE_FORK", unix.NOTE_FORK},
+ {"NOTE_LINK", unix.NOTE_LINK},
+ {"NOTE_LOWAT", unix.NOTE_LOWAT},
+ {"NOTE_OOB", unix.NOTE_OOB},
+ {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK},
+ {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK},
+ {"NOTE_RENAME", unix.NOTE_RENAME},
+ {"NOTE_REVOKE", unix.NOTE_REVOKE},
+ {"NOTE_TRACK", unix.NOTE_TRACK},
+ {"NOTE_TRACKERR", unix.NOTE_TRACKERR},
+ {"NOTE_TRIGGER", unix.NOTE_TRIGGER},
+ {"NOTE_WRITE", unix.NOTE_WRITE},
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go
new file mode 100644
index 0000000000..f69fdb930f
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go
@@ -0,0 +1,42 @@
+package internal
+
+import "golang.org/x/sys/unix"
+
+var names = []struct {
+ n string
+ m uint32
+}{
+ {"NOTE_ABSTIME", unix.NOTE_ABSTIME},
+ {"NOTE_ATTRIB", unix.NOTE_ATTRIB},
+ {"NOTE_CHILD", unix.NOTE_CHILD},
+ {"NOTE_CLOSE", unix.NOTE_CLOSE},
+ {"NOTE_CLOSE_WRITE", unix.NOTE_CLOSE_WRITE},
+ {"NOTE_DELETE", unix.NOTE_DELETE},
+ {"NOTE_EXEC", unix.NOTE_EXEC},
+ {"NOTE_EXIT", unix.NOTE_EXIT},
+ {"NOTE_EXTEND", unix.NOTE_EXTEND},
+ {"NOTE_FFAND", unix.NOTE_FFAND},
+ {"NOTE_FFCOPY", unix.NOTE_FFCOPY},
+ {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK},
+ {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK},
+ {"NOTE_FFNOP", unix.NOTE_FFNOP},
+ {"NOTE_FFOR", unix.NOTE_FFOR},
+ {"NOTE_FILE_POLL", unix.NOTE_FILE_POLL},
+ {"NOTE_FORK", unix.NOTE_FORK},
+ {"NOTE_LINK", unix.NOTE_LINK},
+ {"NOTE_LOWAT", unix.NOTE_LOWAT},
+ {"NOTE_MSECONDS", unix.NOTE_MSECONDS},
+ {"NOTE_NSECONDS", unix.NOTE_NSECONDS},
+ {"NOTE_OPEN", unix.NOTE_OPEN},
+ {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK},
+ {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK},
+ {"NOTE_READ", unix.NOTE_READ},
+ {"NOTE_RENAME", unix.NOTE_RENAME},
+ {"NOTE_REVOKE", unix.NOTE_REVOKE},
+ {"NOTE_SECONDS", unix.NOTE_SECONDS},
+ {"NOTE_TRACK", unix.NOTE_TRACK},
+ {"NOTE_TRACKERR", unix.NOTE_TRACKERR},
+ {"NOTE_TRIGGER", unix.NOTE_TRIGGER},
+ {"NOTE_USECONDS", unix.NOTE_USECONDS},
+ {"NOTE_WRITE", unix.NOTE_WRITE},
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go
new file mode 100644
index 0000000000..607e683bd7
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go
@@ -0,0 +1,32 @@
+//go:build freebsd || openbsd || netbsd || dragonfly || darwin
+
+package internal
+
+import (
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+func Debug(name string, kevent *unix.Kevent_t) {
+ mask := uint32(kevent.Fflags)
+
+ var (
+ l []string
+ unknown = mask
+ )
+ for _, n := range names {
+ if mask&n.m == n.m {
+ l = append(l, n.n)
+ unknown ^= n.m
+ }
+ }
+ if unknown > 0 {
+ l = append(l, fmt.Sprintf("0x%x", unknown))
+ }
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-60s → %q\n",
+ time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name)
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go
new file mode 100644
index 0000000000..35c734be43
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go
@@ -0,0 +1,56 @@
+package internal
+
+import (
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+func Debug(name string, mask, cookie uint32) {
+ names := []struct {
+ n string
+ m uint32
+ }{
+ {"IN_ACCESS", unix.IN_ACCESS},
+ {"IN_ATTRIB", unix.IN_ATTRIB},
+ {"IN_CLOSE", unix.IN_CLOSE},
+ {"IN_CLOSE_NOWRITE", unix.IN_CLOSE_NOWRITE},
+ {"IN_CLOSE_WRITE", unix.IN_CLOSE_WRITE},
+ {"IN_CREATE", unix.IN_CREATE},
+ {"IN_DELETE", unix.IN_DELETE},
+ {"IN_DELETE_SELF", unix.IN_DELETE_SELF},
+ {"IN_IGNORED", unix.IN_IGNORED},
+ {"IN_ISDIR", unix.IN_ISDIR},
+ {"IN_MODIFY", unix.IN_MODIFY},
+ {"IN_MOVE", unix.IN_MOVE},
+ {"IN_MOVED_FROM", unix.IN_MOVED_FROM},
+ {"IN_MOVED_TO", unix.IN_MOVED_TO},
+ {"IN_MOVE_SELF", unix.IN_MOVE_SELF},
+ {"IN_OPEN", unix.IN_OPEN},
+ {"IN_Q_OVERFLOW", unix.IN_Q_OVERFLOW},
+ {"IN_UNMOUNT", unix.IN_UNMOUNT},
+ }
+
+ var (
+ l []string
+ unknown = mask
+ )
+ for _, n := range names {
+ if mask&n.m == n.m {
+ l = append(l, n.n)
+ unknown ^= n.m
+ }
+ }
+ if unknown > 0 {
+ l = append(l, fmt.Sprintf("0x%x", unknown))
+ }
+ var c string
+ if cookie > 0 {
+ c = fmt.Sprintf("(cookie: %d) ", cookie)
+ }
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-30s → %s%q\n",
+ time.Now().Format("15:04:05.000000000"), strings.Join(l, "|"), c, name)
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go
new file mode 100644
index 0000000000..e5b3b6f694
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go
@@ -0,0 +1,25 @@
+package internal
+
+import "golang.org/x/sys/unix"
+
+var names = []struct {
+ n string
+ m uint32
+}{
+ {"NOTE_ATTRIB", unix.NOTE_ATTRIB},
+ {"NOTE_CHILD", unix.NOTE_CHILD},
+ {"NOTE_DELETE", unix.NOTE_DELETE},
+ {"NOTE_EXEC", unix.NOTE_EXEC},
+ {"NOTE_EXIT", unix.NOTE_EXIT},
+ {"NOTE_EXTEND", unix.NOTE_EXTEND},
+ {"NOTE_FORK", unix.NOTE_FORK},
+ {"NOTE_LINK", unix.NOTE_LINK},
+ {"NOTE_LOWAT", unix.NOTE_LOWAT},
+ {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK},
+ {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK},
+ {"NOTE_RENAME", unix.NOTE_RENAME},
+ {"NOTE_REVOKE", unix.NOTE_REVOKE},
+ {"NOTE_TRACK", unix.NOTE_TRACK},
+ {"NOTE_TRACKERR", unix.NOTE_TRACKERR},
+ {"NOTE_WRITE", unix.NOTE_WRITE},
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go
new file mode 100644
index 0000000000..1dd455bc5a
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go
@@ -0,0 +1,28 @@
+package internal
+
+import "golang.org/x/sys/unix"
+
+var names = []struct {
+ n string
+ m uint32
+}{
+ {"NOTE_ATTRIB", unix.NOTE_ATTRIB},
+ // {"NOTE_CHANGE", unix.NOTE_CHANGE}, // Not on 386?
+ {"NOTE_CHILD", unix.NOTE_CHILD},
+ {"NOTE_DELETE", unix.NOTE_DELETE},
+ {"NOTE_EOF", unix.NOTE_EOF},
+ {"NOTE_EXEC", unix.NOTE_EXEC},
+ {"NOTE_EXIT", unix.NOTE_EXIT},
+ {"NOTE_EXTEND", unix.NOTE_EXTEND},
+ {"NOTE_FORK", unix.NOTE_FORK},
+ {"NOTE_LINK", unix.NOTE_LINK},
+ {"NOTE_LOWAT", unix.NOTE_LOWAT},
+ {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK},
+ {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK},
+ {"NOTE_RENAME", unix.NOTE_RENAME},
+ {"NOTE_REVOKE", unix.NOTE_REVOKE},
+ {"NOTE_TRACK", unix.NOTE_TRACK},
+ {"NOTE_TRACKERR", unix.NOTE_TRACKERR},
+ {"NOTE_TRUNCATE", unix.NOTE_TRUNCATE},
+ {"NOTE_WRITE", unix.NOTE_WRITE},
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go
new file mode 100644
index 0000000000..f1b2e73bd5
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go
@@ -0,0 +1,45 @@
+package internal
+
+import (
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+func Debug(name string, mask int32) {
+ names := []struct {
+ n string
+ m int32
+ }{
+ {"FILE_ACCESS", unix.FILE_ACCESS},
+ {"FILE_MODIFIED", unix.FILE_MODIFIED},
+ {"FILE_ATTRIB", unix.FILE_ATTRIB},
+ {"FILE_TRUNC", unix.FILE_TRUNC},
+ {"FILE_NOFOLLOW", unix.FILE_NOFOLLOW},
+ {"FILE_DELETE", unix.FILE_DELETE},
+ {"FILE_RENAME_TO", unix.FILE_RENAME_TO},
+ {"FILE_RENAME_FROM", unix.FILE_RENAME_FROM},
+ {"UNMOUNTED", unix.UNMOUNTED},
+ {"MOUNTEDOVER", unix.MOUNTEDOVER},
+ {"FILE_EXCEPTION", unix.FILE_EXCEPTION},
+ }
+
+ var (
+ l []string
+ unknown = mask
+ )
+ for _, n := range names {
+ if mask&n.m == n.m {
+ l = append(l, n.n)
+ unknown ^= n.m
+ }
+ }
+ if unknown > 0 {
+ l = append(l, fmt.Sprintf("0x%x", unknown))
+ }
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-30s → %q\n",
+ time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name)
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go
new file mode 100644
index 0000000000..52bf4ce53b
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go
@@ -0,0 +1,40 @@
+package internal
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "golang.org/x/sys/windows"
+)
+
+func Debug(name string, mask uint32) {
+ names := []struct {
+ n string
+ m uint32
+ }{
+ {"FILE_ACTION_ADDED", windows.FILE_ACTION_ADDED},
+ {"FILE_ACTION_REMOVED", windows.FILE_ACTION_REMOVED},
+ {"FILE_ACTION_MODIFIED", windows.FILE_ACTION_MODIFIED},
+ {"FILE_ACTION_RENAMED_OLD_NAME", windows.FILE_ACTION_RENAMED_OLD_NAME},
+ {"FILE_ACTION_RENAMED_NEW_NAME", windows.FILE_ACTION_RENAMED_NEW_NAME},
+ }
+
+ var (
+ l []string
+ unknown = mask
+ )
+ for _, n := range names {
+ if mask&n.m == n.m {
+ l = append(l, n.n)
+ unknown ^= n.m
+ }
+ }
+ if unknown > 0 {
+ l = append(l, fmt.Sprintf("0x%x", unknown))
+ }
+ fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-65s → %q\n",
+ time.Now().Format("15:04:05.000000000"), strings.Join(l, " | "), filepath.ToSlash(name))
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go
new file mode 100644
index 0000000000..5ac8b50797
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go
@@ -0,0 +1,31 @@
+//go:build freebsd
+
+package internal
+
+import (
+ "syscall"
+
+ "golang.org/x/sys/unix"
+)
+
+var (
+ ErrSyscallEACCES = syscall.EACCES
+ ErrUnixEACCES = unix.EACCES
+)
+
+var maxfiles uint64
+
+func SetRlimit() {
+ // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/
+ var l syscall.Rlimit
+ err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l)
+ if err == nil && l.Cur != l.Max {
+ l.Cur = l.Max
+ syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l)
+ }
+ maxfiles = uint64(l.Cur)
+}
+
+func Maxfiles() uint64 { return maxfiles }
+func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) }
+func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, uint64(dev)) }
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/internal.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/internal.go
new file mode 100644
index 0000000000..7daa45e19e
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/internal.go
@@ -0,0 +1,2 @@
+// Package internal contains some helpers.
+package internal
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/unix.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/unix.go
new file mode 100644
index 0000000000..b251fb8038
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/unix.go
@@ -0,0 +1,31 @@
+//go:build !windows && !darwin && !freebsd && !plan9
+
+package internal
+
+import (
+ "syscall"
+
+ "golang.org/x/sys/unix"
+)
+
+var (
+ ErrSyscallEACCES = syscall.EACCES
+ ErrUnixEACCES = unix.EACCES
+)
+
+var maxfiles uint64
+
+func SetRlimit() {
+ // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/
+ var l syscall.Rlimit
+ err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l)
+ if err == nil && l.Cur != l.Max {
+ l.Cur = l.Max
+ syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l)
+ }
+ maxfiles = uint64(l.Cur)
+}
+
+func Maxfiles() uint64 { return maxfiles }
+func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) }
+func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) }
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/unix2.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/unix2.go
new file mode 100644
index 0000000000..37dfeddc28
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/unix2.go
@@ -0,0 +1,7 @@
+//go:build !windows
+
+package internal
+
+func HasPrivilegesForSymlink() bool {
+ return true
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/internal/windows.go b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/windows.go
new file mode 100644
index 0000000000..896bc2e5a2
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/internal/windows.go
@@ -0,0 +1,41 @@
+//go:build windows
+
+package internal
+
+import (
+ "errors"
+
+ "golang.org/x/sys/windows"
+)
+
+// Just a dummy.
+var (
+ ErrSyscallEACCES = errors.New("dummy")
+ ErrUnixEACCES = errors.New("dummy")
+)
+
+func SetRlimit() {}
+func Maxfiles() uint64 { return 1<<64 - 1 }
+func Mkfifo(path string, mode uint32) error { return errors.New("no FIFOs on Windows") }
+func Mknod(path string, mode uint32, dev int) error { return errors.New("no device nodes on Windows") }
+
+func HasPrivilegesForSymlink() bool {
+ var sid *windows.SID
+ err := windows.AllocateAndInitializeSid(
+ &windows.SECURITY_NT_AUTHORITY,
+ 2,
+ windows.SECURITY_BUILTIN_DOMAIN_RID,
+ windows.DOMAIN_ALIAS_RID_ADMINS,
+ 0, 0, 0, 0, 0, 0,
+ &sid)
+ if err != nil {
+ return false
+ }
+ defer windows.FreeSid(sid)
+ token := windows.Token(0)
+ member, err := token.IsMember(sid)
+ if err != nil {
+ return false
+ }
+ return member || token.IsElevated()
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/mkdoc.zsh b/test/tools/vendor/github.com/fsnotify/fsnotify/mkdoc.zsh
deleted file mode 100644
index 99012ae653..0000000000
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/mkdoc.zsh
+++ /dev/null
@@ -1,259 +0,0 @@
-#!/usr/bin/env zsh
-[ "${ZSH_VERSION:-}" = "" ] && echo >&2 "Only works with zsh" && exit 1
-setopt err_exit no_unset pipefail extended_glob
-
-# Simple script to update the godoc comments on all watchers so you don't need
-# to update the same comment 5 times.
-
-watcher=$(</tmp/x
- print -r -- $cmt >>/tmp/x
- tail -n+$(( end + 1 )) $file >>/tmp/x
- mv /tmp/x $file
- done
-}
-
-set-cmt '^type Watcher struct ' $watcher
-set-cmt '^func NewWatcher(' $new
-set-cmt '^func NewBufferedWatcher(' $newbuffered
-set-cmt '^func (w \*Watcher) Add(' $add
-set-cmt '^func (w \*Watcher) AddWith(' $addwith
-set-cmt '^func (w \*Watcher) Remove(' $remove
-set-cmt '^func (w \*Watcher) Close(' $close
-set-cmt '^func (w \*Watcher) WatchList(' $watchlist
-set-cmt '^[[:space:]]*Events *chan Event$' $events
-set-cmt '^[[:space:]]*Errors *chan error$' $errors
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/shared.go b/test/tools/vendor/github.com/fsnotify/fsnotify/shared.go
new file mode 100644
index 0000000000..3ee9b58f1d
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/shared.go
@@ -0,0 +1,64 @@
+package fsnotify
+
+import "sync"
+
+type shared struct {
+ Events chan Event
+ Errors chan error
+ done chan struct{}
+ mu sync.Mutex
+}
+
+func newShared(ev chan Event, errs chan error) *shared {
+ return &shared{
+ Events: ev,
+ Errors: errs,
+ done: make(chan struct{}),
+ }
+}
+
+// Returns true if the event was sent, or false if watcher is closed.
+func (w *shared) sendEvent(e Event) bool {
+ if e.Op == 0 {
+ return true
+ }
+ select {
+ case <-w.done:
+ return false
+ case w.Events <- e:
+ return true
+ }
+}
+
+// Returns true if the error was sent, or false if watcher is closed.
+func (w *shared) sendError(err error) bool {
+ if err == nil {
+ return true
+ }
+ select {
+ case <-w.done:
+ return false
+ case w.Errors <- err:
+ return true
+ }
+}
+
+func (w *shared) isClosed() bool {
+ select {
+ case <-w.done:
+ return true
+ default:
+ return false
+ }
+}
+
+// Mark as closed; returns true if it was already closed.
+func (w *shared) close() bool {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.isClosed() {
+ return true
+ }
+ close(w.done)
+ return false
+}
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/staticcheck.conf b/test/tools/vendor/github.com/fsnotify/fsnotify/staticcheck.conf
new file mode 100644
index 0000000000..8fa7351f0c
--- /dev/null
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/staticcheck.conf
@@ -0,0 +1,3 @@
+checks = ['all',
+ '-U1000', # Don't complain about unused functions.
+]
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/system_bsd.go b/test/tools/vendor/github.com/fsnotify/fsnotify/system_bsd.go
index 4322b0b885..f65e8fe3ed 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/system_bsd.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/system_bsd.go
@@ -1,5 +1,4 @@
//go:build freebsd || openbsd || netbsd || dragonfly
-// +build freebsd openbsd netbsd dragonfly
package fsnotify
diff --git a/test/tools/vendor/github.com/fsnotify/fsnotify/system_darwin.go b/test/tools/vendor/github.com/fsnotify/fsnotify/system_darwin.go
index 5da5ffa78f..a29fc7aab6 100644
--- a/test/tools/vendor/github.com/fsnotify/fsnotify/system_darwin.go
+++ b/test/tools/vendor/github.com/fsnotify/fsnotify/system_darwin.go
@@ -1,5 +1,4 @@
//go:build darwin
-// +build darwin
package fsnotify
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/.editorconfig b/test/tools/vendor/github.com/go-openapi/analysis/.editorconfig
new file mode 100644
index 0000000000..3152da69a5
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/analysis/.gitignore b/test/tools/vendor/github.com/go-openapi/analysis/.gitignore
index 87c3bd3e66..885dc27ab0 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/.gitignore
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/analysis/.golangci.yml b/test/tools/vendor/github.com/go-openapi/analysis/.golangci.yml
index 22f8d21cca..02edc1b9fa 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/analysis/.golangci.yml
@@ -1,61 +1,70 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
+ - depguard
- funlen
- godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
+ - gomoddirectives
- exhaustruct
- - varnamelen
- - gci
- - depguard
- - errchkjson
- - inamedparam
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 25
+ gocyclo:
+ min-complexity: 25
+ gocognit:
+ min-complexity: 35
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/analysis/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/analysis/CONTRIBUTORS.md
new file mode 100644
index 0000000000..cf8fcaa7dc
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/analysis/README.md b/test/tools/vendor/github.com/go-openapi/analysis/README.md
index e005d4b37b..96821d3e43 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/README.md
+++ b/test/tools/vendor/github.com/go-openapi/analysis/README.md
@@ -1,22 +1,46 @@
-# OpenAPI analysis [](https://github.com/go-openapi/analysis/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/analysis)
+# analysis
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/analysis/master/LICENSE)
-[](https://pkg.go.dev/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/test/tools/vendor/github.com/go-openapi/analysis/SECURITY.md b/test/tools/vendor/github.com/go-openapi/analysis/SECURITY.md
new file mode 100644
index 0000000000..6ceb159ca2
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/analysis/analyzer.go b/test/tools/vendor/github.com/go-openapi/analysis/analyzer.go
index c17aee1b61..1c91b8c550 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/analyzer.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/analyzer.go
@@ -1,28 +1,24 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package analysis
import (
"fmt"
+ "maps"
slashpath "path"
"strconv"
"strings"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/spec"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/mangling"
+)
+
+const (
+ allocLargeMap = 150
+ allocMediumMap = 64
+ allocSmallMap = 10
)
type referenceAnalysis struct {
@@ -105,37 +101,52 @@ func (p *patternAnalysis) addSchemaPattern(key, pattern string) {
}
type enumAnalysis struct {
- parameters map[string][]interface{}
- headers map[string][]interface{}
- items map[string][]interface{}
- schemas map[string][]interface{}
- allEnums map[string][]interface{}
+ parameters map[string][]any
+ headers map[string][]any
+ items map[string][]any
+ schemas map[string][]any
+ allEnums map[string][]any
}
-func (p *enumAnalysis) addEnum(key string, enum []interface{}) {
+func (p *enumAnalysis) addEnum(key string, enum []any) {
p.allEnums["#"+key] = enum
}
-func (p *enumAnalysis) addParameterEnum(key string, enum []interface{}) {
+func (p *enumAnalysis) addParameterEnum(key string, enum []any) {
p.parameters["#"+key] = enum
p.addEnum(key, enum)
}
-func (p *enumAnalysis) addHeaderEnum(key string, enum []interface{}) {
+func (p *enumAnalysis) addHeaderEnum(key string, enum []any) {
p.headers["#"+key] = enum
p.addEnum(key, enum)
}
-func (p *enumAnalysis) addItemsEnum(key string, enum []interface{}) {
+func (p *enumAnalysis) addItemsEnum(key string, enum []any) {
p.items["#"+key] = enum
p.addEnum(key, enum)
}
-func (p *enumAnalysis) addSchemaEnum(key string, enum []interface{}) {
+func (p *enumAnalysis) addSchemaEnum(key string, enum []any) {
p.schemas["#"+key] = enum
p.addEnum(key, enum)
}
+// Spec is an analyzed specification object. It takes a swagger spec object and turns it into a registry
+// with a bunch of utility methods to act on the information in the spec.
+type Spec struct {
+ spec *spec.Swagger
+ consumes map[string]struct{}
+ produces map[string]struct{}
+ authSchemes map[string]struct{}
+ operations map[string]map[string]*spec.Operation
+ references referenceAnalysis
+ patterns patternAnalysis
+ enums enumAnalysis
+ allSchemas map[string]SchemaRef
+ allOfs map[string]SchemaRef
+}
+
// New takes a swagger spec object and returns an analyzed spec document.
// The analyzed document contains a number of indices that make it easier to
// reason about semantics of a swagger specification for use in code generation
@@ -153,46 +164,570 @@ func New(doc *spec.Swagger) *Spec {
return a
}
-// Spec is an analyzed specification object. It takes a swagger spec object and turns it into a registry
-// with a bunch of utility methods to act on the information in the spec.
-type Spec struct {
- spec *spec.Swagger
- consumes map[string]struct{}
- produces map[string]struct{}
- authSchemes map[string]struct{}
- operations map[string]map[string]*spec.Operation
- references referenceAnalysis
- patterns patternAnalysis
- enums enumAnalysis
- allSchemas map[string]SchemaRef
- allOfs map[string]SchemaRef
+// 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.
+func (s *Spec) SecurityRequirementsFor(operation *spec.Operation) [][]SecurityRequirement {
+ if s.spec.Security == nil && operation.Security == nil {
+ return nil
+ }
+
+ schemes := s.spec.Security
+ if operation.Security != nil {
+ schemes = operation.Security
+ }
+
+ result := [][]SecurityRequirement{}
+ for _, scheme := range schemes {
+ if len(scheme) == 0 {
+ // append a zero object for anonymous
+ result = append(result, []SecurityRequirement{{}})
+
+ continue
+ }
+
+ var reqs []SecurityRequirement
+ for k, v := range scheme {
+ if v == nil {
+ v = []string{}
+ }
+ reqs = append(reqs, SecurityRequirement{Name: k, Scopes: v})
+ }
+
+ result = append(result, reqs)
+ }
+
+ return result
+}
+
+// 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)
+
+ for _, v := range requirements {
+ if definition, ok := s.spec.SecurityDefinitions[v.Name]; ok {
+ if definition != nil {
+ result[v.Name] = *definition
+ }
+ }
+ }
+
+ return result
+}
+
+// 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 {
+ return nil
+ }
+
+ result := make(map[string]spec.SecurityScheme)
+ for _, reqs := range requirements {
+ for _, v := range reqs {
+ if v.Name == "" {
+ // optional requirement
+ continue
+ }
+
+ if _, ok := result[v.Name]; ok {
+ // duplicate requirement
+ continue
+ }
+
+ if definition, ok := s.spec.SecurityDefinitions[v.Name]; ok {
+ if definition != nil {
+ result[v.Name] = *definition
+ }
+ }
+ }
+ }
+
+ return result
+}
+
+// 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))
+ for _, k := range s.spec.Consumes {
+ cons[k] = struct{}{}
+ }
+
+ return s.structMapKeys(cons)
+ }
+
+ cons := make(map[string]struct{}, len(operation.Consumes))
+ for _, c := range operation.Consumes {
+ cons[c] = struct{}{}
+ }
+
+ return s.structMapKeys(cons)
+}
+
+// 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))
+ for _, k := range s.spec.Produces {
+ prod[k] = struct{}{}
+ }
+
+ return s.structMapKeys(prod)
+ }
+
+ prod := make(map[string]struct{}, len(operation.Produces))
+ for _, c := range operation.Produces {
+ prod[c] = struct{}{}
+ }
+
+ return s.structMapKeys(prod)
+}
+
+func mapKeyFromParam(param *spec.Parameter) string {
+ return fmt.Sprintf("%s#%s", param.In, fieldNameFromParam(param))
+}
+
+func fieldNameFromParam(param *spec.Parameter) string {
+ // TODO: this should be x-go-name
+ if nm, ok := param.Extensions.GetString("go-name"); ok {
+ return nm
+ }
+ mangler := mangling.NewNameMangler()
+
+ return mangler.ToGoName(param.Name)
+}
+
+// ErrorOnParamFunc is a callback function to be invoked
+// whenever an error is encountered while resolving references
+// on parameters.
+//
+// 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.
+//
+// If it returns true, the calling function should continue evaluating parameters.
+// A nil ErrorOnParamFunc must be evaluated as equivalent to panic().
+type ErrorOnParamFunc func(spec.Parameter, error) bool
+
+// ParametersFor the specified operation id.
+//
+// Assumes parameters properly resolve references if any and that
+// such references actually resolve to a parameter object.
+// Otherwise, panics.
+func (s *Spec) ParametersFor(operationID string) []spec.Parameter {
+ return s.SafeParametersFor(operationID, nil)
+}
+
+// SafeParametersFor the specified operation id.
+//
+// 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
+// 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 {
+ bag := make(map[string]spec.Parameter)
+ s.paramsAsMap(pi.Parameters, bag, callmeOnError)
+ s.paramsAsMap(op.Parameters, bag, callmeOnError)
+
+ res := make([]spec.Parameter, 0, len(bag))
+ for _, v := range bag {
+ res = append(res, v)
+ }
+
+ return res
+ }
+
+ for _, pi := range s.spec.Paths.Paths {
+ if pi.Get != nil && pi.Get.ID == operationID {
+ return gatherParams(&pi, pi.Get) //#nosec
+ }
+ if pi.Head != nil && pi.Head.ID == operationID {
+ return gatherParams(&pi, pi.Head) //#nosec
+ }
+ if pi.Options != nil && pi.Options.ID == operationID {
+ return gatherParams(&pi, pi.Options) //#nosec
+ }
+ if pi.Post != nil && pi.Post.ID == operationID {
+ return gatherParams(&pi, pi.Post) //#nosec
+ }
+ if pi.Patch != nil && pi.Patch.ID == operationID {
+ return gatherParams(&pi, pi.Patch) //#nosec
+ }
+ if pi.Put != nil && pi.Put.ID == operationID {
+ return gatherParams(&pi, pi.Put) //#nosec
+ }
+ if pi.Delete != nil && pi.Delete.ID == operationID {
+ return gatherParams(&pi, pi.Delete) //#nosec
+ }
+ }
+
+ return nil
+}
+
+// ParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that
+// apply for the method and path.
+//
+// Assumes parameters properly resolve references if any and that
+// such references actually resolve to a parameter object.
+// Otherwise, panics.
+func (s *Spec) ParamsFor(method, path string) map[string]spec.Parameter {
+ return s.SafeParamsFor(method, path, nil)
+}
+
+// SafeParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that
+// apply for the method and path.
+//
+// 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
+// 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)
+ if pi, ok := s.spec.Paths.Paths[path]; ok {
+ s.paramsAsMap(pi.Parameters, res, callmeOnError)
+ s.paramsAsMap(s.operations[strings.ToUpper(method)][path].Parameters, res, callmeOnError)
+ }
+
+ return res
+}
+
+// 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 {
+ if operationID == op.ID {
+ return method, path, op, true
+ }
+ }
+ }
+
+ return "", "", nil, false
+}
+
+// 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]
+
+ return op, fn
+ }
+
+ return nil, false
+}
+
+// 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.
+func (s *Spec) AllPaths() map[string]spec.PathItem {
+ if s.spec == nil || s.spec.Paths == nil {
+ return nil
+ }
+
+ return s.spec.Paths.Paths
+}
+
+// OperationIDs gets all the operation ids based on method an dpath.
+func (s *Spec) OperationIDs() []string {
+ if len(s.operations) == 0 {
+ return nil
+ }
+
+ result := make([]string, 0, len(s.operations))
+ for method, v := range s.operations {
+ for p, o := range v {
+ if o.ID != "" {
+ result = append(result, o.ID)
+ } else {
+ result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p))
+ }
+ }
+ }
+
+ return result
+}
+
+// OperationMethodPaths gets all the operation ids based on method an dpath.
+func (s *Spec) OperationMethodPaths() []string {
+ if len(s.operations) == 0 {
+ return nil
+ }
+
+ result := make([]string, 0, len(s.operations))
+ for method, v := range s.operations {
+ for p := range v {
+ result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p))
+ }
+ }
+
+ return result
+}
+
+// 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.
+func (s *Spec) RequiredProduces() []string {
+ return s.structMapKeys(s.produces)
+}
+
+// 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.
+type SchemaRef struct {
+ Name string
+ Ref spec.Ref
+ Schema *spec.Schema
+ TopLevel bool
+}
+
+// SchemasWithAllOf returns schema references to all schemas that are defined
+// with an allOf key.
+func (s *Spec) SchemasWithAllOf() (result []SchemaRef) {
+ for _, v := range s.allOfs {
+ result = append(result, v)
+ }
+
+ return
+}
+
+// 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)
+ }
+
+ return
+}
+
+// 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())
+ }
+
+ return
+}
+
+// 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())
+ }
+
+ return
+}
+
+// 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())
+ }
+
+ return
+}
+
+// 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())
+ }
+
+ return
+}
+
+// AllItemsReferences returns the references for all the items in simple schemas (parameters or headers).
+//
+// NOTE: since Swagger 2.0 forbids $ref in simple params, this should always yield an empty slice for a valid
+// Swagger 2.0 spec.
+func (s *Spec) AllItemsReferences() (result []string) {
+ for _, v := range s.references.items {
+ result = append(result, v.String())
+ }
+
+ return
+}
+
+// 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())
+ }
+
+ return
+}
+
+// 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 {
+ a := v.String()
+ if a == "" {
+ continue
+ }
+
+ if _, ok := set[a]; !ok {
+ set[a] = struct{}{}
+ result = append(result, v)
+ }
+ }
+
+ return
+}
+
+// ParameterPatterns returns all the patterns found in parameters
+// 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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+func (s *Spec) AllEnums() map[string][]any {
+ return cloneEnumMap(s.enums.allEnums)
+}
+
+func (s *Spec) structMapKeys(mp map[string]struct{}) []string {
+ if len(mp) == 0 {
+ return nil
+ }
+
+ result := make([]string, 0, len(mp))
+ for k := range mp {
+ result = append(result, k)
+ }
+
+ return result
+}
+
+func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) {
+ for _, param := range parameters {
+ pr := param
+ if pr.Ref.String() == "" {
+ res[mapKeyFromParam(&pr)] = pr
+
+ continue
+ }
+
+ // resolve $ref
+ if callmeOnError == nil {
+ callmeOnError = func(_ spec.Parameter, err error) bool {
+ panic(err)
+ }
+ }
+
+ obj, _, err := pr.Ref.GetPointer().Get(s.spec)
+ if err != nil {
+ if callmeOnError(param, ErrInvalidRef(pr.Ref.String())) {
+ continue
+ }
+
+ break
+ }
+
+ objAsParam, ok := obj.(spec.Parameter)
+ if !ok {
+ if callmeOnError(param, ErrInvalidParameterRef(pr.Ref.String())) {
+ continue
+ }
+
+ break
+ }
+
+ pr = objAsParam
+ res[mapKeyFromParam(&pr)] = pr
+ }
}
func (s *Spec) reset() {
- s.consumes = make(map[string]struct{}, 150)
- s.produces = make(map[string]struct{}, 150)
- s.authSchemes = make(map[string]struct{}, 150)
- s.operations = make(map[string]map[string]*spec.Operation, 150)
- s.allSchemas = make(map[string]SchemaRef, 150)
- s.allOfs = make(map[string]SchemaRef, 150)
- s.references.schemas = make(map[string]spec.Ref, 150)
- s.references.pathItems = make(map[string]spec.Ref, 150)
- s.references.responses = make(map[string]spec.Ref, 150)
- s.references.parameters = make(map[string]spec.Ref, 150)
- s.references.items = make(map[string]spec.Ref, 150)
- s.references.headerItems = make(map[string]spec.Ref, 150)
- s.references.parameterItems = make(map[string]spec.Ref, 150)
- s.references.allRefs = make(map[string]spec.Ref, 150)
- s.patterns.parameters = make(map[string]string, 150)
- s.patterns.headers = make(map[string]string, 150)
- s.patterns.items = make(map[string]string, 150)
- s.patterns.schemas = make(map[string]string, 150)
- s.patterns.allPatterns = make(map[string]string, 150)
- s.enums.parameters = make(map[string][]interface{}, 150)
- s.enums.headers = make(map[string][]interface{}, 150)
- s.enums.items = make(map[string][]interface{}, 150)
- s.enums.schemas = make(map[string][]interface{}, 150)
- s.enums.allEnums = make(map[string][]interface{}, 150)
+ s.consumes = make(map[string]struct{}, allocLargeMap)
+ s.produces = make(map[string]struct{}, allocLargeMap)
+ s.authSchemes = make(map[string]struct{}, allocLargeMap)
+ s.operations = make(map[string]map[string]*spec.Operation, allocLargeMap)
+ s.allSchemas = make(map[string]SchemaRef, allocLargeMap)
+ s.allOfs = make(map[string]SchemaRef, allocLargeMap)
+ s.references.schemas = make(map[string]spec.Ref, allocLargeMap)
+ s.references.pathItems = make(map[string]spec.Ref, allocLargeMap)
+ s.references.responses = make(map[string]spec.Ref, allocLargeMap)
+ s.references.parameters = make(map[string]spec.Ref, allocLargeMap)
+ s.references.items = make(map[string]spec.Ref, allocLargeMap)
+ s.references.headerItems = make(map[string]spec.Ref, allocLargeMap)
+ s.references.parameterItems = make(map[string]spec.Ref, allocLargeMap)
+ s.references.allRefs = make(map[string]spec.Ref, allocLargeMap)
+ s.patterns.parameters = make(map[string]string, allocLargeMap)
+ s.patterns.headers = make(map[string]string, allocLargeMap)
+ s.patterns.items = make(map[string]string, allocLargeMap)
+ s.patterns.schemas = make(map[string]string, allocLargeMap)
+ s.patterns.allPatterns = make(map[string]string, allocLargeMap)
+ s.enums.parameters = make(map[string][]any, allocLargeMap)
+ s.enums.headers = make(map[string][]any, allocLargeMap)
+ s.enums.items = make(map[string][]any, allocLargeMap)
+ s.enums.schemas = make(map[string][]any, allocLargeMap)
+ s.enums.allEnums = make(map[string][]any, allocLargeMap)
}
func (s *Spec) reload() {
@@ -440,17 +975,14 @@ func (s *Spec) analyzeSchema(name string, schema *spec.Schema, prefix string) {
}
for k, v := range schema.Definitions {
- v := v
s.analyzeSchema(k, &v, slashpath.Join(refURI, "definitions"))
}
for k, v := range schema.Properties {
- v := v
s.analyzeSchema(k, &v, slashpath.Join(refURI, "properties"))
}
for k, v := range schema.PatternProperties {
- v := v
// NOTE: swagger 2.0 does not support PatternProperties.
// However it is possible to analyze this in a schema
s.analyzeSchema(k, &v, slashpath.Join(refURI, "patternProperties"))
@@ -507,558 +1039,16 @@ func (s *Spec) analyzeSchema(name string, schema *spec.Schema, prefix string) {
}
}
-// 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
-func (s *Spec) SecurityRequirementsFor(operation *spec.Operation) [][]SecurityRequirement {
- if s.spec.Security == nil && operation.Security == nil {
- return nil
- }
-
- schemes := s.spec.Security
- if operation.Security != nil {
- schemes = operation.Security
- }
-
- result := [][]SecurityRequirement{}
- for _, scheme := range schemes {
- if len(scheme) == 0 {
- // append a zero object for anonymous
- result = append(result, []SecurityRequirement{{}})
-
- continue
- }
-
- var reqs []SecurityRequirement
- for k, v := range scheme {
- if v == nil {
- v = []string{}
- }
- reqs = append(reqs, SecurityRequirement{Name: k, Scopes: v})
- }
-
- result = append(result, reqs)
- }
-
- return result
-}
-
-// 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)
-
- for _, v := range requirements {
- if definition, ok := s.spec.SecurityDefinitions[v.Name]; ok {
- if definition != nil {
- result[v.Name] = *definition
- }
- }
- }
-
- return result
-}
-
-// 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 {
- return nil
- }
-
- result := make(map[string]spec.SecurityScheme)
- for _, reqs := range requirements {
- for _, v := range reqs {
- if v.Name == "" {
- // optional requirement
- continue
- }
-
- if _, ok := result[v.Name]; ok {
- // duplicate requirement
- continue
- }
-
- if definition, ok := s.spec.SecurityDefinitions[v.Name]; ok {
- if definition != nil {
- result[v.Name] = *definition
- }
- }
- }
- }
-
- return result
-}
-
-// 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))
- for _, k := range s.spec.Consumes {
- cons[k] = struct{}{}
- }
-
- return s.structMapKeys(cons)
- }
-
- cons := make(map[string]struct{}, len(operation.Consumes))
- for _, c := range operation.Consumes {
- cons[c] = struct{}{}
- }
-
- return s.structMapKeys(cons)
-}
-
-// 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))
- for _, k := range s.spec.Produces {
- prod[k] = struct{}{}
- }
-
- return s.structMapKeys(prod)
- }
-
- prod := make(map[string]struct{}, len(operation.Produces))
- for _, c := range operation.Produces {
- prod[c] = struct{}{}
- }
-
- return s.structMapKeys(prod)
-}
-
-func mapKeyFromParam(param *spec.Parameter) string {
- return fmt.Sprintf("%s#%s", param.In, fieldNameFromParam(param))
-}
-
-func fieldNameFromParam(param *spec.Parameter) string {
- // TODO: this should be x-go-name
- if nm, ok := param.Extensions.GetString("go-name"); ok {
- return nm
- }
-
- return swag.ToGoName(param.Name)
-}
-
-// ErrorOnParamFunc is a callback function to be invoked
-// whenever an error is encountered while resolving references
-// on parameters.
-//
-// 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.
-//
-// If it returns true, the calling function should continue evaluating parameters.
-// A nil ErrorOnParamFunc must be evaluated as equivalent to panic().
-type ErrorOnParamFunc func(spec.Parameter, error) bool
-
-func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) {
- for _, param := range parameters {
- pr := param
- if pr.Ref.String() == "" {
- res[mapKeyFromParam(&pr)] = pr
-
- continue
- }
-
- // resolve $ref
- if callmeOnError == nil {
- callmeOnError = func(_ spec.Parameter, err error) bool {
- panic(err)
- }
- }
-
- obj, _, err := pr.Ref.GetPointer().Get(s.spec)
- if err != nil {
- if callmeOnError(param, fmt.Errorf("invalid reference: %q", pr.Ref.String())) {
- continue
- }
-
- break
- }
-
- objAsParam, ok := obj.(spec.Parameter)
- if !ok {
- if callmeOnError(param, fmt.Errorf("resolved reference is not a parameter: %q", pr.Ref.String())) {
- continue
- }
-
- break
- }
-
- pr = objAsParam
- res[mapKeyFromParam(&pr)] = pr
- }
-}
-
-// ParametersFor the specified operation id.
-//
-// Assumes parameters properly resolve references if any and that
-// such references actually resolve to a parameter object.
-// Otherwise, panics.
-func (s *Spec) ParametersFor(operationID string) []spec.Parameter {
- return s.SafeParametersFor(operationID, nil)
-}
-
-// SafeParametersFor the specified operation id.
-//
-// 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
-// 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 {
- bag := make(map[string]spec.Parameter)
- s.paramsAsMap(pi.Parameters, bag, callmeOnError)
- s.paramsAsMap(op.Parameters, bag, callmeOnError)
-
- var res []spec.Parameter
- for _, v := range bag {
- res = append(res, v)
- }
-
- return res
- }
-
- for _, pi := range s.spec.Paths.Paths {
- if pi.Get != nil && pi.Get.ID == operationID {
- return gatherParams(&pi, pi.Get) //#nosec
- }
- if pi.Head != nil && pi.Head.ID == operationID {
- return gatherParams(&pi, pi.Head) //#nosec
- }
- if pi.Options != nil && pi.Options.ID == operationID {
- return gatherParams(&pi, pi.Options) //#nosec
- }
- if pi.Post != nil && pi.Post.ID == operationID {
- return gatherParams(&pi, pi.Post) //#nosec
- }
- if pi.Patch != nil && pi.Patch.ID == operationID {
- return gatherParams(&pi, pi.Patch) //#nosec
- }
- if pi.Put != nil && pi.Put.ID == operationID {
- return gatherParams(&pi, pi.Put) //#nosec
- }
- if pi.Delete != nil && pi.Delete.ID == operationID {
- return gatherParams(&pi, pi.Delete) //#nosec
- }
- }
-
- return nil
-}
-
-// ParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that
-// apply for the method and path.
-//
-// Assumes parameters properly resolve references if any and that
-// such references actually resolve to a parameter object.
-// Otherwise, panics.
-func (s *Spec) ParamsFor(method, path string) map[string]spec.Parameter {
- return s.SafeParamsFor(method, path, nil)
-}
-
-// SafeParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that
-// apply for the method and path.
-//
-// 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
-// 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)
- if pi, ok := s.spec.Paths.Paths[path]; ok {
- s.paramsAsMap(pi.Parameters, res, callmeOnError)
- s.paramsAsMap(s.operations[strings.ToUpper(method)][path].Parameters, res, callmeOnError)
- }
-
- return res
-}
-
-// 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 {
- if operationID == op.ID {
- return method, path, op, true
- }
- }
- }
-
- return "", "", nil, false
-}
-
-// 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]
-
- return op, fn
- }
-
- return nil, false
-}
-
-// Operations gathers all the operations specified in the spec document
-func (s *Spec) Operations() map[string]map[string]*spec.Operation {
- return s.operations
-}
-
-func (s *Spec) structMapKeys(mp map[string]struct{}) []string {
- if len(mp) == 0 {
- return nil
- }
-
- result := make([]string, 0, len(mp))
- for k := range mp {
- result = append(result, k)
- }
-
- return result
-}
-
-// 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
- }
-
- return s.spec.Paths.Paths
-}
-
-// OperationIDs gets all the operation ids based on method an dpath
-func (s *Spec) OperationIDs() []string {
- if len(s.operations) == 0 {
- return nil
- }
-
- result := make([]string, 0, len(s.operations))
- for method, v := range s.operations {
- for p, o := range v {
- if o.ID != "" {
- result = append(result, o.ID)
- } else {
- result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p))
- }
- }
- }
-
- return result
-}
-
-// OperationMethodPaths gets all the operation ids based on method an dpath
-func (s *Spec) OperationMethodPaths() []string {
- if len(s.operations) == 0 {
- return nil
- }
-
- result := make([]string, 0, len(s.operations))
- for method, v := range s.operations {
- for p := range v {
- result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p))
- }
- }
-
- return result
-}
-
-// 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
-func (s *Spec) RequiredProduces() []string {
- return s.structMapKeys(s.produces)
-}
-
-// 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
-type SchemaRef struct {
- Name string
- Ref spec.Ref
- Schema *spec.Schema
- TopLevel bool
-}
-
-// SchemasWithAllOf returns schema references to all schemas that are defined
-// with an allOf key
-func (s *Spec) SchemasWithAllOf() (result []SchemaRef) {
- for _, v := range s.allOfs {
- result = append(result, v)
- }
-
- return
-}
-
-// 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)
- }
-
- return
-}
-
-// AllDefinitionReferences returns json refs for all the discovered schemas
-func (s *Spec) AllDefinitionReferences() (result []string) {
- for _, v := range s.references.schemas {
- result = append(result, v.String())
- }
-
- return
-}
-
-// AllParameterReferences returns json refs for all the discovered parameters
-func (s *Spec) AllParameterReferences() (result []string) {
- for _, v := range s.references.parameters {
- result = append(result, v.String())
- }
-
- return
-}
-
-// AllResponseReferences returns json refs for all the discovered responses
-func (s *Spec) AllResponseReferences() (result []string) {
- for _, v := range s.references.responses {
- result = append(result, v.String())
- }
-
- return
-}
-
-// 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())
- }
-
- return
-}
-
-// AllItemsReferences returns the references for all the items in simple schemas (parameters or headers).
-//
-// NOTE: since Swagger 2.0 forbids $ref in simple params, this should always yield an empty slice for a valid
-// Swagger 2.0 spec.
-func (s *Spec) AllItemsReferences() (result []string) {
- for _, v := range s.references.items {
- result = append(result, v.String())
- }
-
- return
-}
-
-// 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())
- }
-
- return
-}
-
-// 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 {
- a := v.String()
- if a == "" {
- continue
- }
-
- if _, ok := set[a]; !ok {
- set[a] = struct{}{}
- result = append(result, v)
- }
- }
-
- return
-}
-
func cloneStringMap(source map[string]string) map[string]string {
res := make(map[string]string, len(source))
- for k, v := range source {
- res[k] = v
- }
+ maps.Copy(res, source)
return res
}
-func cloneEnumMap(source map[string][]interface{}) map[string][]interface{} {
- res := make(map[string][]interface{}, len(source))
- for k, v := range source {
- res[k] = v
- }
+func cloneEnumMap(source map[string][]any) map[string][]any {
+ res := make(map[string][]any, len(source))
+ maps.Copy(res, source)
return res
}
-
-// ParameterPatterns returns all the patterns found in parameters
-// 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
-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
-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
-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
-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
-func (s *Spec) ParameterEnums() map[string][]interface{} {
- return cloneEnumMap(s.enums.parameters)
-}
-
-// HeaderEnums returns all the enums found in response headers
-// the map is cloned to avoid accidental changes
-func (s *Spec) HeaderEnums() map[string][]interface{} {
- return cloneEnumMap(s.enums.headers)
-}
-
-// ItemsEnums returns all the enums found in simple array items
-// the map is cloned to avoid accidental changes
-func (s *Spec) ItemsEnums() map[string][]interface{} {
- return cloneEnumMap(s.enums.items)
-}
-
-// SchemaEnums returns all the enums found in schemas
-// the map is cloned to avoid accidental changes
-func (s *Spec) SchemaEnums() map[string][]interface{} {
- return cloneEnumMap(s.enums.schemas)
-}
-
-// AllEnums returns all the enums found in the spec
-// the map is cloned to avoid accidental changes
-func (s *Spec) AllEnums() map[string][]interface{} {
- return cloneEnumMap(s.enums.allEnums)
-}
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/debug.go b/test/tools/vendor/github.com/go-openapi/analysis/debug.go
index 33c15704ec..8e777c432a 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/debug.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/debug.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package analysis
@@ -20,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/test/tools/vendor/github.com/go-openapi/analysis/doc.go b/test/tools/vendor/github.com/go-openapi/analysis/doc.go
index e8d9f9b131..9c4b165c6f 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/doc.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/doc.go
@@ -1,43 +1,31 @@
-// Copyright 2015 go-swagger maintainers
+// 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.
//
-// 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
+// # Analyzing a specification
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// An analysed specification object (type Spec) provides methods to work with swagger definition.
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-/*
-Package 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.
-*/
+// # 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/test/tools/vendor/github.com/go-openapi/analysis/errors.go b/test/tools/vendor/github.com/go-openapi/analysis/errors.go
new file mode 100644
index 0000000000..540e159a23
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/analysis/errors.go
@@ -0,0 +1,56 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
+package analysis
+
+import (
+ "errors"
+ "fmt"
+)
+
+type analysisError string
+
+const (
+ ErrAnalysis analysisError = "analysis error"
+ ErrNoSchema analysisError = "no schema to analyze"
+)
+
+func (e analysisError) Error() string {
+ return string(e)
+}
+
+func ErrAtKey(key string, err error) error {
+ return errors.Join(
+ fmt.Errorf("key %s: %w", key, err),
+ ErrAnalysis,
+ )
+}
+
+func ErrInvalidRef(key string) error {
+ return fmt.Errorf("invalid reference: %q: %w", key, ErrAnalysis)
+}
+
+func ErrInvalidParameterRef(key string) error {
+ return fmt.Errorf("resolved reference is not a parameter: %q: %w", key, ErrAnalysis)
+}
+
+func ErrResolveSchema(err error) error {
+ return errors.Join(
+ fmt.Errorf("could not resolve schema: %w", err),
+ ErrAnalysis,
+ )
+}
+
+func ErrRewriteRef(key string, target any, err error) error {
+ return errors.Join(
+ fmt.Errorf("failed to rewrite ref for key %q at %v: %w", key, target, err),
+ ErrAnalysis,
+ )
+}
+
+func ErrInlineDefinition(key string, err error) error {
+ return errors.Join(
+ fmt.Errorf("error while creating definition %q from inline schema: %w", key, err),
+ ErrAnalysis,
+ )
+}
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/fixer.go b/test/tools/vendor/github.com/go-openapi/analysis/fixer.go
index 7c2ca08416..74becbbe49 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/fixer.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/fixer.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package analysis
@@ -72,7 +61,7 @@ func FixEmptyDescs(rs *spec.Responses) {
// Response object if it doesn't already have one and isn't a
// ref. No-op on nil input.
func FixEmptyDesc(rs *spec.Response) {
- if rs == nil || rs.Description != "" || rs.Ref.Ref.GetURL() != nil {
+ if rs == nil || rs.Description != "" || rs.Ref.GetURL() != nil {
return
}
rs.Description = "(empty)"
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/flatten.go b/test/tools/vendor/github.com/go-openapi/analysis/flatten.go
index ebedcc9df3..d7ee0064b6 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/flatten.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/flatten.go
@@ -1,23 +1,12 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package analysis
import (
- "fmt"
"log"
"path"
+ "slices"
"sort"
"strings"
@@ -32,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
@@ -43,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,9 +41,9 @@ type context struct {
func newContext() *context {
return &context{
- newRefs: make(map[string]*newRef, 150),
+ newRefs: make(map[string]*newRef, allocMediumMap),
warnings: make([]string, 0),
- resolved: make(map[string]string, 50),
+ resolved: make(map[string]string, allocMediumMap),
}
}
@@ -63,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
//
@@ -81,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.
@@ -91,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
@@ -98,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
@@ -180,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")
@@ -251,7 +245,7 @@ func nameInlinedSchemas(opts *FlattenOpts) error {
asch, err := Schema(SchemaOpts{Schema: sch.Schema, Root: opts.Swagger(), BasePath: opts.BasePath})
if err != nil {
- return fmt.Errorf("schema analysis [%s]: %w", key, err)
+ return ErrAtKey(key, err)
}
if asch.isAnalyzedAsComplex() { // move complex schemas to definitions
@@ -320,7 +314,7 @@ func importNewRef(entry sortref.RefRevIdx, refStr string, opts *FlattenOpts) err
sch, err := spec.ResolveRefWithBase(opts.Swagger(), &entry.Ref, opts.ExpandOpts(false))
if err != nil {
- return fmt.Errorf("could not resolve schema: %w", err)
+ return ErrResolveSchema(err)
}
// at this stage only $ref analysis matters
@@ -335,7 +329,7 @@ func importNewRef(entry sortref.RefRevIdx, refStr string, opts *FlattenOpts) err
// now rewrite those refs with rebase
for key, ref := range partialAnalyzer.references.allRefs {
if err := replace.UpdateRef(sch, key, spec.MustCreateRef(normalize.RebaseRef(entry.Ref.String(), ref.String()))); err != nil {
- return fmt.Errorf("failed to rewrite ref for key %q at %s: %w", key, entry.Ref.String(), err)
+ return ErrRewriteRef(key, entry.Ref.String(), err)
}
}
@@ -429,7 +423,7 @@ func importExternalReferences(opts *FlattenOpts) (bool, error) {
ref := spec.MustCreateRef(r.path)
sch, err := spec.ResolveRefWithBase(opts.Swagger(), &ref, opts.ExpandOpts(false))
if err != nil {
- return false, fmt.Errorf("could not resolve schema: %w", err)
+ return false, ErrResolveSchema(err)
}
r.schema = sch
@@ -502,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())
@@ -532,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
@@ -542,14 +547,7 @@ func updateRefParents(allRefs map[string]spec.Ref, r *newRef) {
continue
}
- found := false
- for _, p := range r.parents {
- if p == k {
- found = true
-
- break
- }
- }
+ found := slices.Contains(r.parents, k)
if !found {
r.parents = append(r.parents, k)
}
@@ -598,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
@@ -605,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
}
@@ -643,7 +662,7 @@ func stripOAIGenForRef(opts *FlattenOpts, k string, r *newRef) (bool, error) {
}
debugLog("re-inlined schema: parent: %s, %t", pr[0], asch.isAnalyzedAsComplex())
- replacedWithComplex = replacedWithComplex || !(path.Dir(pr[0]) == definitionsPath) && asch.isAnalyzedAsComplex()
+ replacedWithComplex = replacedWithComplex || path.Dir(pr[0]) != definitionsPath && asch.isAnalyzedAsComplex()
}
return replacedWithComplex, nil
@@ -666,7 +685,7 @@ func namePointers(opts *FlattenOpts) error {
result, err := replace.DeepestRef(opts.Swagger(), opts.ExpandOpts(false), ref)
if err != nil {
- return fmt.Errorf("at %s, %w", k, err)
+ return ErrAtKey(k, err)
}
replacingRef := result.Ref
@@ -697,7 +716,7 @@ func namePointers(opts *FlattenOpts) error {
// update current replacement, which may have been updated by previous changes of deeper elements
result, erd := replace.DeepestRef(opts.Swagger(), opts.ExpandOpts(false), v.Ref)
if erd != nil {
- return fmt.Errorf("at %s, %w", key, erd)
+ return ErrAtKey(key, erd)
}
if opts.flattenContext != nil {
@@ -743,9 +762,9 @@ func flattenAnonPointer(key string, v SchemaRef, refsToReplace map[string]Schema
// qualify the expanded schema
asch, ers := Schema(SchemaOpts{Schema: v.Schema, Root: opts.Swagger(), BasePath: opts.BasePath})
if ers != nil {
- return fmt.Errorf("schema analysis [%s]: %w", key, ers)
+ return ErrAtKey(key, ers)
}
- callers := make([]string, 0, 64)
+ callers := make([]string, 0, allocMediumMap)
debugLog("looking for callers")
@@ -753,7 +772,7 @@ func flattenAnonPointer(key string, v SchemaRef, refsToReplace map[string]Schema
for k, w := range an.references.allRefs {
r, err := replace.DeepestRef(opts.Swagger(), opts.ExpandOpts(false), w)
if err != nil {
- return fmt.Errorf("at %s, %w", key, err)
+ return ErrAtKey(key, err)
}
if opts.flattenContext != nil {
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/flatten_name.go b/test/tools/vendor/github.com/go-openapi/analysis/flatten_name.go
index c7d7938ebe..922cae55c5 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/flatten_name.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/flatten_name.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package analysis
import (
@@ -11,10 +14,10 @@ import (
"github.com/go-openapi/analysis/internal/flatten/schutils"
"github.com/go-openapi/analysis/internal/flatten/sortref"
"github.com/go-openapi/spec"
- "github.com/go-openapi/swag"
+ "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
@@ -22,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)
@@ -43,7 +46,7 @@ func (isn *InlineSchemaNamer) Name(key string, schema *spec.Schema, aschema *Ana
debugLog("rewriting schema to ref: key=%s with new name: %s", key, newName)
if err := replace.RewriteSchemaToRef(isn.Spec, key,
spec.MustCreateRef(path.Join(definitionsPath, newName))); err != nil {
- return fmt.Errorf("error while creating definition %q from inline schema: %w", newName, err)
+ return ErrInlineDefinition(newName, err)
}
// rewrite any dependent $ref pointing to this place,
@@ -54,7 +57,7 @@ func (isn *InlineSchemaNamer) Name(key string, schema *spec.Schema, aschema *Ana
for k, v := range an.references.allRefs {
r, erd := replace.DeepestRef(isn.opts.Swagger(), isn.opts.ExpandOpts(false), v)
if erd != nil {
- return fmt.Errorf("at %s, %w", k, erd)
+ return ErrAtKey(k, erd)
}
if isn.opts.flattenContext != nil {
@@ -105,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 == "" {
@@ -227,19 +230,24 @@ func namesForOperation(parts sortref.SplitKey, operations map[string]operations.
return baseNames, startIndex
}
+const (
+ minStartIndex = 2
+ minSegments = 2
+)
+
func namesForDefinition(parts sortref.SplitKey) ([][]string, int) {
nm := parts.DefinitionName()
if nm != "" {
- return [][]string{{parts.DefinitionName()}}, 2
+ return [][]string{{parts.DefinitionName()}}, minStartIndex
}
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, 2)
+ segments := make([]string, 0, minSegments)
if part == "items" || part == "additionalItems" {
if aschema.IsTuple || aschema.IsTupleWithExtra {
@@ -265,8 +273,9 @@ func mangler(o *FlattenOpts) func(string) string {
if o.KeepNames {
return func(in string) string { return in }
}
+ mangler := mangling.NewNameMangler()
- return swag.ToJSONName
+ return mangler.ToJSONName
}
func nameFromRef(ref spec.Ref, o *FlattenOpts) string {
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/flatten_options.go b/test/tools/vendor/github.com/go-openapi/analysis/flatten_options.go
index c943fe1e84..23a57ea1ac 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/flatten_options.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/flatten_options.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package analysis
import (
@@ -32,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,
@@ -41,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/test/tools/vendor/github.com/go-openapi/analysis/go.work b/test/tools/vendor/github.com/go-openapi/analysis/go.work
new file mode 100644
index 0000000000..1794cfc979
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/analysis/go.work
@@ -0,0 +1,6 @@
+go 1.24.0
+
+use (
+ .
+ ./internal/testintegration
+)
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/go.work.sum b/test/tools/vendor/github.com/go-openapi/analysis/go.work.sum
new file mode 100644
index 0000000000..b767fb6171
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/analysis/internal/debug/debug.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/debug/debug.go
index 39f55a97bf..d3fa08d3ba 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/internal/debug/debug.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/debug/debug.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package debug
@@ -22,20 +11,18 @@ 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
-func GetLogger(prefix string, debug bool) func(string, ...interface{}) {
+// GetLogger provides a prefix debug logger.
+func GetLogger(prefix string, debug bool) func(string, ...any) {
if debug {
logger := log.New(output, prefix+":", log.LstdFlags)
- return func(msg string, args ...interface{}) {
+ return func(msg string, args ...any) {
_, file1, pos1, _ := runtime.Caller(1)
logger.Printf("%s:%d: %s", filepath.Base(file1), pos1, fmt.Sprintf(msg, args...))
}
}
- return func(_ string, _ ...interface{}) {}
+ return func(_ string, _ ...any) {}
}
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go
index 8c9df0580d..afeef20ea6 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package normalize
import (
@@ -14,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)
@@ -66,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/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go
index 7f3a2b8717..325e2751f8 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go
@@ -1,21 +1,25 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package operations
import (
"path"
+ "slices"
"sort"
"strings"
"github.com/go-openapi/jsonpointer"
"github.com/go-openapi/spec"
- "github.com/go-openapi/swag"
+ "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 {
@@ -25,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
@@ -35,27 +39,28 @@ 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()
for method, pathItem := range specDoc.Operations() {
for pth, operation := range pathItem {
vv := *operation
oprefs = append(oprefs, OpRef{
- Key: swag.ToGoName(strings.ToLower(method) + " " + pth),
+ Key: mangler.ToGoName(strings.ToLower(method) + " " + pth),
Method: method,
Path: pth,
ID: vv.ID,
@@ -79,7 +84,7 @@ func GatherOperations(specDoc Provider, operationIDs []string) map[string]OpRef
nm = opr.Key
}
- if len(operationIDs) == 0 || swag.ContainsStrings(operationIDs, opr.ID) || swag.ContainsStrings(operationIDs, nm) {
+ if len(operationIDs) == 0 || slices.Contains(operationIDs, opr.ID) || slices.Contains(operationIDs, nm) {
opr.ID = nm
opr.Op.ID = nm
operations[nm] = opr
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go
new file mode 100644
index 0000000000..b2a8a93ba6
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go
@@ -0,0 +1,64 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
+package replace
+
+import (
+ "errors"
+ "fmt"
+)
+
+type replaceError string
+
+const (
+ ErrReplace replaceError = "flatten replace error"
+ ErrUnexpectedType replaceError = "unexpected type used in getPointerFromKey"
+)
+
+func (e replaceError) Error() string {
+ return string(e)
+}
+
+func ErrNoSchemaWithRef(key string, value any) error {
+ return fmt.Errorf("no schema with ref found at %s for %T: %w", key, value, ErrReplace)
+}
+
+func ErrNoSchema(key string) error {
+ return fmt.Errorf("no schema found at %s: %w", key, ErrReplace)
+}
+
+func ErrNotANumber(key string, err error) error {
+ return errors.Join(
+ ErrReplace,
+ fmt.Errorf("%s not a number: %w", key, err),
+ )
+}
+
+func ErrUnhandledParentRewrite(key string, value any) error {
+ return fmt.Errorf("unhandled parent schema rewrite %s: %T: %w", key, value, ErrReplace)
+}
+
+func ErrUnhandledParentType(key string, value any) error {
+ return fmt.Errorf("unhandled type for parent of %s: %T: %w", key, value, ErrReplace)
+}
+
+func ErrNoParent(key string, err error) error {
+ return errors.Join(
+ fmt.Errorf("can't get parent for %s: %w", key, err),
+ ErrReplace,
+ )
+}
+
+func ErrUnhandledContainerType(key string, value any) error {
+ return fmt.Errorf("unhandled container type at %s: %T: %w", key, value, ErrReplace)
+}
+
+func ErrCyclicChain(key string) error {
+ return fmt.Errorf("cannot resolve cyclic chain of pointers under %s: %w", key, ErrReplace)
+}
+
+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 (%w): %w",
+ key, value, err, ErrReplace,
+ )
+}
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go
index c0f43e728a..b4c0fdd44a 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go
@@ -1,7 +1,11 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package replace
import (
"encoding/json"
+ "errors"
"fmt"
"net/url"
"os"
@@ -13,11 +17,15 @@ import (
"github.com/go-openapi/spec"
)
-const definitionsPath = "#/definitions"
+const (
+ definitionsPath = "#/definitions"
+ 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)
@@ -41,10 +49,10 @@ func RewriteSchemaToRef(sp *spec.Swagger, key string, ref spec.Ref) error {
if refable.Schema != nil {
refable.Schema = &spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
}
- case map[string]interface{}: // this happens e.g. if a schema points to an extension unmarshaled as map[string]interface{}
+ case map[string]any: // this happens e.g. if a schema points to an extension unmarshaled as map[string]interface{}
return rewriteParentRef(sp, key, ref)
default:
- return fmt.Errorf("no schema with ref found at %s for %T", key, value)
+ return ErrNoSchemaWithRef(key, value)
}
return nil
@@ -69,7 +77,7 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error {
case *spec.Responses:
statusCode, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", key[1:], err)
+ return ErrNotANumber(key[1:], err)
}
resp := container.StatusCodeResponses[statusCode]
resp.Schema = &spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
@@ -93,7 +101,7 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error {
case []spec.Parameter:
idx, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", key[1:], err)
+ return ErrNotANumber(key[1:], err)
}
param := container[idx]
param.Schema = &spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
@@ -108,7 +116,7 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error {
case []spec.Schema:
idx, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", key[1:], err)
+ return ErrNotANumber(key[1:], err)
}
container[idx] = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
@@ -116,60 +124,63 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error {
// NOTE: this is necessarily an array - otherwise, the parent would be *Schema
idx, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", key[1:], err)
+ return ErrNotANumber(key[1:], err)
}
container.Schemas[idx] = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
case spec.SchemaProperties:
container[entry] = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
- case *interface{}:
+ case *any:
*container = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
// NOTE: can't have case *spec.SchemaOrBool = parent in this case is *Schema
default:
- return fmt.Errorf("unhandled parent schema rewrite %s (%T)", key, pvalue)
+ return ErrUnhandledParentRewrite(key, pvalue)
}
return nil
}
-// getPointerFromKey retrieves the content of the JSON pointer "key"
-func getPointerFromKey(sp interface{}, key string) (string, interface{}, error) {
+// getPointerFromKey retrieves the content of the JSON pointer "key".
+func getPointerFromKey(sp any, key string) (string, any, error) {
switch sp.(type) {
case *spec.Schema:
case *spec.Swagger:
default:
- panic("unexpected type used in getPointerFromKey")
+ panic(ErrUnexpectedType)
}
if key == "#/" {
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, err
+ return "", nil, errors.Join(err, ErrReplace)
}
value, _, err := ptr.Get(sp)
if err != nil {
debugLog("error when getting key: %s with path: %s", key, pth)
- return "", nil, err
+ return "", nil, errors.Join(err, ErrReplace)
}
return pth, value, nil
}
-// getParentFromKey retrieves the container of the JSON pointer "key"
-func getParentFromKey(sp interface{}, key string) (string, string, interface{}, error) {
+// 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:
case *spec.Swagger:
default:
- panic("unexpected type used in getPointerFromKey")
+ panic(ErrUnexpectedType)
}
// unescape chars in key, e.g. "{}" from path params
pth, _ := url.PathUnescape(key[1:])
@@ -179,23 +190,23 @@ func getParentFromKey(sp interface{}, key string) (string, string, interface{},
pptr, err := jsonpointer.New(parent)
if err != nil {
- return "", "", nil, err
+ return "", "", nil, errors.Join(err, ErrReplace)
}
pvalue, _, err := pptr.Get(sp)
if err != nil {
- return "", "", nil, fmt.Errorf("can't get parent for %s: %w", parent, err)
+ return "", "", nil, ErrNoParent(parent, err)
}
return parent, entry, pvalue, nil
}
-// UpdateRef replaces a ref by another one
-func UpdateRef(sp interface{}, key string, ref spec.Ref) error {
+// UpdateRef replaces a ref by another one.
+func UpdateRef(sp any, key string, ref spec.Ref) error {
switch sp.(type) {
case *spec.Schema:
case *spec.Swagger:
default:
- panic("unexpected type used in getPointerFromKey")
+ panic(ErrUnexpectedType)
}
debugLog("updating ref for %s with %s", key, ref.String())
pth, value, err := getPointerFromKey(sp, key)
@@ -218,7 +229,7 @@ func UpdateRef(sp interface{}, key string, ref spec.Ref) error {
debugLog("rewriting holder for %T", refable)
_, entry, pvalue, erp := getParentFromKey(sp, key)
if erp != nil {
- return err
+ return erp
}
switch container := pvalue.(type) {
case spec.Definitions:
@@ -230,7 +241,7 @@ func UpdateRef(sp interface{}, key string, ref spec.Ref) error {
case []spec.Schema:
idx, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", pth, err)
+ return ErrNotANumber(pth, err)
}
container[idx] = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
@@ -238,7 +249,7 @@ func UpdateRef(sp interface{}, key string, ref spec.Ref) error {
// NOTE: this is necessarily an array - otherwise, the parent would be *Schema
idx, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", pth, err)
+ return ErrNotANumber(pth, err)
}
container.Schemas[idx] = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}}
@@ -248,17 +259,17 @@ func UpdateRef(sp interface{}, key string, ref spec.Ref) error {
// NOTE: can't have case *spec.SchemaOrBool = parent in this case is *Schema
default:
- return fmt.Errorf("unhandled container type at %s: %T", key, value)
+ return ErrUnhandledContainerType(key, value)
}
default:
- return fmt.Errorf("no schema with ref found at %s for %T", key, value)
+ return ErrNoSchemaWithRef(key, value)
}
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)
@@ -272,8 +283,9 @@ func UpdateRefWithSchema(sp *spec.Swagger, key string, sch *spec.Schema) error {
case spec.Schema:
_, entry, pvalue, erp := getParentFromKey(sp, key)
if erp != nil {
- return err
+ return erp
}
+
switch container := pvalue.(type) {
case spec.Definitions:
container[entry] = *sch
@@ -284,7 +296,7 @@ func UpdateRefWithSchema(sp *spec.Swagger, key string, sch *spec.Schema) error {
case []spec.Schema:
idx, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", pth, err)
+ return ErrNotANumber(pth, err)
}
container[idx] = *sch
@@ -292,7 +304,7 @@ func UpdateRefWithSchema(sp *spec.Swagger, key string, sch *spec.Schema) error {
// NOTE: this is necessarily an array - otherwise, the parent would be *Schema
idx, err := strconv.Atoi(entry)
if err != nil {
- return fmt.Errorf("%s not a number: %w", pth, err)
+ return ErrNotANumber(pth, err)
}
container.Schemas[idx] = *sch
@@ -302,7 +314,7 @@ func UpdateRefWithSchema(sp *spec.Swagger, key string, sch *spec.Schema) error {
// NOTE: can't have case *spec.SchemaOrBool = parent in this case is *Schema
default:
- return fmt.Errorf("unhandled type for parent of [%s]: %T", key, value)
+ return ErrUnhandledParentType(key, value)
}
case *spec.SchemaOrArray:
*refable.Schema = *sch
@@ -310,13 +322,13 @@ func UpdateRefWithSchema(sp *spec.Swagger, key string, sch *spec.Schema) error {
case *spec.SchemaOrBool:
*refable.Schema = *sch
default:
- return fmt.Errorf("no schema with ref found at %s for %T", key, value)
+ return ErrNoSchemaWithRef(key, value)
}
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
@@ -324,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:
@@ -336,8 +351,8 @@ func DeepestRef(sp *spec.Swagger, opts *spec.ExpandOptions, ref spec.Ref) (*Deep
}
currentRef := ref
- visited := make(map[string]bool, 64)
- warnings := make([]string, 0, 2)
+ visited := make(map[string]bool, allocMediumMap)
+ warnings := make([]string, 0)
DOWNREF:
for currentRef.String() != "" {
@@ -347,8 +362,7 @@ DOWNREF:
}
if _, beenThere := visited[currentRef.String()]; beenThere {
- return nil,
- fmt.Errorf("cannot resolve cyclic chain of pointers under %s", currentRef.String())
+ return nil, ErrCyclicChain(currentRef.String())
}
visited[currentRef.String()] = true
@@ -385,15 +399,14 @@ 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 {
- return nil,
- fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T (%v)",
- currentRef.String(), value, err,
- )
+ 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()))
@@ -405,13 +418,13 @@ 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 {
- return nil,
- fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T (%v)",
- currentRef.String(), value, err,
- )
+ if err = asSchema.UnmarshalJSON(asJSON); err != nil {
+ return nil, ErrInvalidPointerType(currentRef.String(), value, err)
}
warnings = append(warnings, fmt.Sprintf("found $ref %q (parameter) interpreted as schema", currentRef.String()))
@@ -427,13 +440,13 @@ 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 {
- return nil,
- fmt.Errorf("unhandled type to resolve JSON pointer %s. Expected a Schema, got: %T (%v)",
- currentRef.String(), value, err,
- )
+ 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))
@@ -451,7 +464,7 @@ DOWNREF:
}
if sch == nil {
- return nil, fmt.Errorf("no schema found at %s", currentRef.String())
+ return nil, ErrNoSchema(currentRef.String())
}
return &DeepestRefResult{Ref: currentRef, Schema: sch, Warnings: warnings}, nil
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go
index 4590236e68..59855ef072 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go
@@ -1,29 +1,34 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
// Package schutils provides tools to save or clone a schema
// when flattening a spec.
package schutils
import (
"github.com/go-openapi/spec"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
-// Save registers a schema as an entry in spec #/definitions
+const allocLargeMap = 150
+
+// Save registers a schema as an entry in spec #/definitions.
func Save(sp *spec.Swagger, name string, schema *spec.Schema) {
if schema == nil {
return
}
if sp.Definitions == nil {
- sp.Definitions = make(map[string]spec.Schema, 150)
+ sp.Definitions = make(map[string]spec.Schema, allocLargeMap)
}
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
- _ = swag.FromDynamicJSON(schema, &sch)
+ _ = jsonutils.FromDynamicJSON(schema, &sch)
return &sch
}
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go
index ac80fc2e83..363bb19efa 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package sortref
import (
@@ -17,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": {},
@@ -40,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) }
@@ -57,10 +56,10 @@ 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.Split(key[1:], "/") {
+ for part := range strings.SplitSeq(key[1:], "/") {
if part != "" {
res = append(res, jsonpointer.Unescape(part))
}
@@ -72,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 ""
@@ -86,6 +85,105 @@ func (s SplitKey) DefinitionName() string {
return s[1]
}
+// PartAdder know how to construct the components of a new name.
+type PartAdder func(string) []string
+
+// 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) {
+ segments = append(segments, adder(part)...)
+ }
+ }
+
+ return strings.Join(segments, " ")
+}
+
+// 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.
+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.
+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.
+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.
+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.
+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.
+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.
+func (s SplitKey) IsStatusCodeResponse() bool {
+ isInt := func() bool {
+ _, err := strconv.Atoi(s[4])
+
+ return err == nil
+ }
+
+ return len(s) > 4 && s[0] == paths && s[3] == responses && isInt()
+}
+
+// ResponseName yields either the status code or "Default" for a response.
+func (s SplitKey) ResponseName() string {
+ if s.IsStatusCodeResponse() {
+ code, _ := strconv.Atoi(s[4])
+
+ return http.StatusText(code)
+ }
+
+ if s.IsDefaultResponse() {
+ return "Default"
+ }
+
+ return ""
+}
+
+// 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 {
+ return spec.Ref{}
+ }
+
+ pth, method := s[1], s[2]
+ if _, isValidMethod := validMethods[strings.ToUpper(method)]; !isValidMethod && !strings.HasPrefix(method, "x-") {
+ return 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}.
+func (s SplitKey) PathRef() spec.Ref {
+ if !s.IsOperation() {
+ return spec.Ref{}
+ }
+
+ return spec.MustCreateRef("#" + path.Join("/", paths, jsonpointer.Escape(s[1])))
+}
+
func (s SplitKey) isKeyName(i int) bool {
if i <= 0 {
return false
@@ -101,101 +199,3 @@ func (s SplitKey) isKeyName(i int) bool {
return count%2 != 0
}
-
-// PartAdder know how to construct the components of a new name
-type PartAdder func(string) []string
-
-// 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) {
- segments = append(segments, adder(part)...)
- }
- }
-
- return strings.Join(segments, " ")
-}
-
-// 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
-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
-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
-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
-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
-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
-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
-func (s SplitKey) IsStatusCodeResponse() bool {
- isInt := func() bool {
- _, err := strconv.Atoi(s[4])
-
- return err == nil
- }
-
- return len(s) > 4 && s[0] == paths && s[3] == responses && isInt()
-}
-
-// ResponseName yields either the status code or "Default" for a response
-func (s SplitKey) ResponseName() string {
- if s.IsStatusCodeResponse() {
- code, _ := strconv.Atoi(s[4])
-
- return http.StatusText(code)
- }
-
- if s.IsDefaultResponse() {
- return "Default"
- }
-
- return ""
-}
-
-// PathItemRef constructs a $ref object from a split key of the form /{path}/{method}
-func (s SplitKey) PathItemRef() spec.Ref {
- if len(s) < 3 {
- return spec.Ref{}
- }
-
- pth, method := s[1], s[2]
- if _, isValidMethod := validMethods[strings.ToUpper(method)]; !isValidMethod && !strings.HasPrefix(method, "x-") {
- return 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}
-func (s SplitKey) PathRef() spec.Ref {
- if !s.IsOperation() {
- return spec.Ref{}
- }
-
- return spec.MustCreateRef("#" + path.Join("/", paths, jsonpointer.Escape(s[1])))
-}
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go
index 73243df87f..e4ad07b096 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go
@@ -1,7 +1,12 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package sortref
import (
+ "iter"
"reflect"
+ "slices"
"sort"
"strings"
@@ -9,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
@@ -30,7 +31,7 @@ func (i *mapIterator) Key() string {
return i.mapIter.Key().String()
}
-func mustMapIterator(anyMap interface{}) *mapIterator {
+func mustMapIterator(anyMap any) *mapIterator {
val := reflect.ValueOf(anyMap)
return &mapIterator{mapIter: val.MapRange(), len: val.Len()}
@@ -39,8 +40,8 @@ func mustMapIterator(anyMap interface{}) *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
-func DepthFirst(in interface{}) []string {
+// flatten groups into a single list of keys.
+func DepthFirst(in any) []string {
iterator := mustMapIterator(in)
sorted := make([]string, 0, iterator.Len())
grouped := make(map[string]Keys, iterator.Len())
@@ -74,7 +75,7 @@ func DepthFirst(in interface{}) []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)
@@ -86,6 +87,12 @@ func DepthFirst(in interface{}) []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
@@ -101,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)
@@ -109,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/test/tools/vendor/github.com/go-openapi/analysis/mixin.go b/test/tools/vendor/github.com/go-openapi/analysis/mixin.go
index 7785a29b27..a7a9306cb3 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/mixin.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/mixin.go
@@ -1,22 +1,12 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package analysis
import (
"fmt"
"reflect"
+ "slices"
"github.com/go-openapi/spec"
)
@@ -28,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
@@ -49,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))
@@ -248,14 +239,7 @@ func mergeResponses(primary *spec.Swagger, m *spec.Swagger) (skipped []string) {
func mergeConsumes(primary *spec.Swagger, m *spec.Swagger) []string {
for _, v := range m.Consumes {
- found := false
- for _, vv := range primary.Consumes {
- if v == vv {
- found = true
-
- break
- }
- }
+ found := slices.Contains(primary.Consumes, v)
if found {
// no warning here: we just skip it
@@ -269,14 +253,7 @@ func mergeConsumes(primary *spec.Swagger, m *spec.Swagger) []string {
func mergeProduces(primary *spec.Swagger, m *spec.Swagger) []string {
for _, v := range m.Produces {
- found := false
- for _, vv := range primary.Produces {
- if v == vv {
- found = true
-
- break
- }
- }
+ found := slices.Contains(primary.Produces, v)
if found {
// no warning here: we just skip it
@@ -317,14 +294,7 @@ func mergeTags(primary *spec.Swagger, m *spec.Swagger) (skipped []string) {
func mergeSchemes(primary *spec.Swagger, m *spec.Swagger) []string {
for _, v := range m.Schemes {
- found := false
- for _, vv := range primary.Schemes {
- if v == vv {
- found = true
-
- break
- }
- }
+ found := slices.Contains(primary.Schemes, v)
if found {
// no warning here: we just skip it
@@ -391,7 +361,7 @@ func mergeInfo(primary *spec.Info, m *spec.Info) []string {
}
if primary.Title == "" {
- primary.Description = m.Description
+ primary.Title = m.Title
}
if primary.TermsOfService == "" {
@@ -474,23 +444,23 @@ func initPrimary(primary *spec.Swagger) {
}
if primary.Security == nil {
- primary.Security = make([]map[string][]string, 0, 10)
+ primary.Security = make([]map[string][]string, 0, allocSmallMap)
}
if primary.Produces == nil {
- primary.Produces = make([]string, 0, 10)
+ primary.Produces = make([]string, 0, allocSmallMap)
}
if primary.Consumes == nil {
- primary.Consumes = make([]string, 0, 10)
+ primary.Consumes = make([]string, 0, allocSmallMap)
}
if primary.Tags == nil {
- primary.Tags = make([]spec.Tag, 0, 10)
+ primary.Tags = make([]spec.Tag, 0, allocSmallMap)
}
if primary.Schemes == nil {
- primary.Schemes = make([]string, 0, 10)
+ primary.Schemes = make([]string, 0, allocSmallMap)
}
if primary.Paths == nil {
diff --git a/test/tools/vendor/github.com/go-openapi/analysis/schema.go b/test/tools/vendor/github.com/go-openapi/analysis/schema.go
index ab190db5b7..bedea652ac 100644
--- a/test/tools/vendor/github.com/go-openapi/analysis/schema.go
+++ b/test/tools/vendor/github.com/go-openapi/analysis/schema.go
@@ -1,16 +1,17 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package analysis
import (
- "errors"
-
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
)
-// SchemaOpts configures the schema analyzer
+// SchemaOpts configures the schema analyzer.
type SchemaOpts struct {
Schema *spec.Schema
- Root interface{}
+ Root any
BasePath string
_ struct{}
}
@@ -19,7 +20,7 @@ type SchemaOpts struct {
// patterns.
func Schema(opts SchemaOpts) (*AnalyzedSchema, error) {
if opts.Schema == nil {
- return nil, errors.New("no schema to analyze")
+ return nil, ErrNoSchema
}
a := &AnalyzedSchema{
@@ -51,10 +52,10 @@ 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 interface{}
+ root any
basePath string
hasProps bool
@@ -77,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/test/tools/vendor/github.com/go-openapi/errors/.editorconfig b/test/tools/vendor/github.com/go-openapi/errors/.editorconfig
new file mode 100644
index 0000000000..3152da69a5
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/errors/.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/test/tools/vendor/github.com/go-openapi/errors/.gitignore b/test/tools/vendor/github.com/go-openapi/errors/.gitignore
index dd91ed6a04..9364443a6f 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/.gitignore
+++ b/test/tools/vendor/github.com/go-openapi/errors/.gitignore
@@ -1,2 +1,7 @@
-secrets.yml
-coverage.out
+*.out
+*.cov
+.idea
+.env
+.mcp.json
+.claude/
+settings.local.json
diff --git a/test/tools/vendor/github.com/go-openapi/errors/.golangci.yml b/test/tools/vendor/github.com/go-openapi/errors/.golangci.yml
index cf88ead324..e2c14be86d 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/errors/.golangci.yml
@@ -1,62 +1,71 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - errname # this repo doesn't follow the convention advised by this linter
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
+ - depguard
- funlen
- godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- exhaustruct
- - varnamelen
- - gci
- - depguard
- - errchkjson
- - inamedparam
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 20
+ gocyclo:
+ min-complexity: 20
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - 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$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/errors/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/errors/CONTRIBUTORS.md
new file mode 100644
index 0000000000..d49e377a13
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/errors/CONTRIBUTORS.md
@@ -0,0 +1,25 @@
+# Contributors
+
+- Repository: ['go-openapi/errors']
+
+| Total Contributors | Total Contributions |
+| --- | --- |
+| 13 | 110 |
+
+| Username | All Time Contribution Count | All Commits |
+| --- | --- | --- |
+| @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/test/tools/vendor/github.com/go-openapi/errors/README.md b/test/tools/vendor/github.com/go-openapi/errors/README.md
index 6d57ea55c7..d9f4a3f151 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/README.md
+++ b/test/tools/vendor/github.com/go-openapi/errors/README.md
@@ -1,8 +1,118 @@
-# OpenAPI errors [](https://github.com/go-openapi/errors/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/errors)
+# errors
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/errors/master/LICENSE)
-[](https://pkg.go.dev/github.com/go-openapi/errors)
-[](https://goreportcard.com/report/github.com/go-openapi/errors)
+
+[![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]
+
+---
Shared errors and error interface used throughout the various libraries found in the go-openapi toolkit.
+
+## 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/errors
+```
+
+## Basic usage
+
+```go
+const url = "https://www.example.com/#"
+
+errGeneric := New(401,"onvalid argument: %s", url)
+
+errNotFound := NotFound("resource not found: %s", url)
+
+errNotImplemented := NotImplemented("method: %s", url)
+```
+
+## 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/errors/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/errors/actions/workflows/go-test.yml/badge.svg
+[test-url]: https://github.com/go-openapi/errors/actions/workflows/go-test.yml
+[cov-badge]: https://codecov.io/gh/go-openapi/errors/branch/master/graph/badge.svg
+[cov-url]: https://codecov.io/gh/go-openapi/errors
+[vuln-scan-badge]: https://github.com/go-openapi/errors/actions/workflows/scanner.yml/badge.svg
+[vuln-scan-url]: https://github.com/go-openapi/errors/actions/workflows/scanner.yml
+[codeql-badge]: https://github.com/go-openapi/errors/actions/workflows/codeql.yml/badge.svg
+[codeql-url]: https://github.com/go-openapi/errors/actions/workflows/codeql.yml
+
+[release-badge]: https://badge.fury.io/gh/go-openapi%2Ferrors.svg
+[release-url]: https://badge.fury.io/gh/go-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
+
+[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/twZ9BwT3
+
+
+[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg
+[license-url]: https://github.com/go-openapi/errors/?tab=Apache-2.0-1-ov-file#readme
+
+[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/errors
+[goversion-url]: https://github.com/go-openapi/errors/blob/master/go.mod
+[top-badge]: https://img.shields.io/github/languages/top/go-openapi/errors
+[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/errors/latest
diff --git a/test/tools/vendor/github.com/go-openapi/errors/SECURITY.md b/test/tools/vendor/github.com/go-openapi/errors/SECURITY.md
new file mode 100644
index 0000000000..6ceb159ca2
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/errors/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/test/tools/vendor/github.com/go-openapi/errors/api.go b/test/tools/vendor/github.com/go-openapi/errors/api.go
index 5320cb9630..d2b4427aac 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/api.go
+++ b/test/tools/vendor/github.com/go-openapi/errors/api.go
@@ -1,21 +1,11 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package errors
import (
"encoding/json"
+ "errors"
"fmt"
"net/http"
"reflect"
@@ -23,9 +13,11 @@ import (
)
// DefaultHTTPCode is used when the error Code cannot be used as an HTTP code.
+//
+//nolint:gochecknoglobals // it should have been a constant in the first place, but now it is mutable so we have to leave it here or introduce a breaking change.
var DefaultHTTPCode = http.StatusUnprocessableEntity
-// Error represents a error interface all swagger framework errors implement
+// Error represents a error interface all swagger framework errors implement.
type Error interface {
error
Code() int32
@@ -36,24 +28,26 @@ type apiError struct {
message string
}
+// Error implements the standard error interface.
func (a *apiError) Error() string {
return a.message
}
+// Code returns the HTTP status code associated with this error.
func (a *apiError) Code() int32 {
return a.code
}
-// MarshalJSON implements the JSON encoding interface
+// MarshalJSON implements the JSON encoding interface.
func (a apiError) MarshalJSON() ([]byte, error) {
- return json.Marshal(map[string]interface{}{
+ return json.Marshal(map[string]any{
"code": a.code,
"message": a.message,
})
}
-// New creates a new API error with a code and a message
-func New(code int32, message string, args ...interface{}) Error {
+// New creates a new API error with a code and a message.
+func New(code int32, message string, args ...any) Error {
if len(args) > 0 {
return &apiError{
code: code,
@@ -66,38 +60,39 @@ func New(code int32, message string, args ...interface{}) Error {
}
}
-// NotFound creates a new not found error
-func NotFound(message string, args ...interface{}) Error {
+// NotFound creates a new not found error.
+func NotFound(message string, args ...any) Error {
if message == "" {
message = "Not found"
}
- return New(http.StatusNotFound, fmt.Sprintf(message, args...))
+ return New(http.StatusNotFound, message, args...)
}
-// NotImplemented creates a new not implemented error
+// NotImplemented creates a new not implemented error.
func NotImplemented(message string) Error {
- return New(http.StatusNotImplemented, message)
+ return New(http.StatusNotImplemented, "%s", message)
}
-// MethodNotAllowedError represents an error for when the path matches but the method doesn't
+// MethodNotAllowedError represents an error for when the path matches but the method doesn't.
type MethodNotAllowedError struct {
code int32
Allowed []string
message string
}
+// Error implements the standard error interface.
func (m *MethodNotAllowedError) Error() string {
return m.message
}
-// Code the error code
+// Code returns 405 (Method Not Allowed) as the HTTP status code.
func (m *MethodNotAllowedError) Code() int32 {
return m.code
}
-// MarshalJSON implements the JSON encoding interface
+// MarshalJSON implements the JSON encoding interface.
func (m MethodNotAllowedError) MarshalJSON() ([]byte, error) {
- return json.Marshal(map[string]interface{}{
+ return json.Marshal(map[string]any{
"code": m.code,
"message": m.message,
"allowed": m.Allowed,
@@ -115,25 +110,33 @@ func errorAsJSON(err Error) []byte {
func flattenComposite(errs *CompositeError) *CompositeError {
var res []error
- for _, er := range errs.Errors {
- switch e := er.(type) {
- case *CompositeError:
- if e != nil && len(e.Errors) > 0 {
- flat := flattenComposite(e)
- if len(flat.Errors) > 0 {
- res = append(res, flat.Errors...)
- }
- }
- default:
- if e != nil {
- res = append(res, e)
- }
+
+ for _, err := range errs.Errors {
+ if err == nil {
+ continue
}
+
+ e := &CompositeError{}
+ if !errors.As(err, &e) {
+ res = append(res, err)
+
+ continue
+ }
+
+ if len(e.Errors) == 0 {
+ res = append(res, e)
+
+ continue
+ }
+
+ flat := flattenComposite(e)
+ res = append(res, flat.Errors...)
}
+
return CompositeValidationError(res...)
}
-// MethodNotAllowed creates a new method not allowed error
+// MethodNotAllowed creates a new method not allowed error.
func MethodNotAllowed(requested string, allow []string) Error {
msg := fmt.Sprintf("method %s is not allowed, but [%s] are", requested, strings.Join(allow, ","))
return &MethodNotAllowedError{
@@ -143,49 +146,65 @@ 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")
- switch e := err.(type) {
- case *CompositeError:
- er := flattenComposite(e)
+
+ if err == nil {
+ rw.WriteHeader(http.StatusInternalServerError)
+ _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
+
+ return
+ }
+
+ errComposite := &CompositeError{}
+ errMethodNotAllowed := &MethodNotAllowedError{}
+ var errError Error
+
+ switch {
+ case errors.As(err, &errComposite):
+ er := flattenComposite(errComposite)
// strips composite errors to first element only
if len(er.Errors) > 0 {
ServeError(rw, r, er.Errors[0])
- } else {
- // guard against empty CompositeError (invalid construct)
- ServeError(rw, r, nil)
+
+ return
}
- case *MethodNotAllowedError:
- rw.Header().Add("Allow", strings.Join(e.Allowed, ","))
- rw.WriteHeader(asHTTPCode(int(e.Code())))
+
+ // guard against empty CompositeError (invalid construct)
+ ServeError(rw, r, nil)
+
+ case errors.As(err, &errMethodNotAllowed):
+ rw.Header().Add("Allow", strings.Join(errMethodNotAllowed.Allowed, ","))
+ rw.WriteHeader(asHTTPCode(int(errMethodNotAllowed.Code())))
if r == nil || r.Method != http.MethodHead {
- _, _ = rw.Write(errorAsJSON(e))
+ _, _ = rw.Write(errorAsJSON(errMethodNotAllowed))
}
- case Error:
- value := reflect.ValueOf(e)
+
+ case errors.As(err, &errError):
+ value := reflect.ValueOf(errError)
if value.Kind() == reflect.Ptr && value.IsNil() {
rw.WriteHeader(http.StatusInternalServerError)
_, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
+
return
}
- rw.WriteHeader(asHTTPCode(int(e.Code())))
+
+ rw.WriteHeader(asHTTPCode(int(errError.Code())))
if r == nil || r.Method != http.MethodHead {
- _, _ = rw.Write(errorAsJSON(e))
+ _, _ = rw.Write(errorAsJSON(errError))
}
- case nil:
- rw.WriteHeader(http.StatusInternalServerError)
- _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
+
default:
rw.WriteHeader(http.StatusInternalServerError)
if r == nil || r.Method != http.MethodHead {
- _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, err.Error())))
+ _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "%v", err)))
}
}
}
func asHTTPCode(input int) int {
- if input >= 600 {
+ if input >= maximumValidHTTPCode {
return DefaultHTTPCode
}
return input
diff --git a/test/tools/vendor/github.com/go-openapi/errors/auth.go b/test/tools/vendor/github.com/go-openapi/errors/auth.go
index 0545b501bd..1173b5642c 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/auth.go
+++ b/test/tools/vendor/github.com/go-openapi/errors/auth.go
@@ -1,22 +1,11 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package errors
import "net/http"
-// Unauthenticated returns an unauthenticated error
+// Unauthenticated returns an unauthenticated error.
func Unauthenticated(scheme string) Error {
return New(http.StatusUnauthorized, "unauthenticated for %s", scheme)
}
diff --git a/test/tools/vendor/github.com/go-openapi/errors/doc.go b/test/tools/vendor/github.com/go-openapi/errors/doc.go
index af01190ce6..208c740590 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/doc.go
+++ b/test/tools/vendor/github.com/go-openapi/errors/doc.go
@@ -1,26 +1,13 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// 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/test/tools/vendor/github.com/go-openapi/errors/headers.go b/test/tools/vendor/github.com/go-openapi/errors/headers.go
index dfebe8f95f..717a51ac43 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/headers.go
+++ b/test/tools/vendor/github.com/go-openapi/errors/headers.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package errors
@@ -20,28 +9,30 @@ import (
"net/http"
)
-// Validation represents a failure of a precondition
-type Validation struct {
+// Validation represents a failure of a precondition.
+type Validation struct { //nolint: errname // changing the name to abide by the naming rule would bring a breaking change.
code int32
Name string
In string
- Value interface{}
+ Value any
message string
- Values []interface{}
+ Values []any
}
+// Error implements the standard error interface.
func (e *Validation) Error() string {
return e.message
}
-// Code the error code
+// Code returns the HTTP status code for this validation error.
+// Returns 422 (Unprocessable Entity) by default.
func (e *Validation) Code() int32 {
return e.code
}
-// MarshalJSON implements the JSON encoding interface
+// MarshalJSON implements the JSON encoding interface.
func (e Validation) MarshalJSON() ([]byte, error) {
- return json.Marshal(map[string]interface{}{
+ return json.Marshal(map[string]any{
"code": e.code,
"message": e.message,
"in": e.In,
@@ -51,7 +42,7 @@ func (e Validation) MarshalJSON() ([]byte, error) {
})
}
-// ValidateName sets the name for a validation or updates it for a nested property
+// ValidateName sets the name for a validation or updates it for a nested property.
func (e *Validation) ValidateName(name string) *Validation {
if name != "" {
if e.Name == "" {
@@ -70,9 +61,9 @@ const (
responseFormatFail = `unsupported media type requested, only %v are available`
)
-// InvalidContentType error for an invalid content type
+// InvalidContentType error for an invalid content type.
func InvalidContentType(value string, allowed []string) *Validation {
- values := make([]interface{}, 0, len(allowed))
+ values := make([]any, 0, len(allowed))
for _, v := range allowed {
values = append(values, v)
}
@@ -86,9 +77,9 @@ func InvalidContentType(value string, allowed []string) *Validation {
}
}
-// InvalidResponseFormat error for an unacceptable response format request
+// InvalidResponseFormat error for an unacceptable response format request.
func InvalidResponseFormat(value string, allowed []string) *Validation {
- values := make([]interface{}, 0, len(allowed))
+ values := make([]any, 0, len(allowed))
for _, v := range allowed {
values = append(values, v)
}
diff --git a/test/tools/vendor/github.com/go-openapi/errors/middleware.go b/test/tools/vendor/github.com/go-openapi/errors/middleware.go
index 963472d1f3..f89275f9c1 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/middleware.go
+++ b/test/tools/vendor/github.com/go-openapi/errors/middleware.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package errors
@@ -21,13 +10,14 @@ import (
)
// APIVerificationFailed is an error that contains all the missing info for a mismatched section
-// between the api registrations and the api spec
-type APIVerificationFailed struct {
+// between the api registrations and the api spec.
+type APIVerificationFailed struct { //nolint: errname
Section string `json:"section,omitempty"`
MissingSpecification []string `json:"missingSpecification,omitempty"`
MissingRegistration []string `json:"missingRegistration,omitempty"`
}
+// Error implements the standard error interface.
func (v *APIVerificationFailed) Error() string {
buf := bytes.NewBuffer(nil)
@@ -35,7 +25,7 @@ func (v *APIVerificationFailed) Error() string {
hasSpecMissing := len(v.MissingSpecification) > 0
if hasRegMissing {
- buf.WriteString(fmt.Sprintf("missing [%s] %s registrations", strings.Join(v.MissingRegistration, ", "), v.Section))
+ fmt.Fprintf(buf, "missing [%s] %s registrations", strings.Join(v.MissingRegistration, ", "), v.Section)
}
if hasRegMissing && hasSpecMissing {
@@ -43,7 +33,7 @@ func (v *APIVerificationFailed) Error() string {
}
if hasSpecMissing {
- buf.WriteString(fmt.Sprintf("missing from spec file [%s] %s", strings.Join(v.MissingSpecification, ", "), v.Section))
+ fmt.Fprintf(buf, "missing from spec file [%s] %s", strings.Join(v.MissingSpecification, ", "), v.Section)
}
return buf.String()
diff --git a/test/tools/vendor/github.com/go-openapi/errors/parsing.go b/test/tools/vendor/github.com/go-openapi/errors/parsing.go
index 5096e1ea7b..46e6612cdf 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/parsing.go
+++ b/test/tools/vendor/github.com/go-openapi/errors/parsing.go
@@ -1,25 +1,15 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package errors
import (
"encoding/json"
"fmt"
+ "net/http"
)
-// ParseError represents a parsing error
+// ParseError represents a parsing error.
type ParseError struct {
code int32
Name string
@@ -29,22 +19,41 @@ type ParseError struct {
message string
}
+// NewParseError creates a new parse error.
+func NewParseError(name, in, value string, reason error) *ParseError {
+ var msg string
+ if in == "" {
+ msg = fmt.Sprintf(parseErrorTemplContentNoIn, name, value, reason)
+ } else {
+ msg = fmt.Sprintf(parseErrorTemplContent, name, in, value, reason)
+ }
+ return &ParseError{
+ code: http.StatusBadRequest,
+ Name: name,
+ In: in,
+ Value: value,
+ Reason: reason,
+ message: msg,
+ }
+}
+
+// Error implements the standard error interface.
func (e *ParseError) Error() string {
return e.message
}
-// Code returns the http status code for this error
+// Code returns 400 (Bad Request) as the HTTP status code for parsing errors.
func (e *ParseError) Code() int32 {
return e.code
}
-// MarshalJSON implements the JSON encoding interface
+// MarshalJSON implements the JSON encoding interface.
func (e ParseError) MarshalJSON() ([]byte, error) {
var reason string
if e.Reason != nil {
reason = e.Reason.Error()
}
- return json.Marshal(map[string]interface{}{
+ return json.Marshal(map[string]any{
"code": e.code,
"message": e.message,
"in": e.In,
@@ -58,21 +67,3 @@ const (
parseErrorTemplContent = `parsing %s %s from %q failed, because %s`
parseErrorTemplContentNoIn = `parsing %s from %q failed, because %s`
)
-
-// NewParseError creates a new parse error
-func NewParseError(name, in, value string, reason error) *ParseError {
- var msg string
- if in == "" {
- msg = fmt.Sprintf(parseErrorTemplContentNoIn, name, value, reason)
- } else {
- msg = fmt.Sprintf(parseErrorTemplContent, name, in, value, reason)
- }
- return &ParseError{
- code: 400,
- Name: name,
- In: in,
- Value: value,
- Reason: reason,
- message: msg,
- }
-}
diff --git a/test/tools/vendor/github.com/go-openapi/errors/schema.go b/test/tools/vendor/github.com/go-openapi/errors/schema.go
index cf7ac2ed4d..2378bae67f 100644
--- a/test/tools/vendor/github.com/go-openapi/errors/schema.go
+++ b/test/tools/vendor/github.com/go-openapi/errors/schema.go
@@ -1,22 +1,13 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package errors
import (
"encoding/json"
+ "errors"
"fmt"
+ "net/http"
"strings"
)
@@ -32,12 +23,12 @@ const (
patternFail = "%s in %s should match '%s'"
enumFail = "%s in %s should be one of %v"
multipleOfFail = "%s in %s should be a multiple of %v"
- maxIncFail = "%s in %s should be less than or equal to %v"
- maxExcFail = "%s in %s should be less than %v"
+ maximumIncFail = "%s in %s should be less than or equal to %v"
+ maximumExcFail = "%s in %s should be less than %v"
minIncFail = "%s in %s should be greater than or equal to %v"
minExcFail = "%s in %s should be greater than %v"
uniqueFail = "%s in %s shouldn't contain duplicates"
- maxItemsFail = "%s in %s should have at most %d items"
+ maximumItemsFail = "%s in %s should have at most %d items"
minItemsFail = "%s in %s should have at least %d items"
typeFailNoIn = "%s must be of type %s"
typeFailWithDataNoIn = "%s must be of type %s: %q"
@@ -49,12 +40,12 @@ const (
patternFailNoIn = "%s should match '%s'"
enumFailNoIn = "%s should be one of %v"
multipleOfFailNoIn = "%s should be a multiple of %v"
- maxIncFailNoIn = "%s should be less than or equal to %v"
- maxExcFailNoIn = "%s should be less than %v"
+ maximumIncFailNoIn = "%s should be less than or equal to %v"
+ maximumExcFailNoIn = "%s should be less than %v"
minIncFailNoIn = "%s should be greater than or equal to %v"
minExcFailNoIn = "%s should be greater than %v"
uniqueFailNoIn = "%s shouldn't contain duplicates"
- maxItemsFailNoIn = "%s should have at most %d items"
+ maximumItemsFailNoIn = "%s should have at most %d items"
minItemsFailNoIn = "%s should have at least %d items"
noAdditionalItems = "%s in %s can't have additional items"
noAdditionalItemsNoIn = "%s can't have additional items"
@@ -69,14 +60,18 @@ const (
multipleOfMustBePositive = "factor MultipleOf declared for %s must be positive: %v"
)
+const maximumValidHTTPCode = 600
+
// All code responses can be used to differentiate errors for different handling
-// by the consuming program
+// by the consuming program.
const (
// CompositeErrorCode remains 422 for backwards-compatibility
- // and to separate it from validation errors with cause
- CompositeErrorCode = 422
- // InvalidTypeCode is used for any subclass of invalid types
- InvalidTypeCode = 600 + iota
+ // and to separate it from validation errors with cause.
+ CompositeErrorCode = http.StatusUnprocessableEntity
+
+ // InvalidTypeCode is used for any subclass of invalid types.
+ InvalidTypeCode = maximumValidHTTPCode + iota
+ // RequiredFailCode indicates a required field is missing.
RequiredFailCode
TooLongFailCode
TooShortFailCode
@@ -97,22 +92,26 @@ const (
ReadOnlyFailCode
)
-// CompositeError is an error that groups several errors together
+// CompositeError is an error that groups several errors together.
type CompositeError struct {
Errors []error
code int32
message string
}
-// Code for this error
+// Code returns the HTTP status code for this composite error.
func (c *CompositeError) Code() int32 {
return c.code
}
+// Error implements the standard error interface.
func (c *CompositeError) Error() string {
if len(c.Errors) > 0 {
msgs := []string{c.message + ":"}
for _, e := range c.Errors {
+ if e == nil {
+ continue
+ }
msgs = append(msgs, e.Error())
}
return strings.Join(msgs, "\n")
@@ -120,20 +119,21 @@ func (c *CompositeError) Error() string {
return c.message
}
+// Unwrap implements the [errors.Unwrap] interface.
func (c *CompositeError) Unwrap() []error {
return c.Errors
}
-// MarshalJSON implements the JSON encoding interface
+// MarshalJSON implements the JSON encoding interface.
func (c CompositeError) MarshalJSON() ([]byte, error) {
- return json.Marshal(map[string]interface{}{
+ return json.Marshal(map[string]any{
"code": c.code,
"message": c.message,
"errors": c.Errors,
})
}
-// CompositeValidationError an error to wrap a bunch of other errors
+// CompositeValidationError an error to wrap a bunch of other errors.
func CompositeValidationError(errors ...error) *CompositeError {
return &CompositeError{
code: CompositeErrorCode,
@@ -142,20 +142,33 @@ func CompositeValidationError(errors ...error) *CompositeError {
}
}
-// ValidateName recursively sets the name for all validations or updates them for nested properties
+// ValidateName recursively sets the name for all validations or updates them for nested properties.
func (c *CompositeError) ValidateName(name string) *CompositeError {
for i, e := range c.Errors {
- if ve, ok := e.(*Validation); ok {
- c.Errors[i] = ve.ValidateName(name)
- } else if ce, ok := e.(*CompositeError); ok {
- c.Errors[i] = ce.ValidateName(name)
+ if e == nil {
+ continue
}
+
+ ce := &CompositeError{}
+ if errors.As(e, &ce) {
+ c.Errors[i] = ce.ValidateName(name)
+
+ continue
+ }
+
+ ve := &Validation{}
+ if errors.As(e, &ve) {
+ c.Errors[i] = ve.ValidateName(name)
+
+ continue
+ }
+
}
return c
}
-// FailedAllPatternProperties an error for when the property doesn't match a pattern
+// FailedAllPatternProperties an error for when the property doesn't match a pattern.
func FailedAllPatternProperties(name, in, key string) *Validation {
msg := fmt.Sprintf(failedAllPatternProps, name, key, in)
if in == "" {
@@ -170,7 +183,7 @@ func FailedAllPatternProperties(name, in, key string) *Validation {
}
}
-// PropertyNotAllowed an error for when the property doesn't match a pattern
+// PropertyNotAllowed an error for when the property doesn't match a pattern.
func PropertyNotAllowed(name, in, key string) *Validation {
msg := fmt.Sprintf(unallowedProperty, name, key, in)
if in == "" {
@@ -185,7 +198,7 @@ func PropertyNotAllowed(name, in, key string) *Validation {
}
}
-// TooFewProperties an error for an object with too few properties
+// TooFewProperties an error for an object with too few properties.
func TooFewProperties(name, in string, n int64) *Validation {
msg := fmt.Sprintf(tooFewProperties, name, in, n)
if in == "" {
@@ -200,7 +213,7 @@ func TooFewProperties(name, in string, n int64) *Validation {
}
}
-// TooManyProperties an error for an object with too many properties
+// TooManyProperties an error for an object with too many properties.
func TooManyProperties(name, in string, n int64) *Validation {
msg := fmt.Sprintf(tooManyProperties, name, in, n)
if in == "" {
@@ -215,7 +228,7 @@ func TooManyProperties(name, in string, n int64) *Validation {
}
}
-// AdditionalItemsNotAllowed an error for invalid additional items
+// AdditionalItemsNotAllowed an error for invalid additional items.
func AdditionalItemsNotAllowed(name, in string) *Validation {
msg := fmt.Sprintf(noAdditionalItems, name, in)
if in == "" {
@@ -229,7 +242,7 @@ func AdditionalItemsNotAllowed(name, in string) *Validation {
}
}
-// InvalidCollectionFormat another flavor of invalid type error
+// InvalidCollectionFormat another flavor of invalid type error.
func InvalidCollectionFormat(name, in, format string) *Validation {
return &Validation{
code: InvalidTypeCode,
@@ -240,7 +253,7 @@ func InvalidCollectionFormat(name, in, format string) *Validation {
}
}
-// InvalidTypeName an error for when the type is invalid
+// InvalidTypeName an error for when the type is invalid.
func InvalidTypeName(typeName string) *Validation {
return &Validation{
code: InvalidTypeCode,
@@ -249,8 +262,8 @@ func InvalidTypeName(typeName string) *Validation {
}
}
-// InvalidType creates an error for when the type is invalid
-func InvalidType(name, in, typeName string, value interface{}) *Validation {
+// InvalidType creates an error for when the type is invalid.
+func InvalidType(name, in, typeName string, value any) *Validation {
var message string
if in != "" {
@@ -280,10 +293,9 @@ func InvalidType(name, in, typeName string, value interface{}) *Validation {
Value: value,
message: message,
}
-
}
-// DuplicateItems error for when an array contains duplicates
+// DuplicateItems error for when an array contains duplicates.
func DuplicateItems(name, in string) *Validation {
msg := fmt.Sprintf(uniqueFail, name, in)
if in == "" {
@@ -297,11 +309,11 @@ func DuplicateItems(name, in string) *Validation {
}
}
-// TooManyItems error for when an array contains too many items
-func TooManyItems(name, in string, max int64, value interface{}) *Validation {
- msg := fmt.Sprintf(maxItemsFail, name, in, max)
+// TooManyItems error for when an array contains too many items.
+func TooManyItems(name, in string, maximum int64, value any) *Validation {
+ msg := fmt.Sprintf(maximumItemsFail, name, in, maximum)
if in == "" {
- msg = fmt.Sprintf(maxItemsFailNoIn, name, max)
+ msg = fmt.Sprintf(maximumItemsFailNoIn, name, maximum)
}
return &Validation{
@@ -313,11 +325,11 @@ func TooManyItems(name, in string, max int64, value interface{}) *Validation {
}
}
-// TooFewItems error for when an array contains too few items
-func TooFewItems(name, in string, min int64, value interface{}) *Validation {
- msg := fmt.Sprintf(minItemsFail, name, in, min)
+// TooFewItems error for when an array contains too few items.
+func TooFewItems(name, in string, minimum int64, value any) *Validation {
+ msg := fmt.Sprintf(minItemsFail, name, in, minimum)
if in == "" {
- msg = fmt.Sprintf(minItemsFailNoIn, name, min)
+ msg = fmt.Sprintf(minItemsFailNoIn, name, minimum)
}
return &Validation{
code: MinItemsFailCode,
@@ -328,21 +340,21 @@ func TooFewItems(name, in string, min int64, value interface{}) *Validation {
}
}
-// ExceedsMaximumInt error for when maximum validation fails
-func ExceedsMaximumInt(name, in string, max int64, exclusive bool, value interface{}) *Validation {
+// ExceedsMaximumInt error for when maximum validation fails.
+func ExceedsMaximumInt(name, in string, maximum int64, exclusive bool, value any) *Validation {
var message string
if in == "" {
- m := maxIncFailNoIn
+ m := maximumIncFailNoIn
if exclusive {
- m = maxExcFailNoIn
+ m = maximumExcFailNoIn
}
- message = fmt.Sprintf(m, name, max)
+ message = fmt.Sprintf(m, name, maximum)
} else {
- m := maxIncFail
+ m := maximumIncFail
if exclusive {
- m = maxExcFail
+ m = maximumExcFail
}
- message = fmt.Sprintf(m, name, in, max)
+ message = fmt.Sprintf(m, name, in, maximum)
}
return &Validation{
code: MaxFailCode,
@@ -353,21 +365,21 @@ func ExceedsMaximumInt(name, in string, max int64, exclusive bool, value interfa
}
}
-// ExceedsMaximumUint error for when maximum validation fails
-func ExceedsMaximumUint(name, in string, max uint64, exclusive bool, value interface{}) *Validation {
+// ExceedsMaximumUint error for when maximum validation fails.
+func ExceedsMaximumUint(name, in string, maximum uint64, exclusive bool, value any) *Validation {
var message string
if in == "" {
- m := maxIncFailNoIn
+ m := maximumIncFailNoIn
if exclusive {
- m = maxExcFailNoIn
+ m = maximumExcFailNoIn
}
- message = fmt.Sprintf(m, name, max)
+ message = fmt.Sprintf(m, name, maximum)
} else {
- m := maxIncFail
+ m := maximumIncFail
if exclusive {
- m = maxExcFail
+ m = maximumExcFail
}
- message = fmt.Sprintf(m, name, in, max)
+ message = fmt.Sprintf(m, name, in, maximum)
}
return &Validation{
code: MaxFailCode,
@@ -378,21 +390,21 @@ func ExceedsMaximumUint(name, in string, max uint64, exclusive bool, value inter
}
}
-// ExceedsMaximum error for when maximum validation fails
-func ExceedsMaximum(name, in string, max float64, exclusive bool, value interface{}) *Validation {
+// ExceedsMaximum error for when maximum validation fails.
+func ExceedsMaximum(name, in string, maximum float64, exclusive bool, value any) *Validation {
var message string
if in == "" {
- m := maxIncFailNoIn
+ m := maximumIncFailNoIn
if exclusive {
- m = maxExcFailNoIn
+ m = maximumExcFailNoIn
}
- message = fmt.Sprintf(m, name, max)
+ message = fmt.Sprintf(m, name, maximum)
} else {
- m := maxIncFail
+ m := maximumIncFail
if exclusive {
- m = maxExcFail
+ m = maximumExcFail
}
- message = fmt.Sprintf(m, name, in, max)
+ message = fmt.Sprintf(m, name, in, maximum)
}
return &Validation{
code: MaxFailCode,
@@ -403,21 +415,21 @@ func ExceedsMaximum(name, in string, max float64, exclusive bool, value interfac
}
}
-// ExceedsMinimumInt error for when minimum validation fails
-func ExceedsMinimumInt(name, in string, min int64, exclusive bool, value interface{}) *Validation {
+// ExceedsMinimumInt error for when minimum validation fails.
+func ExceedsMinimumInt(name, in string, minimum int64, exclusive bool, value any) *Validation {
var message string
if in == "" {
m := minIncFailNoIn
if exclusive {
m = minExcFailNoIn
}
- message = fmt.Sprintf(m, name, min)
+ message = fmt.Sprintf(m, name, minimum)
} else {
m := minIncFail
if exclusive {
m = minExcFail
}
- message = fmt.Sprintf(m, name, in, min)
+ message = fmt.Sprintf(m, name, in, minimum)
}
return &Validation{
code: MinFailCode,
@@ -428,21 +440,21 @@ func ExceedsMinimumInt(name, in string, min int64, exclusive bool, value interfa
}
}
-// ExceedsMinimumUint error for when minimum validation fails
-func ExceedsMinimumUint(name, in string, min uint64, exclusive bool, value interface{}) *Validation {
+// ExceedsMinimumUint error for when minimum validation fails.
+func ExceedsMinimumUint(name, in string, minimum uint64, exclusive bool, value any) *Validation {
var message string
if in == "" {
m := minIncFailNoIn
if exclusive {
m = minExcFailNoIn
}
- message = fmt.Sprintf(m, name, min)
+ message = fmt.Sprintf(m, name, minimum)
} else {
m := minIncFail
if exclusive {
m = minExcFail
}
- message = fmt.Sprintf(m, name, in, min)
+ message = fmt.Sprintf(m, name, in, minimum)
}
return &Validation{
code: MinFailCode,
@@ -453,21 +465,21 @@ func ExceedsMinimumUint(name, in string, min uint64, exclusive bool, value inter
}
}
-// ExceedsMinimum error for when minimum validation fails
-func ExceedsMinimum(name, in string, min float64, exclusive bool, value interface{}) *Validation {
+// ExceedsMinimum error for when minimum validation fails.
+func ExceedsMinimum(name, in string, minimum float64, exclusive bool, value any) *Validation {
var message string
if in == "" {
m := minIncFailNoIn
if exclusive {
m = minExcFailNoIn
}
- message = fmt.Sprintf(m, name, min)
+ message = fmt.Sprintf(m, name, minimum)
} else {
m := minIncFail
if exclusive {
m = minExcFail
}
- message = fmt.Sprintf(m, name, in, min)
+ message = fmt.Sprintf(m, name, in, minimum)
}
return &Validation{
code: MinFailCode,
@@ -478,8 +490,8 @@ func ExceedsMinimum(name, in string, min float64, exclusive bool, value interfac
}
}
-// NotMultipleOf error for when multiple of validation fails
-func NotMultipleOf(name, in string, multiple, value interface{}) *Validation {
+// NotMultipleOf error for when multiple of validation fails.
+func NotMultipleOf(name, in string, multiple, value any) *Validation {
var msg string
if in == "" {
msg = fmt.Sprintf(multipleOfFailNoIn, name, multiple)
@@ -495,8 +507,8 @@ func NotMultipleOf(name, in string, multiple, value interface{}) *Validation {
}
}
-// EnumFail error for when an enum validation fails
-func EnumFail(name, in string, value interface{}, values []interface{}) *Validation {
+// EnumFail error for when an enum validation fails.
+func EnumFail(name, in string, value any, values []any) *Validation {
var msg string
if in == "" {
msg = fmt.Sprintf(enumFailNoIn, name, values)
@@ -514,8 +526,8 @@ func EnumFail(name, in string, value interface{}, values []interface{}) *Validat
}
}
-// Required error for when a value is missing
-func Required(name, in string, value interface{}) *Validation {
+// Required error for when a value is missing.
+func Required(name, in string, value any) *Validation {
var msg string
if in == "" {
msg = fmt.Sprintf(requiredFailNoIn, name)
@@ -531,8 +543,8 @@ func Required(name, in string, value interface{}) *Validation {
}
}
-// ReadOnly error for when a value is present in request
-func ReadOnly(name, in string, value interface{}) *Validation {
+// ReadOnly error for when a value is present in request.
+func ReadOnly(name, in string, value any) *Validation {
var msg string
if in == "" {
msg = fmt.Sprintf(readOnlyFailNoIn, name)
@@ -548,13 +560,13 @@ func ReadOnly(name, in string, value interface{}) *Validation {
}
}
-// TooLong error for when a string is too long
-func TooLong(name, in string, max int64, value interface{}) *Validation {
+// TooLong error for when a string is too long.
+func TooLong(name, in string, maximum int64, value any) *Validation {
var msg string
if in == "" {
- msg = fmt.Sprintf(tooLongMessageNoIn, name, max)
+ msg = fmt.Sprintf(tooLongMessageNoIn, name, maximum)
} else {
- msg = fmt.Sprintf(tooLongMessage, name, in, max)
+ msg = fmt.Sprintf(tooLongMessage, name, in, maximum)
}
return &Validation{
code: TooLongFailCode,
@@ -565,13 +577,13 @@ func TooLong(name, in string, max int64, value interface{}) *Validation {
}
}
-// TooShort error for when a string is too short
-func TooShort(name, in string, min int64, value interface{}) *Validation {
+// TooShort error for when a string is too short.
+func TooShort(name, in string, minimum int64, value any) *Validation {
var msg string
if in == "" {
- msg = fmt.Sprintf(tooShortMessageNoIn, name, min)
+ msg = fmt.Sprintf(tooShortMessageNoIn, name, minimum)
} else {
- msg = fmt.Sprintf(tooShortMessage, name, in, min)
+ msg = fmt.Sprintf(tooShortMessage, name, in, minimum)
}
return &Validation{
@@ -585,7 +597,7 @@ func TooShort(name, in string, min int64, value interface{}) *Validation {
// FailedPattern error for when a string fails a regex pattern match
// the pattern that is returned is the ECMA syntax version of the pattern not the golang version.
-func FailedPattern(name, in, pattern string, value interface{}) *Validation {
+func FailedPattern(name, in, pattern string, value any) *Validation {
var msg string
if in == "" {
msg = fmt.Sprintf(patternFailNoIn, name, pattern)
@@ -603,8 +615,8 @@ func FailedPattern(name, in, pattern string, value interface{}) *Validation {
}
// MultipleOfMustBePositive error for when a
-// multipleOf factor is negative
-func MultipleOfMustBePositive(name, in string, factor interface{}) *Validation {
+// multipleOf factor is negative.
+func MultipleOfMustBePositive(name, in string, factor any) *Validation {
return &Validation{
code: MultipleOfMustBePositiveCode,
Name: name,
diff --git a/test/tools/vendor/github.com/go-openapi/inflect/.cliff.toml b/test/tools/vendor/github.com/go-openapi/inflect/.cliff.toml
new file mode 100644
index 0000000000..702629f5dc
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/inflect/.cliff.toml
@@ -0,0 +1,181 @@
+# 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/test/tools/vendor/github.com/go-openapi/inflect/.editorconfig b/test/tools/vendor/github.com/go-openapi/inflect/.editorconfig
new file mode 100644
index 0000000000..3152da69a5
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/inflect/.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/test/tools/vendor/github.com/go-openapi/inflect/.golangci.yml b/test/tools/vendor/github.com/go-openapi/inflect/.golangci.yml
index 22f8d21cca..fdae591bce 100644
--- a/test/tools/vendor/github.com/go-openapi/inflect/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/inflect/.golangci.yml
@@ -1,61 +1,66 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
+ - depguard
- funlen
- godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- exhaustruct
- - varnamelen
- - gci
- - depguard
- - errchkjson
- - inamedparam
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 20
+ gocyclo:
+ min-complexity: 20
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/inflect/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/inflect/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000..9322b065e3
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/inflect/CODE_OF_CONDUCT.md
@@ -0,0 +1,74 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, gender identity and expression, level of experience,
+nationality, personal appearance, race, religion, or sexual identity and
+orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+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
+ address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+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
+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.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+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]
+
+[homepage]: http://contributor-covenant.org
+[version]: http://contributor-covenant.org/version/1/4/
diff --git a/test/tools/vendor/github.com/go-openapi/inflect/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/inflect/CONTRIBUTORS.md
new file mode 100644
index 0000000000..f98e73b016
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/inflect/CONTRIBUTORS.md
@@ -0,0 +1,17 @@
+# Contributors
+
+- Repository: ['go-openapi/inflect']
+
+| Total Contributors | Total Contributions |
+| --- | --- |
+| 5 | 42 |
+
+| Username | All Time Contribution Count | All Commits |
+| --- | --- | --- |
+| @fredbi | 21 | https://github.com/go-openapi/inflect/commits?author=fredbi |
+| @chrisfarms | 15 | https://github.com/go-openapi/inflect/commits?author=chrisfarms |
+| @hirochachacha | 4 | https://github.com/go-openapi/inflect/commits?author=hirochachacha |
+| @casualjim | 1 | https://github.com/go-openapi/inflect/commits?author=casualjim |
+| @roktas | 1 | https://github.com/go-openapi/inflect/commits?author=roktas |
+
+ _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_
diff --git a/test/tools/vendor/github.com/go-openapi/inflect/LICENSE b/test/tools/vendor/github.com/go-openapi/inflect/LICENSE
index 8a36b944a5..261eeb9e9f 100644
--- a/test/tools/vendor/github.com/go-openapi/inflect/LICENSE
+++ b/test/tools/vendor/github.com/go-openapi/inflect/LICENSE
@@ -1,7 +1,201 @@
-Copyright (c) 2011 Chris Farmiloe
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
-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:
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ 1. Definitions.
-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.
+ "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/test/tools/vendor/github.com/mailru/easyjson/LICENSE b/test/tools/vendor/github.com/go-openapi/inflect/NOTICE
similarity index 52%
rename from test/tools/vendor/github.com/mailru/easyjson/LICENSE
rename to test/tools/vendor/github.com/go-openapi/inflect/NOTICE
index fbff658f70..7609638b9c 100644
--- a/test/tools/vendor/github.com/mailru/easyjson/LICENSE
+++ b/test/tools/vendor/github.com/go-openapi/inflect/NOTICE
@@ -1,4 +1,27 @@
-Copyright (c) 2016 Mail.Ru Group
+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 by Chris Farmiloe at https://bitbucket.org/pkg/inflect under a MIT License.
+
+ghttps://bitbucket.org/pkg/inflect
+===========================
+
+Copyright (c) 2011 Chris Farmiloe
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:
diff --git a/test/tools/vendor/github.com/go-openapi/inflect/README.md b/test/tools/vendor/github.com/go-openapi/inflect/README.md
index 187b23b93f..64c7482ebb 100644
--- a/test/tools/vendor/github.com/go-openapi/inflect/README.md
+++ b/test/tools/vendor/github.com/go-openapi/inflect/README.md
@@ -1,13 +1,37 @@
-# inflect [](https://github.com/go-openapi/inflect/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/inflect)
+# inflect
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/inflect/master/LICENSE)
-[](https://pkg.go.dev/github.com/go-openapi/inflect)
-[](https://goreportcard.com/report/github.com/go-openapi/inflect)
+
+[![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] [![Slack Channel][slack-logo]![slack-badge]][slack-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge]
+
+---
A package to pluralize words.
-Originally forked from fork of https://bitbucket.org/pkg/inflect under a MIT License.
+Originally forked from https://bitbucket.org/pkg/inflect under a MIT License.
+
+## Status
+
+API is stable.
+
+This library is not used at all by other go-openapi packages and is somewhat redundant with
+go-openapi/swag/mangling (for camelcase etc).
+
+Currently we have one single dependency in one place in a go-swagger template (used as a funcmap).
+
+## Import this library in your project
+
+```cmd
+go get github.com/go-openapi/inflect
+```
+
+## Basic usage
A golang library applying grammar rules to English words.
@@ -16,3 +40,76 @@ A golang library applying grammar rules to English words.
> (Capitalize, camelCase, snake_case, etc.).
>
> Acronyms are properly handled. A common use case is word pluralization.
+
+## Change log
+
+See
+
+
+
+## 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
+
+* [All-time contributors](./CONTRIBUTORS.md)
+* [Contributing guidelines](.github/CONTRIBUTING.md)
+
+
+## Cutting a new release
+
+Maintainers can cut a new release by either:
+
+* running [this workflow](https://github.com/go-openapi/inflect/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/inflect/actions/workflows/go-test.yml/badge.svg
+[test-url]: https://github.com/go-openapi/inflect/actions/workflows/go-test.yml
+[cov-badge]: https://codecov.io/gh/go-openapi/inflect/branch/master/graph/badge.svg
+[cov-url]: https://codecov.io/gh/go-openapi/inflect
+[vuln-scan-badge]: https://github.com/go-openapi/inflect/actions/workflows/scanner.yml/badge.svg
+[vuln-scan-url]: https://github.com/go-openapi/inflect/actions/workflows/scanner.yml
+[codeql-badge]: https://github.com/go-openapi/inflect/actions/workflows/codeql.yml/badge.svg
+[codeql-url]: https://github.com/go-openapi/inflect/actions/workflows/codeql.yml
+
+[release-badge]: https://badge.fury.io/gh/go-openapi%2Finflect.svg
+[release-url]: https://badge.fury.io/gh/go-openapi%2Finflect
+[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Finflect.svg
+[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Finflect
+
+[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/inflect
+[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/inflect
+[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/inflect
+[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/inflect
+
+[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/inflect
+[godoc-url]: http://pkg.go.dev/github.com/go-openapi/inflect
+[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
+
+[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg
+[license-url]: https://github.com/go-openapi/inflect/?tab=Apache-2.0-1-ov-file#readme
+
+[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/inflect
+[goversion-url]: https://github.com/go-openapi/inflect/blob/master/go.mod
+[top-badge]: https://img.shields.io/github/languages/top/go-openapi/inflect
+[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/inflect/latest
diff --git a/test/tools/vendor/github.com/go-openapi/inflect/SECURITY.md b/test/tools/vendor/github.com/go-openapi/inflect/SECURITY.md
new file mode 100644
index 0000000000..2a7b6f0910
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/inflect/SECURITY.md
@@ -0,0 +1,19 @@
+# Security Policy
+
+This policy outlines the commitment and practices of the go-openapi maintainers regarding security.
+
+## Supported Versions
+
+| Version | Supported |
+| ------- | ------------------ |
+| 0.22.x | :white_check_mark: |
+
+## Reporting a vulnerability
+
+If you become aware of a security vulnerability that affects the current repository,
+please report it privately to the maintainers.
+
+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).
+
+TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability".
diff --git a/test/tools/vendor/github.com/go-openapi/inflect/inflect.go b/test/tools/vendor/github.com/go-openapi/inflect/inflect.go
index 9d8ca6dbd4..54cccbd9bf 100644
--- a/test/tools/vendor/github.com/go-openapi/inflect/inflect.go
+++ b/test/tools/vendor/github.com/go-openapi/inflect/inflect.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package inflect
import (
@@ -9,15 +12,15 @@ import (
"unicode/utf8"
)
-// used by rulesets
+// Rule is used by rulesets.
type Rule struct {
suffix string
replacement string
exact bool
}
-// a Ruleset is the config of pluralization rules
-// you can extend the rules with the Add* methods
+// Ruleset is the config of pluralization rules
+// you can extend the rules with the Add* methods.
type Ruleset struct {
uncountables map[string]bool
plurals []*Rule
@@ -26,10 +29,10 @@ type Ruleset struct {
acronyms []*Rule
}
-// create a blank ruleset. Unless you are going to
+// NewRuleset creates a blank ruleset. Unless you are going to
// build your own rules from scratch you probably
// won't need this and can just use the defaultRuleset
-// via the global inflect.* methods
+// via the global inflect.* methods.
func NewRuleset() *Ruleset {
rs := new(Ruleset)
rs.uncountables = make(map[string]bool)
@@ -40,8 +43,8 @@ func NewRuleset() *Ruleset {
return rs
}
-// create a new ruleset and load it with the default
-// set of common English pluralization rules
+// NewDefaultRuleset create a new ruleset and load it with the default
+// set of common English pluralization rules.
func NewDefaultRuleset() *Ruleset {
rs := NewRuleset()
rs.AddPlural("s", "s")
@@ -236,12 +239,12 @@ func (rs *Ruleset) Uncountables() map[string]bool {
return rs.uncountables
}
-// add a pluralization rule
+// AddPlural adds a pluralization rule.
func (rs *Ruleset) AddPlural(suffix, replacement string) {
rs.AddPluralExact(suffix, replacement, false)
}
-// add a pluralization rule with full string match
+// AddPluralExact adds a pluralization rule with full string match.
func (rs *Ruleset) AddPluralExact(suffix, replacement string, exact bool) {
// remove uncountable
delete(rs.uncountables, suffix)
@@ -254,13 +257,13 @@ func (rs *Ruleset) AddPluralExact(suffix, replacement string, exact bool) {
rs.plurals = append([]*Rule{r}, rs.plurals...)
}
-// add a singular rule
+// AddSingular add a singular rule.
func (rs *Ruleset) AddSingular(suffix, replacement string) {
rs.AddSingularExact(suffix, replacement, false)
}
-// same as AddSingular but you can set `exact` to force
-// a full string match
+// AddSingularExact same as AddSingular but you can set `exact` to force
+// a full string match.
func (rs *Ruleset) AddSingularExact(suffix, replacement string, exact bool) {
// remove from uncountable
delete(rs.uncountables, suffix)
@@ -272,8 +275,8 @@ func (rs *Ruleset) AddSingularExact(suffix, replacement string, exact bool) {
rs.singulars = append([]*Rule{r}, rs.singulars...)
}
-// Human rules are applied by humanize to show more friendly
-// versions of words
+// AddHuman rules are applied by humanize to show more friendly
+// versions of words.
func (rs *Ruleset) AddHuman(suffix, replacement string) {
r := new(Rule)
r.suffix = suffix
@@ -281,7 +284,7 @@ func (rs *Ruleset) AddHuman(suffix, replacement string) {
rs.humans = append([]*Rule{r}, rs.humans...)
}
-// Add any inconsistent pluralizing/sinularizing rules
+// AddIrregular adds any inconsistent pluralizing/singularizing rules
// to the set here.
func (rs *Ruleset) AddIrregular(singular, plural string) {
delete(rs.uncountables, singular)
@@ -291,9 +294,9 @@ func (rs *Ruleset) AddIrregular(singular, plural string) {
rs.AddSingular(plural, singular)
}
-// if you use acronym you may need to add them to the ruleset
+// AddAcronym is used if you use acronym you may need to add them to the ruleset
// to prevent Underscored words of things like "HTML" coming out
-// as "h_t_m_l"
+// as "h_t_m_l".
func (rs *Ruleset) AddAcronym(word string) {
r := new(Rule)
r.suffix = word
@@ -301,22 +304,13 @@ func (rs *Ruleset) AddAcronym(word string) {
rs.acronyms = append(rs.acronyms, r)
}
-// add a word to this ruleset that has the same singular and plural form
-// for example: "rice"
+// AddUncountable adds a word to this ruleset that has the same singular and plural form
+// for example: "rice".
func (rs *Ruleset) AddUncountable(word string) {
rs.uncountables[strings.ToLower(word)] = true
}
-func (rs *Ruleset) isUncountable(word string) bool {
- // handle multiple words by using the last one
- words := strings.Split(word, " ")
- if _, exists := rs.uncountables[strings.ToLower(words[len(words)-1])]; exists {
- return true
- }
- return false
-}
-
-// returns the plural form of a singular word
+// Pluralize returns the plural form of a singular word.
func (rs *Ruleset) Pluralize(word string) string {
if len(word) == 0 {
return word
@@ -338,7 +332,7 @@ func (rs *Ruleset) Pluralize(word string) string {
return word + "s"
}
-// returns the singular form of a plural word
+// Singularize returns the singular form of a plural word.
func (rs *Ruleset) Singularize(word string) string {
if len(word) == 0 {
return word
@@ -360,29 +354,139 @@ func (rs *Ruleset) Singularize(word string) string {
return word
}
-// uppercase first character
+// Capitalize uppercase first character.
func (rs *Ruleset) Capitalize(word string) string {
return strings.ToUpper(word[:1]) + word[1:]
}
-// "dino_party" -> "DinoParty"
+// Camelize makes a word camel-case: "dino_party" -> "DinoParty".
func (rs *Ruleset) Camelize(word string) string {
words := splitAtCaseChangeWithTitlecase(word)
return strings.Join(words, "")
}
-// same as Camelcase but with first letter downcased
+// CamelizeDownFirst is the same as Camelcase but with first letter downcased.
func (rs *Ruleset) CamelizeDownFirst(word string) string {
word = Camelize(word)
return strings.ToLower(word[:1]) + word[1:]
}
-// Captitilize every word in sentance "hello there" -> "Hello There"
+// Titleize capitalizes every word in sentence: "hello there" -> "Hello There".
func (rs *Ruleset) Titleize(word string) string {
words := splitAtCaseChangeWithTitlecase(word)
return strings.Join(words, " ")
}
+// Underscore makes a lowercase underscore version: "BigBen" -> "big_ben".
+func (rs *Ruleset) Underscore(word string) string {
+ return rs.seperatedWords(word, "_")
+}
+
+// Humanize makes the first letter of a sentence capitalized.
+//
+// Uses custom friendly replacements via AddHuman().
+func (rs *Ruleset) Humanize(word string) string {
+ word = replaceLast(word, "_id", "") // strip foreign key kinds
+ // replace and strings in humans list
+ for _, rule := range rs.humans {
+ word = strings.ReplaceAll(word, rule.suffix, rule.replacement)
+ }
+ sentance := rs.seperatedWords(word, " ")
+ return strings.ToUpper(sentance[:1]) + sentance[1:]
+}
+
+// ForeignKey makes an underscored foreign key name: "Person" -> "person_id".
+func (rs *Ruleset) ForeignKey(word string) string {
+ return rs.Underscore(rs.Singularize(word)) + "_id"
+}
+
+// ForeignKeyCondensed makes a foreign key (without an underscore) "Person" -> "personid".
+func (rs *Ruleset) ForeignKeyCondensed(word string) string {
+ return rs.Underscore(word) + "id"
+}
+
+// Tableize makes a rails style pluralized table name: "SuperPerson" -> "super_people".
+func (rs *Ruleset) Tableize(word string) string {
+ return rs.Pluralize(rs.Underscore(rs.Typeify(word)))
+}
+
+var notURLSafe = regexp.MustCompile(`[^\w\d\-_ ]`)
+
+// Parameterize makes param safe dasherized names like "my-param".
+func (rs *Ruleset) Parameterize(word string) string {
+ return ParameterizeJoin(word, "-")
+}
+
+// ParameterizeJoin makes param safe dasherized names with custom separator.
+func (rs *Ruleset) ParameterizeJoin(word, sep string) string {
+ word = strings.ToLower(word)
+ word = rs.Asciify(word)
+ word = notURLSafe.ReplaceAllString(word, "")
+ word = strings.ReplaceAll(word, " ", sep)
+ if len(sep) > 0 {
+ squash, err := regexp.Compile(sep + "+")
+ if err == nil {
+ word = squash.ReplaceAllString(word, sep)
+ }
+ }
+ word = strings.Trim(word, sep+" ")
+ return word
+}
+
+// Asciify transforms latin characters like é -> e.
+func (rs *Ruleset) Asciify(word string) string {
+ for repl, regex := range lookalikes {
+ word = regex.ReplaceAllString(word, repl)
+ }
+ return word
+}
+
+var tablePrefix = regexp.MustCompile(`^[^.]*\.`)
+
+// Typeify makes "something_like_this" -> "SomethingLikeThis".
+func (rs *Ruleset) Typeify(word string) string {
+ word = tablePrefix.ReplaceAllString(word, "")
+ return rs.Camelize(rs.Singularize(word))
+}
+
+// Dasherize uses dashes: "SomeText" -> "some-text".
+func (rs *Ruleset) Dasherize(word string) string {
+ return rs.seperatedWords(word, "-")
+}
+
+// Ordinalize returns an ordinal: "1031" -> "1031st"
+//
+//nolint:mnd
+func (rs *Ruleset) Ordinalize(str string) string {
+ number, err := strconv.Atoi(str)
+ if err != nil {
+ return str
+ }
+ switch abs(number) % 100 {
+ case 11, 12, 13:
+ return fmt.Sprintf("%dth", number)
+ default:
+ switch abs(number) % 10 {
+ case 1:
+ return fmt.Sprintf("%dst", number)
+ case 2:
+ return fmt.Sprintf("%dnd", number)
+ case 3:
+ return fmt.Sprintf("%drd", number)
+ }
+ }
+ return fmt.Sprintf("%dth", number)
+}
+
+func (rs *Ruleset) isUncountable(word string) bool {
+ // handle multiple words by using the last one
+ words := strings.Split(word, " ")
+ if _, exists := rs.uncountables[strings.ToLower(words[len(words)-1])]; exists {
+ return true
+ }
+ return false
+}
+
func (rs *Ruleset) safeCaseAcronyms(word string) string {
// convert an acroymn like HTML into Html
for _, rule := range rs.acronyms {
@@ -397,61 +501,6 @@ func (rs *Ruleset) seperatedWords(word, sep string) string {
return strings.Join(words, sep)
}
-// lowercase underscore version "BigBen" -> "big_ben"
-func (rs *Ruleset) Underscore(word string) string {
- return rs.seperatedWords(word, "_")
-}
-
-// First letter of sentance captitilized
-// Uses custom friendly replacements via AddHuman()
-func (rs *Ruleset) Humanize(word string) string {
- word = replaceLast(word, "_id", "") // strip foreign key kinds
- // replace and strings in humans list
- for _, rule := range rs.humans {
- word = strings.ReplaceAll(word, rule.suffix, rule.replacement)
- }
- sentance := rs.seperatedWords(word, " ")
- return strings.ToUpper(sentance[:1]) + sentance[1:]
-}
-
-// an underscored foreign key name "Person" -> "person_id"
-func (rs *Ruleset) ForeignKey(word string) string {
- return rs.Underscore(rs.Singularize(word)) + "_id"
-}
-
-// a foreign key (with an underscore) "Person" -> "personid"
-func (rs *Ruleset) ForeignKeyCondensed(word string) string {
- return rs.Underscore(word) + "id"
-}
-
-// Rails style pluralized table names: "SuperPerson" -> "super_people"
-func (rs *Ruleset) Tableize(word string) string {
- return rs.Pluralize(rs.Underscore(rs.Typeify(word)))
-}
-
-var notURLSafe = regexp.MustCompile(`[^\w\d\-_ ]`)
-
-// param safe dasherized names like "my-param"
-func (rs *Ruleset) Parameterize(word string) string {
- return ParameterizeJoin(word, "-")
-}
-
-// param safe dasherized names with custom separator
-func (rs *Ruleset) ParameterizeJoin(word, sep string) string {
- word = strings.ToLower(word)
- word = rs.Asciify(word)
- word = notURLSafe.ReplaceAllString(word, "")
- word = strings.ReplaceAll(word, " ", sep)
- if len(sep) > 0 {
- squash, err := regexp.Compile(sep + "+")
- if err == nil {
- word = squash.ReplaceAllString(word, sep)
- }
- }
- word = strings.Trim(word, sep+" ")
- return word
-}
-
var lookalikes = map[string]*regexp.Regexp{
"A": regexp.MustCompile(`À|Á|Â|Ã|Ä|Å`),
"AE": regexp.MustCompile(`Æ`),
@@ -478,49 +527,6 @@ var lookalikes = map[string]*regexp.Regexp{
"y": regexp.MustCompile(`ý|ÿ`),
}
-// transforms latin characters like é -> e
-func (rs *Ruleset) Asciify(word string) string {
- for repl, regex := range lookalikes {
- word = regex.ReplaceAllString(word, repl)
- }
- return word
-}
-
-var tablePrefix = regexp.MustCompile(`^[^.]*\.`)
-
-// "something_like_this" -> "SomethingLikeThis"
-func (rs *Ruleset) Typeify(word string) string {
- word = tablePrefix.ReplaceAllString(word, "")
- return rs.Camelize(rs.Singularize(word))
-}
-
-// "SomeText" -> "some-text"
-func (rs *Ruleset) Dasherize(word string) string {
- return rs.seperatedWords(word, "-")
-}
-
-// "1031" -> "1031st"
-func (rs *Ruleset) Ordinalize(str string) string {
- number, err := strconv.Atoi(str)
- if err != nil {
- return str
- }
- switch abs(number) % 100 {
- case 11, 12, 13:
- return fmt.Sprintf("%dth", number)
- default:
- switch abs(number) % 10 {
- case 1:
- return fmt.Sprintf("%dst", number)
- case 2:
- return fmt.Sprintf("%dnd", number)
- case 3:
- return fmt.Sprintf("%drd", number)
- }
- }
- return fmt.Sprintf("%dth", number)
-}
-
/////////////////////////////////////////
// the default global ruleset
//////////////////////////////////////////
diff --git a/test/tools/vendor/github.com/go-openapi/jsonpointer/.cliff.toml b/test/tools/vendor/github.com/go-openapi/jsonpointer/.cliff.toml
new file mode 100644
index 0000000000..702629f5dc
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/.cliff.toml
@@ -0,0 +1,181 @@
+# 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/test/tools/vendor/github.com/go-openapi/jsonpointer/.gitignore b/test/tools/vendor/github.com/go-openapi/jsonpointer/.gitignore
index 769c244007..885dc27ab0 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonpointer/.gitignore
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/.gitignore
@@ -1 +1,6 @@
-secrets.yml
+*.out
+*.cov
+.idea
+.env
+.mcp.json
+.claude/
diff --git a/test/tools/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/test/tools/vendor/github.com/go-openapi/jsonpointer/.golangci.yml
index 22f8d21cca..dc7c96053d 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonpointer/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/.golangci.yml
@@ -1,61 +1,67 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
+ - depguard
- funlen
- godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- exhaustruct
- - varnamelen
- - gci
- - depguard
- - errchkjson
- - inamedparam
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 20
+ gocyclo:
+ min-complexity: 20
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md
new file mode 100644
index 0000000000..2ebebedc15
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md
@@ -0,0 +1,24 @@
+# Contributors
+
+- Repository: ['go-openapi/jsonpointer']
+
+| Total Contributors | Total Contributions |
+| --- | --- |
+| 12 | 101 |
+
+| Username | All Time Contribution Count | All Commits |
+| --- | --- | --- |
+| @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/test/tools/vendor/github.com/go-openapi/jsonpointer/LICENSE b/test/tools/vendor/github.com/go-openapi/jsonpointer/LICENSE
index d645695673..261eeb9e9f 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonpointer/LICENSE
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/LICENSE
@@ -1,4 +1,3 @@
-
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
diff --git a/test/tools/vendor/github.com/go-openapi/jsonpointer/NOTICE b/test/tools/vendor/github.com/go-openapi/jsonpointer/NOTICE
new file mode 100644
index 0000000000..f3b51939a9
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/NOTICE
@@ -0,0 +1,39 @@
+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 on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com).
+
+github.com/sigh-399/jsonpointer
+===========================
+
+// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
+// SPDX-License-Identifier: Apache-2.0
+
+Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
+
+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/test/tools/vendor/github.com/go-openapi/jsonpointer/README.md b/test/tools/vendor/github.com/go-openapi/jsonpointer/README.md
index 0108f1d572..c52803e2e8 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonpointer/README.md
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/README.md
@@ -1,19 +1,158 @@
-# gojsonpointer [](https://github.com/go-openapi/jsonpointer/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/jsonpointer)
+# jsonpointer
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE)
-[](https://pkg.go.dev/github.com/go-openapi/jsonpointer)
-[](https://goreportcard.com/report/github.com/go-openapi/jsonpointer)
+
+[![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]
-An implementation of JSON Pointer - Go language
+---
+
+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
-Completed YES
-Tested YES
+API is stable.
+
+## Import this library in your project
+
+```cmd
+go get github.com/go-openapi/jsonpointer
+```
+
+## Basic usage
+
+See also some [examples](./examples_test.go)
+
+### Retrieving a value
+
+```go
+ import (
+ "github.com/go-openapi/jsonpointer"
+ )
+
+
+ var doc any
+
+ ...
+
+ pointer, err := jsonpointer.New("/foo/1")
+ if err != nil {
+ ... // error: e.g. invalid JSON pointer specification
+ }
+
+ value, kind, err := pointer.Get(doc)
+ if err != nil {
+ ... // error: e.g. key not found, index out of bounds, etc.
+ }
+
+ ...
+```
+
+### Setting a value
+
+```go
+ ...
+ var doc any
+ ...
+ pointer, err := jsonpointer.New("/foo/1")
+ if err != nil {
+ ... // error: e.g. invalid JSON pointer specification
+ }
+
+ doc, err = p.Set(doc, "value")
+ if err != nil {
+ ... // error: e.g. key not found, index out of bounds, etc.
+ }
+```
+
+## Change log
+
+See
## References
-http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07
-### Note
-The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented.
+
+
+also known as [RFC6901](https://www.rfc-editor.org/rfc/rfc6901)
+
+## 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.
+
+## Limitations
+
+The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array,
+the reference token MUST contain either...' is not implemented.
+
+That is because our implementation of the JSON pointer only supports explicit references to array elements:
+the provision in the spec to resolve non-existent members as "the last element in the array",
+using the special trailing character "-" is not implemented.
+
+## 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/jsonpointer/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/jsonpointer/actions/workflows/go-test.yml/badge.svg
+[test-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml
+[cov-badge]: https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg
+[cov-url]: https://codecov.io/gh/go-openapi/jsonpointer
+[vuln-scan-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml/badge.svg
+[vuln-scan-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml
+[codeql-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml/badge.svg
+[codeql-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml
+
+[release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer.svg
+[release-url]: https://badge.fury.io/gh/go-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
+
+[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
+
+[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/jsonpointer
+[goversion-url]: https://github.com/go-openapi/jsonpointer/blob/master/go.mod
+[top-badge]: https://img.shields.io/github/languages/top/go-openapi/jsonpointer
+[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/jsonpointer/latest
diff --git a/test/tools/vendor/github.com/go-openapi/jsonpointer/SECURITY.md b/test/tools/vendor/github.com/go-openapi/jsonpointer/SECURITY.md
new file mode 100644
index 0000000000..1fea2c5736
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/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/test/tools/vendor/github.com/go-openapi/jsonpointer/errors.go b/test/tools/vendor/github.com/go-openapi/jsonpointer/errors.go
new file mode 100644
index 0000000000..8c50dde8bc
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/errors.go
@@ -0,0 +1,35 @@
+// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
+package jsonpointer
+
+import "fmt"
+
+type pointerError string
+
+func (e pointerError) Error() string {
+ return string(e)
+}
+
+const (
+ // ErrPointer is a sentinel error raised by all errors from this package.
+ ErrPointer pointerError = "JSON pointer error"
+
+ // ErrInvalidStart states that a JSON pointer must start with a separator ("/").
+ ErrInvalidStart pointerError = `JSON pointer must be empty or start with a "` + pointerSeparator
+
+ // ErrUnsupportedValueType indicates that a value of the wrong type is being set.
+ ErrUnsupportedValueType pointerError = "only structs, pointers, maps and slices are supported for setting values"
+)
+
+func errNoKey(key string) error {
+ return fmt.Errorf("object has no key %q: %w", key, ErrPointer)
+}
+
+func errOutOfBounds(length, idx int) error {
+ return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", length-1, idx, ErrPointer)
+}
+
+func errInvalidReference(token string) error {
+ return fmt.Errorf("invalid token reference %q: %w", token, ErrPointer)
+}
diff --git a/test/tools/vendor/github.com/go-openapi/jsonpointer/pointer.go b/test/tools/vendor/github.com/go-openapi/jsonpointer/pointer.go
index d970c7cf44..7df49af3b9 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonpointer/pointer.go
+++ b/test/tools/vendor/github.com/go-openapi/jsonpointer/pointer.go
@@ -1,28 +1,7 @@
-// Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
-//
-// 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.
-
-// author sigu-399
-// author-github https://github.com/sigu-399
-// author-mail sigu.399@gmail.com
-//
-// repository-name jsonpointer
-// repository-desc An implementation of JSON Pointer - Go language
-//
-// description Main and unique file.
-//
-// created 25-02-2013
+// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+// Package jsonpointer provides a golang implementation for json pointers.
package jsonpointer
import (
@@ -33,353 +12,101 @@ import (
"strconv"
"strings"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonname"
)
const (
emptyPointer = ``
pointerSeparator = `/`
-
- invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator
- notFound = `Can't find the pointer in the document`
)
-var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem()
-var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem()
-
-// JSONPointable is an interface for structs to implement when they need to customize the
-// json pointer process
+// JSONPointable is an interface for structs to implement,
+// when they need to customize the json pointer process or want to avoid the use of reflection.
type JSONPointable interface {
- JSONLookup(string) (any, error)
+ // JSONLookup returns a value pointed at this (unescaped) key.
+ JSONLookup(key string) (any, error)
}
-// JSONSetable is an interface for structs to implement when they need to customize the
-// json pointer process
+// JSONSetable is an interface for structs to implement,
+// when they need to customize the json pointer process or want to avoid the use of reflection.
type JSONSetable interface {
- JSONSet(string, any) error
+ // JSONSet sets the value pointed at the (unescaped) key.
+ JSONSet(key string, value any) error
}
-// New creates a new json pointer for the given string
-func New(jsonPointerString string) (Pointer, error) {
-
- var p Pointer
- err := p.parse(jsonPointerString)
- return p, err
-
-}
-
-// Pointer the json pointer reprsentation
+// Pointer is a representation of a json pointer.
+//
+// Use [Pointer.Get] to retrieve a value or [Pointer.Set] to set a value.
+//
+// It works with any go type interpreted as a JSON document, which means:
+//
+// - if a type implements [JSONPointable], its [JSONPointable.JSONLookup] method is used to resolve [Pointer.Get]
+// - if a type implements [JSONSetable], its [JSONPointable.JSONSet] method is used to resolve [Pointer.Set]
+// - a go map[K]V is interpreted as an object, with type K assignable to a string
+// - a go slice []T is interpreted as an array
+// - a go struct is interpreted as an object, with exported fields interpreted as keys
+// - promoted fields from an embedded struct are traversed
+// - scalars (e.g. int, float64 ...), channels, functions and go arrays cannot be traversed
+//
+// For struct s resolved by reflection, key mappings honor the conventional struct tag `json`.
+//
+// Fields that do not specify a `json` tag, or specify an empty one, or are tagged as `json:"-"` are ignored.
+//
+// # Limitations
+//
+// - Unlike go standard marshaling, untagged fields do not default to the go field name and are ignored.
+// - anonymous fields are not traversed if untagged
type Pointer struct {
referenceTokens []string
}
-// "Constructor", parses the given string JSON pointer
-func (p *Pointer) parse(jsonPointerString string) error {
+// New creates a new json pointer from its string representation.
+func New(jsonPointerString string) (Pointer, error) {
+ var p Pointer
+ err := p.parse(jsonPointerString)
- var err error
-
- if jsonPointerString != emptyPointer {
- if !strings.HasPrefix(jsonPointerString, pointerSeparator) {
- err = errors.New(invalidStart)
- } else {
- referenceTokens := strings.Split(jsonPointerString, pointerSeparator)
- p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...)
- }
- }
-
- return err
+ return p, err
}
-// Get uses the pointer to retrieve a value from a JSON document
+// Get uses the pointer to retrieve a value from a JSON document.
+//
+// It returns the value with its type as a [reflect.Kind] or an error.
func (p *Pointer) Get(document any) (any, reflect.Kind, error) {
- return p.get(document, swag.DefaultJSONNameProvider)
+ return p.get(document, jsonname.DefaultJSONNameProvider)
}
-// Set uses the pointer to set a value from a JSON document
+// Set uses the pointer to set a value from a data type
+// that represent a JSON document.
+//
+// It returns the updated document.
func (p *Pointer) Set(document any, value any) (any, error) {
- return document, p.set(document, value, swag.DefaultJSONNameProvider)
+ return document, p.set(document, value, jsonname.DefaultJSONNameProvider)
}
-// GetForToken gets a value for a json pointer token 1 level deep
-func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) {
- return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider)
-}
-
-// SetForToken gets a value for a json pointer token 1 level deep
-func SetForToken(document any, decodedToken string, value any) (any, error) {
- return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider)
-}
-
-func isNil(input any) bool {
- if input == nil {
- return true
- }
-
- kind := reflect.TypeOf(input).Kind()
- switch kind { //nolint:exhaustive
- case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan:
- return reflect.ValueOf(input).IsNil()
- default:
- return false
- }
-}
-
-func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) {
- rValue := reflect.Indirect(reflect.ValueOf(node))
- kind := rValue.Kind()
- if isNil(node) {
- return nil, kind, fmt.Errorf("nil value has not field %q", decodedToken)
- }
-
- switch typed := node.(type) {
- case JSONPointable:
- r, err := typed.JSONLookup(decodedToken)
- if err != nil {
- return nil, kind, err
- }
- return r, kind, nil
- case *any: // case of a pointer to interface, that is not resolved by reflect.Indirect
- return getSingleImpl(*typed, decodedToken, nameProvider)
- }
-
- switch kind { //nolint:exhaustive
- case reflect.Struct:
- nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
- if !ok {
- return nil, kind, fmt.Errorf("object has no field %q", decodedToken)
- }
- fld := rValue.FieldByName(nm)
- return fld.Interface(), kind, nil
-
- case reflect.Map:
- kv := reflect.ValueOf(decodedToken)
- mv := rValue.MapIndex(kv)
-
- if mv.IsValid() {
- return mv.Interface(), kind, nil
- }
- return nil, kind, fmt.Errorf("object has no key %q", decodedToken)
-
- case reflect.Slice:
- tokenIndex, err := strconv.Atoi(decodedToken)
- if err != nil {
- return nil, kind, err
- }
- sLength := rValue.Len()
- if tokenIndex < 0 || tokenIndex >= sLength {
- return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex)
- }
-
- elem := rValue.Index(tokenIndex)
- return elem.Interface(), kind, nil
-
- default:
- return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken)
- }
-
-}
-
-func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error {
- rValue := reflect.Indirect(reflect.ValueOf(node))
-
- if ns, ok := node.(JSONSetable); ok { // pointer impl
- return ns.JSONSet(decodedToken, data)
- }
-
- if rValue.Type().Implements(jsonSetableType) {
- return node.(JSONSetable).JSONSet(decodedToken, data)
- }
-
- switch rValue.Kind() { //nolint:exhaustive
- case reflect.Struct:
- nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
- if !ok {
- return fmt.Errorf("object has no field %q", decodedToken)
- }
- fld := rValue.FieldByName(nm)
- if fld.IsValid() {
- fld.Set(reflect.ValueOf(data))
- }
- return nil
-
- case reflect.Map:
- kv := reflect.ValueOf(decodedToken)
- rValue.SetMapIndex(kv, reflect.ValueOf(data))
- return nil
-
- case reflect.Slice:
- tokenIndex, err := strconv.Atoi(decodedToken)
- if err != nil {
- return err
- }
- sLength := rValue.Len()
- if tokenIndex < 0 || tokenIndex >= sLength {
- return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex)
- }
-
- elem := rValue.Index(tokenIndex)
- if !elem.CanSet() {
- return fmt.Errorf("can't set slice index %s to %v", decodedToken, data)
- }
- elem.Set(reflect.ValueOf(data))
- return nil
-
- default:
- return fmt.Errorf("invalid token reference %q", decodedToken)
- }
-
-}
-
-func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) {
-
- if nameProvider == nil {
- nameProvider = swag.DefaultJSONNameProvider
- }
-
- kind := reflect.Invalid
-
- // Full document when empty
- if len(p.referenceTokens) == 0 {
- return node, kind, nil
- }
-
- for _, token := range p.referenceTokens {
-
- decodedToken := Unescape(token)
-
- r, knd, err := getSingleImpl(node, decodedToken, nameProvider)
- if err != nil {
- return nil, knd, err
- }
- node = r
- }
-
- rValue := reflect.ValueOf(node)
- kind = rValue.Kind()
-
- return node, kind, nil
-}
-
-func (p *Pointer) set(node, data any, nameProvider *swag.NameProvider) error {
- knd := reflect.ValueOf(node).Kind()
-
- if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array {
- return errors.New("only structs, pointers, maps and slices are supported for setting values")
- }
-
- if nameProvider == nil {
- nameProvider = swag.DefaultJSONNameProvider
- }
-
- // Full document when empty
- if len(p.referenceTokens) == 0 {
- return nil
- }
-
- lastI := len(p.referenceTokens) - 1
- for i, token := range p.referenceTokens {
- isLastToken := i == lastI
- decodedToken := Unescape(token)
-
- if isLastToken {
-
- return setSingleImpl(node, data, decodedToken, nameProvider)
- }
-
- rValue := reflect.Indirect(reflect.ValueOf(node))
- kind := rValue.Kind()
-
- if rValue.Type().Implements(jsonPointableType) {
- r, err := node.(JSONPointable).JSONLookup(decodedToken)
- if err != nil {
- return err
- }
- fld := reflect.ValueOf(r)
- if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr {
- node = fld.Addr().Interface()
- continue
- }
- node = r
- continue
- }
-
- switch kind { //nolint:exhaustive
- case reflect.Struct:
- nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
- if !ok {
- return fmt.Errorf("object has no field %q", decodedToken)
- }
- fld := rValue.FieldByName(nm)
- if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr {
- node = fld.Addr().Interface()
- continue
- }
- node = fld.Interface()
-
- case reflect.Map:
- kv := reflect.ValueOf(decodedToken)
- mv := rValue.MapIndex(kv)
-
- if !mv.IsValid() {
- return fmt.Errorf("object has no key %q", decodedToken)
- }
- if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr {
- node = mv.Addr().Interface()
- continue
- }
- node = mv.Interface()
-
- case reflect.Slice:
- tokenIndex, err := strconv.Atoi(decodedToken)
- if err != nil {
- return err
- }
- sLength := rValue.Len()
- if tokenIndex < 0 || tokenIndex >= sLength {
- return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex)
- }
-
- elem := rValue.Index(tokenIndex)
- if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr {
- node = elem.Addr().Interface()
- continue
- }
- node = elem.Interface()
-
- default:
- return fmt.Errorf("invalid token reference %q", decodedToken)
- }
-
- }
-
- return nil
-}
-
-// DecodedTokens returns the decoded tokens
+// DecodedTokens returns the decoded (unescaped) tokens of this JSON pointer.
func (p *Pointer) DecodedTokens() []string {
result := make([]string, 0, len(p.referenceTokens))
- for _, t := range p.referenceTokens {
- result = append(result, Unescape(t))
+ for _, token := range p.referenceTokens {
+ result = append(result, Unescape(token))
}
+
return result
}
-// IsEmpty returns true if this is an empty json pointer
-// this indicates that it points to the root document
+// IsEmpty returns true if this is an empty json pointer.
+//
+// This indicates that it points to the root document.
func (p *Pointer) IsEmpty() bool {
return len(p.referenceTokens) == 0
}
-// Pointer to string representation function
+// String representation of a pointer.
func (p *Pointer) String() string {
-
if len(p.referenceTokens) == 0 {
return emptyPointer
}
- pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator)
-
- return pointerString
+ return pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator)
}
func (p *Pointer) Offset(document string) (int64, error) {
@@ -404,15 +131,328 @@ func (p *Pointer) Offset(document string) (int64, error) {
return 0, err
}
default:
- return 0, fmt.Errorf("invalid token %#v", tk)
+ return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer)
}
default:
- return 0, fmt.Errorf("invalid token %#v", tk)
+ return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer)
}
}
return offset, nil
}
+// "Constructor", parses the given string JSON pointer.
+func (p *Pointer) parse(jsonPointerString string) error {
+ if jsonPointerString == emptyPointer {
+ return nil
+ }
+
+ if !strings.HasPrefix(jsonPointerString, pointerSeparator) {
+ // non empty pointer must start with "/"
+ return errors.Join(ErrInvalidStart, ErrPointer)
+ }
+
+ referenceTokens := strings.Split(jsonPointerString, pointerSeparator)
+ p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...)
+
+ return nil
+}
+
+func (p *Pointer) get(node any, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) {
+ if nameProvider == nil {
+ nameProvider = jsonname.DefaultJSONNameProvider
+ }
+
+ kind := reflect.Invalid
+
+ // full document when empty
+ if len(p.referenceTokens) == 0 {
+ return node, kind, nil
+ }
+
+ for _, token := range p.referenceTokens {
+ decodedToken := Unescape(token)
+
+ r, knd, err := getSingleImpl(node, decodedToken, nameProvider)
+ if err != nil {
+ return nil, knd, err
+ }
+ node = r
+ }
+
+ rValue := reflect.ValueOf(node)
+ kind = rValue.Kind()
+
+ return node, kind, nil
+}
+
+func (p *Pointer) set(node, data any, nameProvider *jsonname.NameProvider) error {
+ knd := reflect.ValueOf(node).Kind()
+
+ if knd != reflect.Pointer && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array {
+ return errors.Join(
+ fmt.Errorf("unexpected type: %T", node), //nolint:err113 // err wrapping is carried out by errors.Join, not fmt.Errorf.
+ ErrUnsupportedValueType,
+ ErrPointer,
+ )
+ }
+
+ l := len(p.referenceTokens)
+
+ // full document when empty
+ if l == 0 {
+ return nil
+ }
+
+ if nameProvider == nil {
+ nameProvider = jsonname.DefaultJSONNameProvider
+ }
+
+ var decodedToken string
+ lastIndex := l - 1
+
+ if lastIndex > 0 { // skip if we only have one token in pointer
+ for _, token := range p.referenceTokens[:lastIndex] {
+ decodedToken = Unescape(token)
+ next, err := p.resolveNodeForToken(node, decodedToken, nameProvider)
+ if err != nil {
+ return err
+ }
+
+ node = next
+ }
+ }
+
+ // last token
+ decodedToken = Unescape(p.referenceTokens[lastIndex])
+
+ return setSingleImpl(node, data, decodedToken, nameProvider)
+}
+
+func (p *Pointer) resolveNodeForToken(node any, decodedToken string, nameProvider *jsonname.NameProvider) (next any, err error) {
+ // check for nil during traversal
+ if isNil(node) {
+ return nil, fmt.Errorf("cannot traverse through nil value at %q: %w", decodedToken, ErrPointer)
+ }
+
+ pointable, ok := node.(JSONPointable)
+ if ok {
+ r, err := pointable.JSONLookup(decodedToken)
+ if err != nil {
+ return nil, err
+ }
+
+ fld := reflect.ValueOf(r)
+ if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Pointer {
+ return fld.Addr().Interface(), nil
+ }
+
+ return r, nil
+ }
+
+ rValue := reflect.Indirect(reflect.ValueOf(node))
+ kind := rValue.Kind()
+
+ switch kind {
+ case reflect.Struct:
+ nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
+ if !ok {
+ return nil, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer)
+ }
+
+ return typeFromValue(rValue.FieldByName(nm)), nil
+
+ case reflect.Map:
+ kv := reflect.ValueOf(decodedToken)
+ mv := rValue.MapIndex(kv)
+
+ if !mv.IsValid() {
+ return nil, errNoKey(decodedToken)
+ }
+
+ return typeFromValue(mv), nil
+
+ case reflect.Slice:
+ tokenIndex, err := strconv.Atoi(decodedToken)
+ if err != nil {
+ return nil, errors.Join(err, ErrPointer)
+ }
+
+ sLength := rValue.Len()
+ if tokenIndex < 0 || tokenIndex >= sLength {
+ return nil, errOutOfBounds(sLength, tokenIndex)
+ }
+
+ return typeFromValue(rValue.Index(tokenIndex)), nil
+
+ default:
+ return nil, errInvalidReference(decodedToken)
+ }
+}
+
+func isNil(input any) bool {
+ if input == nil {
+ return true
+ }
+
+ kind := reflect.TypeOf(input).Kind()
+ switch kind {
+ case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan:
+ return reflect.ValueOf(input).IsNil()
+ default:
+ return false
+ }
+}
+
+func typeFromValue(v reflect.Value) any {
+ if v.CanAddr() && v.Kind() != reflect.Interface && v.Kind() != reflect.Map && v.Kind() != reflect.Slice && v.Kind() != reflect.Pointer {
+ return v.Addr().Interface()
+ }
+
+ return v.Interface()
+}
+
+// GetForToken gets a value for a json pointer token 1 level deep.
+func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) {
+ return getSingleImpl(document, decodedToken, jsonname.DefaultJSONNameProvider)
+}
+
+// SetForToken sets a value for a json pointer token 1 level deep.
+func SetForToken(document any, decodedToken string, value any) (any, error) {
+ return document, setSingleImpl(document, value, decodedToken, jsonname.DefaultJSONNameProvider)
+}
+
+func getSingleImpl(node any, decodedToken string, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) {
+ rValue := reflect.Indirect(reflect.ValueOf(node))
+ kind := rValue.Kind()
+ if isNil(node) {
+ return nil, kind, fmt.Errorf("nil value has no field %q: %w", decodedToken, ErrPointer)
+ }
+
+ switch typed := node.(type) {
+ case JSONPointable:
+ r, err := typed.JSONLookup(decodedToken)
+ if err != nil {
+ return nil, kind, err
+ }
+ return r, kind, nil
+ case *any: // case of a pointer to interface, that is not resolved by reflect.Indirect
+ return getSingleImpl(*typed, decodedToken, nameProvider)
+ }
+
+ switch kind {
+ case reflect.Struct:
+ nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
+ if !ok {
+ return nil, kind, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer)
+ }
+
+ fld := rValue.FieldByName(nm)
+
+ return fld.Interface(), kind, nil
+
+ case reflect.Map:
+ kv := reflect.ValueOf(decodedToken)
+ mv := rValue.MapIndex(kv)
+
+ if mv.IsValid() {
+ return mv.Interface(), kind, nil
+ }
+
+ return nil, kind, errNoKey(decodedToken)
+
+ case reflect.Slice:
+ tokenIndex, err := strconv.Atoi(decodedToken)
+ if err != nil {
+ return nil, kind, errors.Join(err, ErrPointer)
+ }
+ sLength := rValue.Len()
+ if tokenIndex < 0 || tokenIndex >= sLength {
+ return nil, kind, errOutOfBounds(sLength, tokenIndex)
+ }
+
+ elem := rValue.Index(tokenIndex)
+ return elem.Interface(), kind, nil
+
+ default:
+ return nil, kind, errInvalidReference(decodedToken)
+ }
+}
+
+func setSingleImpl(node, data any, decodedToken string, nameProvider *jsonname.NameProvider) error {
+ // check for nil to prevent panic when calling rValue.Type()
+ if isNil(node) {
+ return fmt.Errorf("cannot set field %q on nil value: %w", decodedToken, ErrPointer)
+ }
+
+ if ns, ok := node.(JSONSetable); ok {
+ return ns.JSONSet(decodedToken, data)
+ }
+
+ rValue := reflect.Indirect(reflect.ValueOf(node))
+
+ switch rValue.Kind() {
+ case reflect.Struct:
+ nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken)
+ if !ok {
+ return fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer)
+ }
+
+ fld := rValue.FieldByName(nm)
+ if !fld.CanSet() {
+ return fmt.Errorf("can't set struct field %s to %v: %w", nm, data, ErrPointer)
+ }
+
+ value := reflect.ValueOf(data)
+ valueType := value.Type()
+ assignedType := fld.Type()
+
+ if !valueType.AssignableTo(assignedType) {
+ return fmt.Errorf("can't set value with type %T to field %s with type %v: %w", data, nm, assignedType, ErrPointer)
+ }
+
+ fld.Set(value)
+
+ return nil
+
+ case reflect.Map:
+ kv := reflect.ValueOf(decodedToken)
+ rValue.SetMapIndex(kv, reflect.ValueOf(data))
+
+ return nil
+
+ case reflect.Slice:
+ tokenIndex, err := strconv.Atoi(decodedToken)
+ if err != nil {
+ return errors.Join(err, ErrPointer)
+ }
+
+ sLength := rValue.Len()
+ if tokenIndex < 0 || tokenIndex >= sLength {
+ return errOutOfBounds(sLength, tokenIndex)
+ }
+
+ elem := rValue.Index(tokenIndex)
+ if !elem.CanSet() {
+ return fmt.Errorf("can't set slice index %s to %v: %w", decodedToken, data, ErrPointer)
+ }
+
+ value := reflect.ValueOf(data)
+ valueType := value.Type()
+ assignedType := elem.Type()
+
+ if !valueType.AssignableTo(assignedType) {
+ return fmt.Errorf("can't set value with type %T to slice element %d with type %v: %w", data, tokenIndex, assignedType, ErrPointer)
+ }
+
+ elem.Set(value)
+
+ return nil
+
+ default:
+ return errInvalidReference(decodedToken)
+ }
+}
+
func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) {
for dec.More() {
offset := dec.InputOffset()
@@ -437,16 +477,17 @@ func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) {
return offset, nil
}
default:
- return 0, fmt.Errorf("invalid token %#v", tk)
+ return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer)
}
}
- return 0, fmt.Errorf("token reference %q not found", decodedToken)
+
+ return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer)
}
func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) {
idx, err := strconv.Atoi(decodedToken)
if err != nil {
- return 0, fmt.Errorf("token reference %q is not a number: %v", decodedToken, err)
+ return 0, fmt.Errorf("token reference %q is not a number: %w: %w", decodedToken, err, ErrPointer)
}
var i int
for i = 0; i < idx && dec.More(); i++ {
@@ -470,12 +511,14 @@ func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) {
}
if !dec.More() {
- return 0, fmt.Errorf("token reference %q not found", decodedToken)
+ return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer)
}
+
return dec.InputOffset(), nil
}
// drainSingle drains a single level of object or array.
+//
// The decoder has to guarantee the beginning delim (i.e. '{' or '[') has been consumed.
func drainSingle(dec *json.Decoder) error {
for dec.More() {
@@ -497,14 +540,15 @@ func drainSingle(dec *json.Decoder) error {
}
}
- // Consumes the ending delim
+ // consumes the ending delim
if _, err := dec.Token(); err != nil {
return err
}
+
return nil
}
-// Specific JSON pointer encoding here
+// JSON pointer encoding:
// ~0 => ~
// ~1 => /
// ... and vice versa
@@ -516,16 +560,24 @@ const (
decRefTok1 = `/`
)
-// Unescape unescapes a json pointer reference token string to the original representation
+var (
+ encRefTokReplacer = strings.NewReplacer(encRefTok1, decRefTok1, encRefTok0, decRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global
+ decRefTokReplacer = strings.NewReplacer(decRefTok1, encRefTok1, decRefTok0, encRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global
+)
+
+// Unescape unescapes a json pointer reference token string to the original representation.
func Unescape(token string) string {
- step1 := strings.ReplaceAll(token, encRefTok1, decRefTok1)
- step2 := strings.ReplaceAll(step1, encRefTok0, decRefTok0)
- return step2
+ return encRefTokReplacer.Replace(token)
}
-// Escape escapes a pointer reference token string
+// Escape escapes a pointer reference token string.
+//
+// The JSONPointer specification defines "/" as a separator and "~" as an escape prefix.
+//
+// Keys containing such characters are escaped with the following rules:
+//
+// - "~" is escaped as "~0"
+// - "/" is escaped as "~1"
func Escape(token string) string {
- step1 := strings.ReplaceAll(token, decRefTok0, encRefTok0)
- step2 := strings.ReplaceAll(step1, decRefTok1, encRefTok1)
- return step2
+ return decRefTokReplacer.Replace(token)
}
diff --git a/test/tools/vendor/github.com/go-openapi/jsonreference/.editorconfig b/test/tools/vendor/github.com/go-openapi/jsonreference/.editorconfig
new file mode 100644
index 0000000000..3152da69a5
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/.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/test/tools/vendor/github.com/go-openapi/jsonreference/.gitignore b/test/tools/vendor/github.com/go-openapi/jsonreference/.gitignore
index 769c244007..885dc27ab0 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonreference/.gitignore
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/.gitignore
@@ -1 +1,6 @@
-secrets.yml
+*.out
+*.cov
+.idea
+.env
+.mcp.json
+.claude/
diff --git a/test/tools/vendor/github.com/go-openapi/jsonreference/.golangci.yml b/test/tools/vendor/github.com/go-openapi/jsonreference/.golangci.yml
index 22f8d21cca..dc7c96053d 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonreference/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/.golangci.yml
@@ -1,61 +1,67 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
+ - depguard
- funlen
- godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- exhaustruct
- - varnamelen
- - gci
- - depguard
- - errchkjson
- - inamedparam
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 20
+ gocyclo:
+ min-complexity: 20
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md
new file mode 100644
index 0000000000..7faeb83a77
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md
@@ -0,0 +1,21 @@
+# Contributors
+
+- Repository: ['go-openapi/jsonreference']
+
+| Total Contributors | Total Contributions |
+| --- | --- |
+| 9 | 73 |
+
+| Username | All Time Contribution Count | All Commits |
+| --- | --- | --- |
+| @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 |
+| @apelisse | 1 | https://github.com/go-openapi/jsonreference/commits?author=apelisse |
+| @gbjk | 1 | https://github.com/go-openapi/jsonreference/commits?author=gbjk |
+| @honza | 1 | https://github.com/go-openapi/jsonreference/commits?author=honza |
+| @Neo2308 | 1 | https://github.com/go-openapi/jsonreference/commits?author=Neo2308 |
+| @erraggy | 1 | https://github.com/go-openapi/jsonreference/commits?author=erraggy |
+
+ _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_
diff --git a/test/tools/vendor/github.com/go-openapi/jsonreference/NOTICE b/test/tools/vendor/github.com/go-openapi/jsonreference/NOTICE
new file mode 100644
index 0000000000..814e87ef8c
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/NOTICE
@@ -0,0 +1,39 @@
+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/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");
+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 on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com).
+
+github.com/sigh-399/jsonreference
+===========================
+
+// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
+// SPDX-License-Identifier: Apache-2.0
+
+Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
+
+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/test/tools/vendor/github.com/go-openapi/jsonreference/README.md b/test/tools/vendor/github.com/go-openapi/jsonreference/README.md
index c7fc2049c1..adea160619 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonreference/README.md
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/README.md
@@ -1,19 +1,127 @@
-# gojsonreference [](https://github.com/go-openapi/jsonreference/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/jsonreference)
+# jsonreference
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/jsonreference/master/LICENSE)
-[](https://pkg.go.dev/github.com/go-openapi/jsonreference)
-[](https://goreportcard.com/report/github.com/go-openapi/jsonreference)
+
+[![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]
-An implementation of JSON Reference - Go language
+---
+
+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
-Feature complete. Stable API
+
+API is stable.
+
+## Import this library in your project
+
+```cmd
+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
+
+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
+
+* [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/jsonreference/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/jsonreference/actions/workflows/go-test.yml/badge.svg
+[test-url]: https://github.com/go-openapi/jsonreference/actions/workflows/go-test.yml
+[cov-badge]: https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg
+[cov-url]: https://codecov.io/gh/go-openapi/jsonreference
+[vuln-scan-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/scanner.yml/badge.svg
+[vuln-scan-url]: https://github.com/go-openapi/jsonreference/actions/workflows/scanner.yml
+[codeql-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/codeql.yml/badge.svg
+[codeql-url]: https://github.com/go-openapi/jsonreference/actions/workflows/codeql.yml
+
+[release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonreference.svg
+[release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonreference
+[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference.svg
+[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference
+
+[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonreference
+[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonreference
+[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonreference
+[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonreference
+
+[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/jsonreference
+[godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonreference
+[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
+
+[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/jsonreference
+[goversion-url]: https://github.com/go-openapi/jsonreference/blob/master/go.mod
+[top-badge]: https://img.shields.io/github/languages/top/go-openapi/jsonreference
+[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/jsonreference/latest
diff --git a/test/tools/vendor/github.com/go-openapi/jsonreference/SECURITY.md b/test/tools/vendor/github.com/go-openapi/jsonreference/SECURITY.md
new file mode 100644
index 0000000000..1fea2c5736
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/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/test/tools/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go b/test/tools/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go
index f0610cf1e5..a08b47320e 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package internal
import (
@@ -11,9 +14,11 @@ const (
defaultHTTPSPort = ":443"
)
-// Regular expressions used by the normalizations
-var rxPort = regexp.MustCompile(`(:\d+)/?$`)
-var rxDupSlashes = regexp.MustCompile(`/{2,}`)
+// Regular expressions used by the normalizations.
+var (
+ rxPort = regexp.MustCompile(`(:\d+)/?$`)
+ rxDupSlashes = regexp.MustCompile(`/{2,}`)
+)
// NormalizeURL will normalize the specified URL
// This was added to replace a previous call to the no longer maintained purell library:
diff --git a/test/tools/vendor/github.com/go-openapi/jsonreference/reference.go b/test/tools/vendor/github.com/go-openapi/jsonreference/reference.go
index cfdef03e5d..003ba7a838 100644
--- a/test/tools/vendor/github.com/go-openapi/jsonreference/reference.go
+++ b/test/tools/vendor/github.com/go-openapi/jsonreference/reference.go
@@ -1,27 +1,5 @@
-// Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
-//
-// 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.
-
-// author sigu-399
-// author-github https://github.com/sigu-399
-// author-mail sigu.399@gmail.com
-//
-// repository-name jsonreference
-// repository-desc An implementation of JSON Reference - Go language
-//
-// description Main and unique file.
-//
-// created 26-02-2013
+// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package jsonreference
@@ -38,26 +16,10 @@ const (
fragmentRune = `#`
)
-// New creates a new reference for the given string
-func New(jsonReferenceString string) (Ref, error) {
+// ErrChildURL is raised when there is no child.
+var ErrChildURL = errors.New("child url is nil")
- var r Ref
- err := r.parse(jsonReferenceString)
- return r, err
-
-}
-
-// MustCreateRef parses the ref string and panics when it's invalid.
-// Use the New method for a version that returns an error
-func MustCreateRef(ref string) Ref {
- r, err := New(ref)
- if err != nil {
- panic(err)
- }
- return r
-}
-
-// Ref represents a json reference object
+// Ref represents a json reference object.
type Ref struct {
referenceURL *url.URL
referencePointer jsonpointer.Pointer
@@ -69,19 +31,36 @@ type Ref struct {
HasFullFilePath bool
}
-// GetURL gets the URL for this reference
+// New creates a new reference for the given string.
+func New(jsonReferenceString string) (Ref, error) {
+ var r Ref
+ err := r.parse(jsonReferenceString)
+ return r, err
+}
+
+// MustCreateRef parses the ref string and panics when it's invalid.
+// Use the New method for a version that returns an error.
+func MustCreateRef(ref string) Ref {
+ r, err := New(ref)
+ if err != nil {
+ panic(err)
+ }
+
+ return r
+}
+
+// GetURL gets the URL for this reference.
func (r *Ref) GetURL() *url.URL {
return r.referenceURL
}
-// GetPointer gets the json pointer for this reference
+// GetPointer gets the json pointer for this reference.
func (r *Ref) GetPointer() *jsonpointer.Pointer {
return &r.referencePointer
}
-// String returns the best version of the url for this reference
+// String returns the best version of the url for this reference.
func (r *Ref) String() string {
-
if r.referenceURL != nil {
return r.referenceURL.String()
}
@@ -93,7 +72,7 @@ func (r *Ref) String() string {
return r.referencePointer.String()
}
-// IsRoot returns true if this reference is a root document
+// IsRoot returns true if this reference is a root document.
func (r *Ref) IsRoot() bool {
return r.referenceURL != nil &&
!r.IsCanonical() &&
@@ -101,14 +80,32 @@ func (r *Ref) IsRoot() bool {
r.referenceURL.Fragment == ""
}
-// IsCanonical returns true when this pointer starts with http(s):// or file://
+// IsCanonical returns true when this pointer starts with http(s):// or file://.
func (r *Ref) IsCanonical() bool {
return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL)
}
-// "Constructor", parses the given string JSON reference
-func (r *Ref) parse(jsonReferenceString string) error {
+// Inherits creates a new reference from a parent and a child
+// If the child cannot inherit from the parent, an error is returned.
+func (r *Ref) Inherits(child Ref) (*Ref, error) {
+ childURL := child.GetURL()
+ parentURL := r.GetURL()
+ if childURL == nil {
+ return nil, ErrChildURL
+ }
+ if parentURL == nil {
+ return &child, nil
+ }
+ ref, err := New(parentURL.ResolveReference(childURL).String())
+ if err != nil {
+ return nil, err
+ }
+ return &ref, nil
+}
+
+// "Constructor", parses the given string JSON reference.
+func (r *Ref) parse(jsonReferenceString string) error {
parsed, err := url.Parse(jsonReferenceString)
if err != nil {
return err
@@ -137,22 +134,3 @@ func (r *Ref) parse(jsonReferenceString string) error {
return nil
}
-
-// Inherits creates a new reference from a parent and a child
-// If the child cannot inherit from the parent, an error is returned
-func (r *Ref) Inherits(child Ref) (*Ref, error) {
- childURL := child.GetURL()
- parentURL := r.GetURL()
- if childURL == nil {
- return nil, errors.New("child url is nil")
- }
- if parentURL == nil {
- return &child, nil
- }
-
- ref, err := New(parentURL.ResolveReference(childURL).String())
- if err != nil {
- return nil, err
- }
- return &ref, nil
-}
diff --git a/test/tools/vendor/github.com/go-openapi/loads/.gitignore b/test/tools/vendor/github.com/go-openapi/loads/.gitignore
index e4f15f17bf..d8f4186fe5 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/.gitignore
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/loads/.golangci.yml b/test/tools/vendor/github.com/go-openapi/loads/.golangci.yml
index 22f8d21cca..83968f3fae 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/loads/.golangci.yml
@@ -1,61 +1,69 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
- - funlen
- - godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- - exhaustruct
- - varnamelen
- - gci
- depguard
- - errchkjson
- - inamedparam
+ - funlen
+ - gochecknoglobals # on this repo, it is hard to refactor without globals/inits and no breaking change
+ - gochecknoinits
+ - godox
+ - exhaustruct
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 20
+ gocyclo:
+ min-complexity: 20
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/loads/.travis.yml b/test/tools/vendor/github.com/go-openapi/loads/.travis.yml
deleted file mode 100644
index cd4a7c331b..0000000000
--- a/test/tools/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/test/tools/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/loads/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/loads/CONTRIBUTORS.md
new file mode 100644
index 0000000000..36b836a3d5
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/loads/README.md b/test/tools/vendor/github.com/go-openapi/loads/README.md
index f8bd440dfc..d92e62a040 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/README.md
+++ b/test/tools/vendor/github.com/go-openapi/loads/README.md
@@ -1,6 +1,118 @@
-# Loads OAI specs [](https://github.com/go-openapi/loads/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/loads)
+# Loads OAI specs
-[](https://raw.githubusercontent.com/go-openapi/loads/master/LICENSE) [](http://godoc.org/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 specification documents from local or remote locations. Supports JSON and YAML documents.
+---
+
+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 (
+ "github.com/go-openapi/loads"
+ )
+
+ ...
+
+ // loads a YAML spec from a http file
+ doc, err := loads.Spec(ts.URL)
+
+ ...
+
+ // retrieves the object model for the API specification
+ spec := doc.Spec()
+
+ ...
+```
+
+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/test/tools/vendor/github.com/go-openapi/loads/SECURITY.md b/test/tools/vendor/github.com/go-openapi/loads/SECURITY.md
new file mode 100644
index 0000000000..6ceb159ca2
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/loads/doc.go b/test/tools/vendor/github.com/go-openapi/loads/doc.go
index 5bcaef5dbc..67a5e2f8d9 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/doc.go
+++ b/test/tools/vendor/github.com/go-openapi/loads/doc.go
@@ -1,18 +1,9 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
-// Package loads provides document loading methods for swagger (OAI) specifications.
+// 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/test/tools/vendor/github.com/go-openapi/loads/errors.go b/test/tools/vendor/github.com/go-openapi/loads/errors.go
new file mode 100644
index 0000000000..14a8186b6c
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/loads/errors.go
@@ -0,0 +1,18 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
+package loads
+
+type loaderError string
+
+func (e loaderError) Error() string {
+ return string(e)
+}
+
+const (
+ // ErrLoads is an error returned by the loads package.
+ ErrLoads loaderError = "loaderrs error"
+
+ // ErrNoLoader indicates that no configured loader matched the input.
+ ErrNoLoader loaderError = "no loader matched"
+)
diff --git a/test/tools/vendor/github.com/go-openapi/loads/fmts/yaml.go b/test/tools/vendor/github.com/go-openapi/loads/fmts/yaml.go
index 1cef2ac22b..0526118489 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/fmts/yaml.go
+++ b/test/tools/vendor/github.com/go-openapi/loads/fmts/yaml.go
@@ -1,30 +1,22 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package fmts
-import "github.com/go-openapi/swag"
+import (
+ "github.com/go-openapi/swag/loading"
+ "github.com/go-openapi/swag/yamlutils"
+)
var (
- // YAMLMatcher matches yaml
- YAMLMatcher = swag.YAMLMatcher
- // YAMLToJSON converts YAML unmarshaled data into json compatible data
- YAMLToJSON = swag.YAMLToJSON
- // BytesToYAMLDoc converts raw bytes to a map[string]interface{}
- BytesToYAMLDoc = swag.BytesToYAMLDoc
- // YAMLDoc loads a yaml document from either http or a file and converts it to json
- YAMLDoc = swag.YAMLDoc
- // YAMLData loads a yaml document from either http or a file
- YAMLData = swag.YAMLData
+ // YAMLMatcher matches yaml.
+ YAMLMatcher = loading.YAMLMatcher
+ // YAMLToJSON converts YAML unmarshaled data into json compatible data.
+ YAMLToJSON = yamlutils.YAMLToJSON
+ // BytesToYAMLDoc converts raw bytes to a map[string]interface{}.
+ BytesToYAMLDoc = yamlutils.BytesToYAMLDoc
+ // YAMLDoc loads a yaml document from either http or a file and converts it to json.
+ YAMLDoc = loading.YAMLDoc
+ // YAMLData loads a yaml document from either http or a file.
+ YAMLData = loading.YAMLData
)
diff --git a/test/tools/vendor/github.com/go-openapi/loads/loaders.go b/test/tools/vendor/github.com/go-openapi/loads/loaders.go
index b2d1e034c5..ac8adfe8b2 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/loaders.go
+++ b/test/tools/vendor/github.com/go-openapi/loads/loaders.go
@@ -1,22 +1,24 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package loads
import (
"encoding/json"
"errors"
"net/url"
+ "slices"
"github.com/go-openapi/spec"
- "github.com/go-openapi/swag"
+ "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{
@@ -30,8 +32,8 @@ func init() {
loaders = jsonLoader.WithHead(&loader{
DocLoaderWithMatch: DocLoaderWithMatch{
- Match: swag.YAMLMatcher,
- Fn: swag.YAMLDoc,
+ Match: loading.YAMLMatcher,
+ Fn: loading.YAMLDoc,
},
})
@@ -39,10 +41,10 @@ func init() {
spec.PathLoader = loaders.Load
}
-// DocLoader represents a doc loader type
-type DocLoader func(string) (json.RawMessage, error)
+// 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.
@@ -51,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,
@@ -61,10 +63,13 @@ func NewDocLoaderWithMatch(fn DocLoader, matcher DocMatcher) DocLoaderWithMatch
type loader struct {
DocLoaderWithMatch
+
+ loadingOptions []loading.Option
+
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
@@ -73,27 +78,27 @@ 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 {
- return nil, erp
+ return nil, errors.Join(erp, ErrLoads)
}
- lastErr := errors.New("no loader matched") // default error if no match was found
+ var lastErr error = ErrNoLoader // default error if no match was found
for ldr := l; ldr != nil; ldr = ldr.Next {
if ldr.Match != nil && !ldr.Match(path) {
continue
}
// try then move to next one if there is an error
- b, err := ldr.Fn(path)
+ b, err := ldr.Fn(path, l.loadingOptions...)
if err == nil {
return b, nil
}
@@ -101,14 +106,29 @@ func (l *loader) Load(path string) (json.RawMessage, error) {
lastErr = err
}
- return nil, lastErr
+ return nil, errors.Join(lastErr, ErrLoads)
}
-// JSONDoc loads a json document from either a file or a remote url
-func JSONDoc(path string) (json.RawMessage, error) {
- data, err := swag.LoadFromFileOrHTTP(path)
+func (l *loader) clone() *loader {
+ if l == nil {
+ return nil
+ }
+
+ return &loader{
+ DocLoaderWithMatch: l.DocLoaderWithMatch,
+ loadingOptions: slices.Clone(l.loadingOptions),
+ Next: l.Next.clone(),
+ }
+}
+
+// JSONDoc loads a json document from either a file or a remote URL.
+//
+// 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...)
if err != nil {
- return nil, err
+ return nil, errors.Join(err, ErrLoads)
}
return json.RawMessage(data), nil
}
@@ -117,9 +137,10 @@ func JSONDoc(path string) (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/test/tools/vendor/github.com/go-openapi/loads/options.go b/test/tools/vendor/github.com/go-openapi/loads/options.go
index f8305d5607..045ece5e09 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/options.go
+++ b/test/tools/vendor/github.com/go-openapi/loads/options.go
@@ -1,7 +1,13 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package loads
+import "github.com/go-openapi/swag/loading"
+
type options struct {
- loader *loader
+ loader *loader
+ loadingOptions []loading.Option
}
func defaultOptions() *options {
@@ -16,13 +22,16 @@ func loaderFromOptions(options []LoaderOption) *loader {
apply(opts)
}
- return opts.loader
+ l := opts.loader.clone()
+ l.loadingOptions = opts.loadingOptions
+
+ 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 {
@@ -39,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
@@ -59,3 +68,10 @@ func WithDocLoaderMatches(l ...DocLoaderWithMatch) LoaderOption {
opt.loader = final
}
}
+
+// WithLoadingOptions adds some [loading.Option] to be added when calling a registered loader.
+func WithLoadingOptions(loadingOptions ...loading.Option) LoaderOption {
+ return func(opt *options) {
+ opt.loadingOptions = loadingOptions
+ }
+}
diff --git a/test/tools/vendor/github.com/go-openapi/loads/spec.go b/test/tools/vendor/github.com/go-openapi/loads/spec.go
index c9039cd5d7..606a01d8e9 100644
--- a/test/tools/vendor/github.com/go-openapi/loads/spec.go
+++ b/test/tools/vendor/github.com/go-openapi/loads/spec.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package loads
@@ -18,19 +7,21 @@ import (
"bytes"
"encoding/gob"
"encoding/json"
+ "errors"
"fmt"
+ "maps"
"github.com/go-openapi/analysis"
"github.com/go-openapi/spec"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/yamlutils"
)
func init() {
- gob.Register(map[string]interface{}{})
- gob.Register([]interface{}{})
+ gob.Register(map[string]any{})
+ gob.Register([]any{})
}
-// Document represents a swagger spec document
+// Document represents a swagger spec document.
type Document struct {
// specAnalyzer
Analyzer *analysis.Spec
@@ -42,14 +33,21 @@ type Document struct {
raw json.RawMessage
}
-// JSONSpec loads a spec from a json document
-func JSONSpec(path string, options ...LoaderOption) (*Document, error) {
- data, err := JSONDoc(path)
+// 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) {
+ var o options
+ for _, apply := range opts {
+ apply(&o)
+ }
+
+ data, err := JSONDoc(path, o.loadingOptions...)
if err != nil {
return nil, err
}
// convert to json
- doc, err := Analyzed(data, "", options...)
+ doc, err := Analyzed(data, "", opts...)
if err != nil {
return nil, err
}
@@ -59,8 +57,8 @@ func JSONSpec(path string, options ...LoaderOption) (*Document, error) {
return doc, nil
}
-// Embedded returns a Document based on embedded specs. No analysis is required
-func Embedded(orig, flat json.RawMessage, options ...LoaderOption) (*Document, error) {
+// 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 {
return nil, err
@@ -72,20 +70,22 @@ func Embedded(orig, flat json.RawMessage, options ...LoaderOption) (*Document, e
raw: orig,
origSpec: &origSpec,
spec: &flatSpec,
- pathLoader: loaderFromOptions(options),
+ pathLoader: loaderFromOptions(opts),
}, nil
}
-// Spec loads a new spec document from a local or remote path
-func Spec(path string, options ...LoaderOption) (*Document, error) {
- ldr := loaderFromOptions(options)
+// Spec loads a new spec document from a local or remote path.
+//
+// By default it uses a JSON or YAML loader, with auto-detection based on the resource extension.
+func Spec(path string, opts ...LoaderOption) (*Document, error) {
+ ldr := loaderFromOptions(opts)
b, err := ldr.Load(path)
if err != nil {
return nil, err
}
- document, err := Analyzed(b, "", options...)
+ document, err := Analyzed(b, "", opts...)
if err != nil {
return nil, err
}
@@ -96,13 +96,13 @@ func Spec(path string, options ...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"
}
if version != "2.0" {
- return nil, fmt.Errorf("spec version %q is not supported", version)
+ return nil, fmt.Errorf("spec version %q is not supported: %w", version, ErrLoads)
}
raw, err := trimData(data) // trim blanks, then convert yaml docs into json
@@ -112,12 +112,12 @@ func Analyzed(data json.RawMessage, version string, options ...LoaderOption) (*D
swspec := new(spec.Swagger)
if err = json.Unmarshal(raw, swspec); err != nil {
- return nil, err
+ return nil, errors.Join(err, ErrLoads)
}
origsqspec, err := cloneSpec(swspec)
if err != nil {
- return nil, err
+ return nil, errors.Join(err, ErrLoads)
}
d := &Document{
@@ -143,20 +143,20 @@ func trimData(in json.RawMessage) (json.RawMessage, error) {
}
// assume yaml doc: convert it to json
- yml, err := swag.BytesToYAMLDoc(trimmed)
+ yml, err := yamlutils.BytesToYAMLDoc(trimmed)
if err != nil {
- return nil, fmt.Errorf("analyzed: %v", err)
+ return nil, fmt.Errorf("analyzed: %w: %w", err, ErrLoads)
}
- d, err := swag.YAMLToJSON(yml)
+ d, err := yamlutils.YAMLToJSON(yml)
if err != nil {
- return nil, fmt.Errorf("analyzed: %v", err)
+ 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 spec 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,55 +200,55 @@ 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 ""
+ }
return d.spec.BasePath
}
-// Version returns the version of this spec
+// 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 schema
+// Schema returns the swagger 2.0 meta-schema.
func (d *Document) Schema() *spec.Schema {
return d.schema
}
-// Spec returns the swagger spec object model
+// 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 gives 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 {
- defs := make(map[string]spec.Schema, len(d.origSpec.Definitions))
- for k, v := range d.origSpec.Definitions {
- defs[k] = v
- }
+ d.spec.Definitions = make(map[string]spec.Schema, len(d.origSpec.Definitions))
+ maps.Copy(d.spec.Definitions, d.origSpec.Definitions)
- d.spec.Definitions = defs
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
}
@@ -271,5 +271,6 @@ func cloneSpec(src *spec.Swagger) (*spec.Swagger, error) {
if err := gob.NewDecoder(&b).Decode(&dst); err != nil {
return nil, err
}
+
return &dst, nil
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/.gitignore b/test/tools/vendor/github.com/go-openapi/runtime/.gitignore
index fea8b84eca..d8f4186fe5 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/.gitignore
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/runtime/.golangci.yml b/test/tools/vendor/github.com/go-openapi/runtime/.golangci.yml
index 1c75557bac..0087ed3113 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/runtime/.golangci.yml
@@ -1,62 +1,77 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - nilerr # nilerr crashes on this repo
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
- - funlen
- - godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- - exhaustruct
- - varnamelen
- - gci
- - depguard
- - errchkjson
- - inamedparam
- - nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - depguard
+ - err113 # disabled temporarily: there are just too many issues to address
+ - errchkjson
+ - errorlint
+ - exhaustruct
+ - forcetypeassert
+ - funlen
+ - gochecknoglobals
+ - gochecknoinits
+ - gocognit
+ - godot
+ - godox
+ - gomoddirectives # moved to mono-repo, multi-modules, so replace directives are needed
+ - gosmopolitan
+ - inamedparam
+ - ireturn
+ - lll
+ - musttag
+ - nestif
+ - nilerr # nilerr crashes on this repo
+ - nlreturn
+ - noinlineerr
+ - nonamedreturns
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - unparam
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ gocyclo:
+ min-complexity: 45
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/mitchellh/mapstructure/LICENSE b/test/tools/vendor/github.com/go-openapi/runtime/NOTICE
similarity index 50%
rename from test/tools/vendor/github.com/mitchellh/mapstructure/LICENSE
rename to test/tools/vendor/github.com/go-openapi/runtime/NOTICE
index f9c841a51e..b9153aae9e 100644
--- a/test/tools/vendor/github.com/mitchellh/mapstructure/LICENSE
+++ b/test/tools/vendor/github.com/go-openapi/runtime/NOTICE
@@ -1,6 +1,30 @@
-The MIT License (MIT)
+Copyright 2015-2025 go-swagger maintainers
-Copyright (c) 2013 Mitchell Hashimoto
+// 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
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/README.md b/test/tools/vendor/github.com/go-openapi/runtime/README.md
index b07e0ad9d6..dd7f5039a7 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/README.md
+++ b/test/tools/vendor/github.com/go-openapi/runtime/README.md
@@ -1,10 +1,113 @@
-# runtime [](https://github.com/go-openapi/runtime/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/runtime)
+# runtime
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/runtime/master/LICENSE)
-[](https://pkg.go.dev/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.
+
+## 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
+```
+
+## Change log
+
+See
+
+For pre-v0.30.0 releases see [release notes](docs/NOTES.md).
+
+**What coming next?**
+
+Moving forward, we want to :
+
+* [ ] continue narrowing down the scope of dependencies:
+ * yaml support in an independent module
+ * introduce more up-to-date support for opentelemetry as a separate module that evolves
+ independently from the main package (to avoid breaking changes, the existing API
+ will remain maintained, but evolve at a slower pace than opentelemetry).
+* [ ] fix a few known issues with some file upload requests (e.g. #286)
+
+## 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/test/tools/vendor/github.com/go-openapi/runtime/SECURITY.md b/test/tools/vendor/github.com/go-openapi/runtime/SECURITY.md
new file mode 100644
index 0000000000..1fea2c5736
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/runtime/bytestream.go b/test/tools/vendor/github.com/go-openapi/runtime/bytestream.go
index f8fb482232..8701c8e3d6 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/bytestream.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/bytestream.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -22,14 +11,14 @@ import (
"io"
"reflect"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
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
}
@@ -43,18 +32,19 @@ 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 {
opt(&vals)
}
- return ConsumerFunc(func(reader io.Reader, data interface{}) error {
+ return ConsumerFunc(func(reader io.Reader, data any) error {
if reader == nil {
return errors.New("ByteStreamConsumer requires a reader") // early exit
}
@@ -135,20 +125,21 @@ 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 {
opt(&vals)
}
- return ProducerFunc(func(writer io.Writer, data interface{}) error {
+ return ProducerFunc(func(writer io.Writer, data any) error {
if writer == nil {
return errors.New("ByteStreamProducer requires a writer") // early exit
}
@@ -206,7 +197,7 @@ func ByteStreamProducer(opts ...byteStreamOpt) Producer {
return err
case t.Kind() == reflect.Struct || t.Kind() == reflect.Slice:
- b, err := swag.WriteJSON(data)
+ b, err := jsonutils.WriteJSON(data)
if err != nil {
return err
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/client_auth_info.go b/test/tools/vendor/github.com/go-openapi/runtime/client_auth_info.go
index c6c97d9a7c..5ef59c88bf 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/client_auth_info.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/client_auth_info.go
@@ -1,30 +1,19 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
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/test/tools/vendor/github.com/go-openapi/runtime/client_operation.go b/test/tools/vendor/github.com/go-openapi/runtime/client_operation.go
index 5a5d63563a..ad7277e091 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/client_operation.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/client_operation.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -19,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
@@ -34,8 +23,8 @@ 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) (interface{}, error)
+ Submit(*ClientOperation) (any, error)
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/client_request.go b/test/tools/vendor/github.com/go-openapi/runtime/client_request.go
index 4ebb2deabe..844f57b3ce 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/client_request.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/client_request.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -23,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
}
@@ -53,7 +42,7 @@ type ClientRequest interface { //nolint:interfacebloat // a swagger-capable requ
SetFileParam(string, ...NamedReadCloser) error
- SetBodyParam(interface{}) error
+ SetBodyParam(any) error
SetTimeout(time.Duration) error
@@ -63,18 +52,18 @@ type ClientRequest interface { //nolint:interfacebloat // a swagger-capable requ
GetBody() []byte
- GetBodyParam() interface{}
+ GetBodyParam() any
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 {
@@ -103,7 +92,7 @@ func (n *namedReadCloser) Name() string {
type TestClientRequest struct {
Headers http.Header
- Body interface{}
+ Body any
}
func (t *TestClientRequest) SetHeaderParam(name string, values ...string) error {
@@ -122,7 +111,7 @@ func (t *TestClientRequest) SetPathParam(_ string, _ string) error { return nil
func (t *TestClientRequest) SetFileParam(_ string, _ ...NamedReadCloser) error { return nil }
-func (t *TestClientRequest) SetBodyParam(body interface{}) error {
+func (t *TestClientRequest) SetBodyParam(body any) error {
t.Body = body
return nil
}
@@ -139,7 +128,7 @@ func (t *TestClientRequest) GetPath() string { return "" }
func (t *TestClientRequest) GetBody() []byte { return nil }
-func (t *TestClientRequest) GetBodyParam() interface{} {
+func (t *TestClientRequest) GetBodyParam() any {
return t.Body
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/client_response.go b/test/tools/vendor/github.com/go-openapi/runtime/client_response.go
index 0d1691149d..92668db4ec 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/client_response.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/client_response.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -18,10 +7,12 @@ import (
"encoding/json"
"fmt"
"io"
+ "strings"
)
-// A ClientResponse represents a client response
-// This bridges between responses obtained from different transports
+// A ClientResponse represents a client response.
+//
+// This bridges between responses obtained from different transports.
type ClientResponse interface {
Code() int
Message() string
@@ -30,22 +21,29 @@ type ClientResponse interface {
Body() io.ReadCloser
}
-// A ClientResponseReaderFunc turns a function into a ClientResponseReader interface implementation
-type ClientResponseReaderFunc func(ClientResponse, Consumer) (interface{}, error)
+// A ClientResponseReaderFunc turns a function into a [ClientResponseReader] interface implementation.
+type ClientResponseReaderFunc func(ClientResponse, Consumer) (any, error)
-// ReadResponse reads the response
-func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (interface{}, error) {
+// 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) (interface{}, error)
+ ReadResponse(ClientResponse, Consumer) (any, error)
}
-// NewAPIError creates a new API error
-func NewAPIError(opName string, payload interface{}, code int) *APIError {
+// 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.
+func NewAPIError(opName string, payload any, code int) *APIError {
return &APIError{
OperationName: opName,
Response: payload,
@@ -53,20 +51,17 @@ func NewAPIError(opName string, payload interface{}, code int) *APIError {
}
}
-// APIError wraps an error model and captures the status code
-type APIError struct {
- OperationName string
- Response interface{}
- Code int
-}
+// sanitizer ensures that single quotes are escaped.
+var sanitizer = strings.NewReplacer(`\`, `\\`, `'`, `\'`)
func (o *APIError) Error() string {
var resp []byte
if err, ok := o.Response.(error); ok {
- resp = []byte("'" + err.Error() + "'")
+ resp = []byte("'" + sanitizer.Replace(err.Error()) + "'")
} else {
resp, _ = json.Marshal(o.Response)
}
+
return fmt.Sprintf("%s (status %d): %s", o.OperationName, o.Code, resp)
}
@@ -74,33 +69,37 @@ func (o *APIError) String() string {
return o.Error()
}
-// IsSuccess returns true when this elapse o k response returns a 2xx status code
+// IsSuccess returns true when this API response returns a 2xx status code.
func (o *APIError) IsSuccess() bool {
- return o.Code/100 == 2
+ const statusOK = 2
+ return o.Code/100 == statusOK
}
-// IsRedirect returns true when this elapse o k response returns a 3xx status code
+// IsRedirect returns true when this API response returns a 3xx status code.
func (o *APIError) IsRedirect() bool {
- return o.Code/100 == 3
+ const statusRedirect = 3
+ return o.Code/100 == statusRedirect
}
-// IsClientError returns true when this elapse o k response returns a 4xx status code
+// IsClientError returns true when this API response returns a 4xx status code.
func (o *APIError) IsClientError() bool {
- return o.Code/100 == 4
+ const statusClientError = 4
+ return o.Code/100 == statusClientError
}
-// IsServerError returns true when this elapse o k response returns a 5xx status code
+// IsServerError returns true when this API response returns a 5xx status code.
func (o *APIError) IsServerError() bool {
- return o.Code/100 == 5
+ const statusServerError = 5
+ return o.Code/100 == statusServerError
}
-// IsCode returns true when this elapse o k response returns a 4xx 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/test/tools/vendor/github.com/go-openapi/runtime/constants.go b/test/tools/vendor/github.com/go-openapi/runtime/constants.go
index 515969242c..80de6c8086 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/constants.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/constants.go
@@ -1,49 +1,38 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
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/test/tools/vendor/github.com/go-openapi/runtime/csv.go b/test/tools/vendor/github.com/go-openapi/runtime/csv.go
index c9597bcd6e..558d0cb99a 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/csv.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/csv.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -32,23 +21,24 @@ 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 {
o := csvOptsWithDefaults(opts)
- return ConsumerFunc(func(reader io.Reader, data interface{}) error {
+ return ConsumerFunc(func(reader io.Reader, data any) error {
if reader == nil {
return errors.New("CSVConsumer requires a reader")
}
@@ -168,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
@@ -181,7 +172,7 @@ func CSVConsumer(opts ...CSVOpt) Consumer {
func CSVProducer(opts ...CSVOpt) Producer {
o := csvOptsWithDefaults(opts)
- return ProducerFunc(func(writer io.Writer, data interface{}) error {
+ return ProducerFunc(func(writer io.Writer, data any) error {
if writer == nil {
return errors.New("CSVProducer requires a writer")
}
@@ -294,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/test/tools/vendor/github.com/go-openapi/runtime/csv_options.go b/test/tools/vendor/github.com/go-openapi/runtime/csv_options.go
index c16464c578..e778c64d1f 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/csv_options.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/csv_options.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package runtime
import (
@@ -5,7 +8,7 @@ import (
"io"
)
-// CSVOpts alter the behavior of the CSV consumer or producer.
+// CSVOpt alter the behavior of the CSV consumer or producer.
type CSVOpt func(*csvOpts)
type csvOpts struct {
@@ -15,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) {
@@ -23,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) {
@@ -91,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/test/tools/vendor/github.com/go-openapi/runtime/discard.go b/test/tools/vendor/github.com/go-openapi/runtime/discard.go
index 0d390cfd64..b05678becd 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/discard.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/discard.go
@@ -1,9 +1,12 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package runtime
import "io"
// DiscardConsumer does absolutely nothing, it's a black hole.
-var DiscardConsumer = ConsumerFunc(func(_ io.Reader, _ interface{}) error { return nil })
+var DiscardConsumer = ConsumerFunc(func(_ io.Reader, _ any) error { return nil })
// DiscardProducer does absolutely nothing, it's a black hole.
-var DiscardProducer = ProducerFunc(func(_ io.Writer, _ interface{}) error { return nil })
+var DiscardProducer = ProducerFunc(func(_ io.Writer, _ any) error { return nil })
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/doc.go b/test/tools/vendor/github.com/go-openapi/runtime/doc.go
new file mode 100644
index 0000000000..300c6b15f0
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/runtime/file.go b/test/tools/vendor/github.com/go-openapi/runtime/file.go
index 397d8a4593..2a85379a74 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/file.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/file.go
@@ -1,19 +1,8 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
-import "github.com/go-openapi/swag"
+import "github.com/go-openapi/swag/fileutils"
-type File = swag.File
+type File = fileutils.File
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/go.work b/test/tools/vendor/github.com/go-openapi/runtime/go.work
new file mode 100644
index 0000000000..b4cd9e01e8
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/runtime/go.work
@@ -0,0 +1,6 @@
+use (
+ .
+ ./client-middleware/opentracing
+)
+
+go 1.24.0
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/go.work.sum b/test/tools/vendor/github.com/go-openapi/runtime/go.work.sum
new file mode 100644
index 0000000000..b24a8cfaf9
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/runtime/go.work.sum
@@ -0,0 +1,109 @@
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/go-openapi/errors v0.22.2/go.mod h1:+n/5UdIqdVnLIJ6Q9Se8HNGUXYaY6CN8ImWzfi/Gzp0=
+github.com/go-openapi/jsonpointer v0.22.0/go.mod h1:xt3jV88UtExdIkkL7NloURjRQjbeUgcxFblMjq2iaiU=
+github.com/go-openapi/jsonreference v0.21.1/go.mod h1:PWs8rO4xxTUqKGu+lEvvCxD5k2X7QYkKAepJyCmSTT8=
+github.com/go-openapi/swag v0.24.1/go.mod h1:sm8I3lCPlspsBBwUm1t5oZeWZS0s7m/A+Psg0ooRU0A=
+github.com/go-openapi/swag/cmdutils v0.24.0/go.mod h1:uxib2FAeQMByyHomTlsP8h1TtPd54Msu2ZDU/H5Vuf8=
+github.com/go-openapi/swag/conv v0.24.0/go.mod h1:jbn140mZd7EW2g8a8Y5bwm8/Wy1slLySQQ0ND6DPc2c=
+github.com/go-openapi/swag/fileutils v0.24.0/go.mod h1:3SCrCSBHyP1/N+3oErQ1gP+OX1GV2QYFSnrTbzwli90=
+github.com/go-openapi/swag/jsonname v0.24.0/go.mod h1:GXqrPzGJe611P7LG4QB9JKPtUZ7flE4DOVechNaDd7Q=
+github.com/go-openapi/swag/jsonutils v0.24.0/go.mod h1:vBowZtF5Z4DDApIoxcIVfR8v0l9oq5PpYRUuteVu6f0=
+github.com/go-openapi/swag/loading v0.24.0/go.mod h1:gShCN4woKZYIxPxbfbyHgjXAhO61m88tmjy0lp/LkJk=
+github.com/go-openapi/swag/mangling v0.24.0/go.mod h1:Jm5Go9LHkycsz0wfoaBDkdc4CkpuSnIEf62brzyCbhc=
+github.com/go-openapi/swag/netutils v0.24.0/go.mod h1:WRgiHcYTnx+IqfMCtu0hy9oOaPR0HnPbmArSRN1SkZM=
+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=
+github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
+github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
+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=
+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-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=
+golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
+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=
+golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
+golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
+golang.org/x/net v0.45.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+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=
+golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
+golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
+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.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c=
+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/test/tools/vendor/github.com/go-openapi/runtime/headers.go b/test/tools/vendor/github.com/go-openapi/runtime/headers.go
index 4d111db4fe..4eb2b9254a 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/headers.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/headers.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -21,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/test/tools/vendor/github.com/go-openapi/runtime/interfaces.go b/test/tools/vendor/github.com/go-openapi/runtime/interfaces.go
index e334128683..a8b4b318d9 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/interfaces.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/interfaces.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -22,83 +11,83 @@ import (
"github.com/go-openapi/strfmt"
)
-// OperationHandlerFunc an adapter for a function to the OperationHandler interface
-type OperationHandlerFunc func(interface{}) (interface{}, error)
+// OperationHandlerFunc an adapter for a function to the [OperationHandler] interface.
+type OperationHandlerFunc func(any) (any, error)
-// Handle implements the operation handler interface
-func (s OperationHandlerFunc) Handle(data interface{}) (interface{}, error) {
+// 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(interface{}) (interface{}, error)
+ Handle(any) (any, error)
}
-// ConsumerFunc represents a function that can be used as a consumer
-type ConsumerFunc func(io.Reader, interface{}) error
+// 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
-func (fn ConsumerFunc) Consume(reader io.Reader, data interface{}) error {
+// 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, interface{}) error
+ Consume(io.Reader, any) error
}
-// ProducerFunc represents a function that can be used as a producer
-type ProducerFunc func(io.Writer, interface{}) error
+// 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
-func (f ProducerFunc) Produce(writer io.Writer, data interface{}) error {
+// 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, interface{}) error
+ Produce(io.Writer, any) error
}
-// AuthenticatorFunc turns a function into an authenticator
-type AuthenticatorFunc func(interface{}) (bool, interface{}, error)
+// AuthenticatorFunc turns a function into an authenticator.
+type AuthenticatorFunc func(any) (bool, any, error)
-// Authenticate authenticates the request with the provided data
-func (f AuthenticatorFunc) Authenticate(params interface{}) (bool, interface{}, error) {
+// 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(interface{}) (bool, interface{}, error)
+ Authenticate(any) (bool, any, error)
}
-// AuthorizerFunc turns a function into an authorizer
-type AuthorizerFunc func(*http.Request, interface{}) error
+// AuthorizerFunc turns a function into an authorizer.
+type AuthorizerFunc func(*http.Request, any) error
-// Authorize authorizes the processing of the request for the principal
-func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error {
+// 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, interface{}) error
+ Authorize(*http.Request, any) error
}
// 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
}
@@ -106,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/test/tools/vendor/github.com/go-openapi/runtime/json.go b/test/tools/vendor/github.com/go-openapi/runtime/json.go
index 5a690559cc..2af5dcfe46 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/json.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/json.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -19,18 +8,18 @@ import (
"io"
)
-// JSONConsumer creates a new JSON consumer
+// JSONConsumer creates a new JSON consumer.
func JSONConsumer() Consumer {
- return ConsumerFunc(func(reader io.Reader, data interface{}) error {
+ return ConsumerFunc(func(reader io.Reader, data any) error {
dec := json.NewDecoder(reader)
dec.UseNumber() // preserve number formats
return dec.Decode(data)
})
}
-// JSONProducer creates a new JSON producer
+// JSONProducer creates a new JSON producer.
func JSONProducer() Producer {
- return ProducerFunc(func(writer io.Writer, data interface{}) error {
+ return ProducerFunc(func(writer io.Writer, data any) error {
enc := json.NewEncoder(writer)
enc.SetEscapeHTML(false)
return enc.Encode(data)
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/logger/logger.go b/test/tools/vendor/github.com/go-openapi/runtime/logger/logger.go
index 6f4debcc14..45484deb59 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/logger/logger.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/logger/logger.go
@@ -1,10 +1,13 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package logger
import "os"
type Logger interface {
- Printf(format string, args ...interface{})
- Debugf(format string, args ...interface{})
+ Printf(format string, args ...any)
+ Debugf(format string, args ...any)
}
func DebugEnabled() bool {
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/logger/standard.go b/test/tools/vendor/github.com/go-openapi/runtime/logger/standard.go
index 30035a7777..48ba27f4a3 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/logger/standard.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/logger/standard.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package logger
import (
@@ -9,14 +12,14 @@ var _ Logger = StandardLogger{}
type StandardLogger struct{}
-func (StandardLogger) Printf(format string, args ...interface{}) {
+func (StandardLogger) Printf(format string, args ...any) {
if len(format) == 0 || format[len(format)-1] != '\n' {
format += "\n"
}
fmt.Fprintf(os.Stderr, format, args...)
}
-func (StandardLogger) Debugf(format string, args ...interface{}) {
+func (StandardLogger) Debugf(format string, args ...any) {
if len(format) == 0 || format[len(format)-1] != '\n' {
format += "\n"
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/context.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/context.go
index 44cecf1181..1f85e86b53 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/context.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/context.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
@@ -35,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) {
@@ -54,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
@@ -126,7 +117,7 @@ func newRoutableUntypedAPI(spec *loads.Document, api *untyped.API, context *Cont
}
// bind and validate the request using reflection
- var bound interface{}
+ var bound any
var validation error
bound, r, validation = context.BindAndValidate(r, route)
if validation != nil {
@@ -203,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 {
@@ -213,13 +204,13 @@ 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)) {
- panic(errors.New(http.StatusInternalServerError, "routable context requires either both spec doc and analysis, or none of them"))
+ if (spec != nil || an != nil) && (spec == nil || an == nil) {
+ panic(fmt.Errorf("%d: %s", http.StatusInternalServerError, "routable context requires either both spec doc and analysis, or none of them"))
}
return &Context{
@@ -233,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 {
@@ -250,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)
@@ -287,7 +278,7 @@ func MatchedRouteFrom(req *http.Request) *MatchedRoute {
}
// SecurityPrincipalFrom request context value.
-func SecurityPrincipalFrom(req *http.Request) interface{} {
+func SecurityPrincipalFrom(req *http.Request) any {
return req.Context().Value(ctxSecurityPrincipal)
}
@@ -305,8 +296,11 @@ 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 ""
+ }
return c.spec.BasePath()
}
@@ -317,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
@@ -341,7 +335,7 @@ func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, b
if len(res) == 0 {
cons, ok := route.Consumers[ct]
if !ok {
- res = append(res, errors.New(500, "no consumer registered for %s", ct))
+ res = append(res, errors.New(http.StatusInternalServerError, "no consumer registered for %s", ct))
} else {
route.Consumer = cons
requestContentType = ct
@@ -382,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()
@@ -398,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
@@ -410,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()
@@ -428,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()
@@ -446,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)
@@ -462,8 +456,8 @@ 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
-func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interface{}, *http.Request, 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
}
@@ -486,7 +480,7 @@ func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interfa
return nil, nil, err
}
- return nil, nil, errors.New(http.StatusForbidden, err.Error())
+ return nil, nil, errors.New(http.StatusForbidden, "%v", err)
}
}
@@ -500,8 +494,8 @@ func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interfa
// 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
-func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (interface{}, *http.Request, error) {
+// CompositeValidationError error.
+func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (any, *http.Request, error) {
var rCtx = request.Context()
if v, ok := rCtx.Value(ctxBoundParams).(*validation); ok {
@@ -521,13 +515,13 @@ 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
-func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data interface{}) {
+// 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{}
for _, mt := range produces {
@@ -552,7 +546,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
prods := c.api.ProducersFor(normalizeOffers([]string{c.api.DefaultProduces()}))
pr, ok := prods[c.api.DefaultProduces()]
if !ok {
- panic(errors.New(http.StatusInternalServerError, cantFindProducer(format)))
+ panic(fmt.Errorf("%d: %s", http.StatusInternalServerError, cantFindProducer(format)))
}
prod = pr
}
@@ -585,7 +579,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
producers := c.api.ProducersFor(normalizeOffers(offers))
prod, ok := producers[format]
if !ok {
- panic(errors.New(http.StatusInternalServerError, cantFindProducer(format)))
+ panic(fmt.Errorf("%d: %s", http.StatusInternalServerError, cantFindProducer(format)))
}
if err := prod.Produce(rw, data); err != nil {
panic(err) // let the recovery middleware deal with this
@@ -606,7 +600,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
prods := c.api.ProducersFor(normalizeOffers([]string{c.api.DefaultProduces()}))
pr, ok := prods[c.api.DefaultProduces()]
if !ok {
- panic(errors.New(http.StatusInternalServerError, cantFindProducer(format)))
+ panic(fmt.Errorf("%d: %s", http.StatusInternalServerError, cantFindProducer(format)))
}
prod = pr
}
@@ -617,14 +611,14 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
return
}
- c.api.ServeErrorFor(route.Operation.ID)(rw, r, errors.New(http.StatusInternalServerError, "can't produce response"))
+ c.api.ServeErrorFor(route.Operation.ID)(rw, r, fmt.Errorf("%d: %s", http.StatusInternalServerError, "can't produce response"))
}
// APIHandlerSwaggerUI returns a handler to serve the API.
//
// 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
@@ -643,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
@@ -662,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
@@ -677,6 +671,15 @@ 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.
+func (c *Context) RoutesHandler(builder Builder) http.Handler {
+ b := builder
+ if b == nil {
+ b = PassthroughBuilder
+ }
+ return NewRouter(c, b(NewOperationExecutor(c)))
+}
+
func (c Context) uiOptionsForHandler(opts []UIOption) (string, uiOptions, []SpecOption) {
var title string
sp := c.spec.Spec()
@@ -685,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)
@@ -708,15 +713,6 @@ func (c Context) uiOptionsForHandler(opts []UIOption) (string, uiOptions, []Spec
return pth, uiOpts, []SpecOption{WithSpecDocument(doc)}
}
-// 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 {
- b = PassthroughBuilder
- }
- return NewRouter(c, b(NewOperationExecutor(c)))
-}
-
func cantFindProducer(format string) string {
return "can't find a producer for " + format
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/README.md b/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/README.md
index 30109e17d5..03e0b7f4e3 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/README.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/router.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/router.go
index 4377f77a46..f89d761cf2 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/router.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/router.go
@@ -1,3 +1,8 @@
+// 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
@@ -21,11 +26,11 @@ 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.
- MaxSize = (1 << 22) - 1
+ MaxSize = (1 << 22) - 1 //nolint:mnd
)
// Router represents a URL router.
@@ -36,22 +41,22 @@ type Router struct {
// By default, SizeHint will be determined from given records to Build.
SizeHint int
- static map[string]interface{}
+ static map[string]any
}
// New returns a new Router.
func New() *Router {
return &Router{
SizeHint: -1,
- static: make(map[string]interface{}),
+ static: make(map[string]any),
param: newDoubleArray(),
}
}
// 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 interface{}, params Params, found bool) {
+func (rt *Router) Lookup(path string) (data any, params Params, found bool) {
if data, found = rt.static[path]; found {
return data, nil, true
}
@@ -62,7 +67,7 @@ func (rt *Router) Lookup(path string) (data interface{}, params Params, found bo
if !found {
return nil, nil, false
}
- for i := 0; i < len(params); i++ {
+ for i := range params {
params[i].Name = nd.paramNames[i]
}
return nd.data, params, true
@@ -135,19 +140,24 @@ func newDoubleArray() *doubleArray {
// BASE (22bit) | Extra flags (2bit) | CHECK (8bit)
//
// |----------------------|--|--------|
-// 32 10 8 0
+// 32 10 8 0.
type baseCheck uint32
+const (
+ flagsBits = 10
+ checkBits = 8
+)
+
func (bc baseCheck) Base() int {
- return int(bc >> 10)
+ return int(bc >> flagsBits)
}
func (bc *baseCheck) SetBase(base int) {
- *bc |= baseCheck(base) << 10
+ *bc |= baseCheck(base) << flagsBits //nolint:gosec // integer conversion is ok
}
func (bc baseCheck) Check() byte {
- return byte(bc)
+ return byte(bc) //nolint:gosec // integer conversion is ok
}
func (bc *baseCheck) SetCheck(check byte) {
@@ -171,24 +181,27 @@ func (bc baseCheck) IsAnyParam() bool {
}
func (bc *baseCheck) SetSingleParam() {
- *bc |= (1 << 8)
+ *bc |= (1 << checkBits)
}
func (bc *baseCheck) SetWildcardParam() {
- *bc |= (1 << 9)
+ *bc |= (1 << (checkBits + 1))
}
const (
paramTypeSingle = 0x0100
paramTypeWildcard = 0x0200
paramTypeAny = 0x0300
+
+ indexOffset = 32
+ indexMask = uint64(0xffffffff)
)
func (da *doubleArray) lookup(path string, params []Param, idx int) (*node, []Param, bool) {
indices := make([]uint64, 0, 1)
- for i := 0; i < len(path); i++ {
+ for i := range len(path) {
if da.bc[idx].IsAnyParam() {
- indices = append(indices, (uint64(i)<<32)|(uint64(idx)&0xffffffff))
+ indices = append(indices, (uint64(i)<= len(da.bc) || da.bc[idx].Check() != c {
@@ -201,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]>>32), int(indices[j]&0xffffffff)
+ 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) {
@@ -340,7 +353,7 @@ func (da *doubleArray) arrange(records []*record, idx, depth int, usedBase map[i
// node represents a node of Double-Array.
type node struct {
- data interface{}
+ data any
// Names of path parameters.
paramNames []string
@@ -414,11 +427,11 @@ type Record struct {
Key string
// Result value for Key.
- Value interface{}
+ Value any
}
// NewRecord returns a new Record.
-func NewRecord(key string, value interface{}) Record {
+func NewRecord(key string, value any) Record {
return Record{
Key: key,
Value: value,
@@ -428,6 +441,7 @@ func NewRecord(key string, value interface{}) Record {
// record represents a record that use to build the Double-Array.
type record struct {
Record
+
paramNames []string
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/server.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/server.go
index 0886713c18..e6c0976d8b 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/server.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/server.go
@@ -1,3 +1,8 @@
+// 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
import (
@@ -7,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)
}
@@ -41,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 {
@@ -70,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/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/util.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/util.go
index edc1f6ab80..e7da422623 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/util.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/denco/util.go
@@ -1,3 +1,8 @@
+// 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
// NextSeparator returns an index of next separator in path.
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/doc.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/doc.go
index 836a98850d..f78ec52c79 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/doc.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/doc.go
@@ -1,63 +1,50 @@
-// Copyright 2015 go-swagger maintainers
+// 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.
//
-// 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
+// Pseudo middleware handler.
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// import (
+// "net/http"
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-/*
-Package 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))
- })
- }
-*/
+// "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/test/tools/vendor/github.com/go-openapi/runtime/middleware/header/header.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/header/header.go
index df073c87d9..6ce870d893 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/header/header.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/header/header.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
// Copyright 2013 The Go Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
@@ -10,6 +13,7 @@
package header
import (
+ "maps"
"net/http"
"strings"
"time"
@@ -25,6 +29,11 @@ const (
isSpace
)
+const (
+ asciiMaxControlChar = 31
+ asciiMaxChar = 127
+)
+
func init() {
// OCTET =
// CHAR =
@@ -42,10 +51,10 @@ func init() {
// token = 1*
// qdtext = >
- for c := 0; c < 256; c++ {
+ for c := range 256 {
var t octetType
- isCtl := c <= 31 || c == 127
- isChar := 0 <= c && c <= 127
+ isCtl := c <= asciiMaxControlChar || c == asciiMaxChar
+ isChar := 0 <= c && c <= asciiMaxChar
isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c))
if strings.ContainsRune(" \t\r\n", rune(c)) {
t |= isSpace
@@ -60,9 +69,7 @@ func init() {
// Copy returns a shallow copy of the header.
func Copy(header http.Header) http.Header {
h := make(http.Header)
- for k, vs := range header {
- h[k] = vs
- }
+ maps.Copy(h, header)
return h
}
@@ -92,7 +99,7 @@ func ParseList(header http.Header, key string) []string {
end := 0
escape := false
quote := false
- for i := 0; i < len(s); i++ {
+ for i := range len(s) {
b := s[i]
switch {
case escape:
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/negotiate.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/negotiate.go
index a9b6f27d3d..cb0a85283c 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/negotiate.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/negotiate.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
// Copyright 2013 The Go Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
@@ -94,5 +97,6 @@ func normalizeOffers(orig []string) (norm []string) {
}
func normalizeOffer(orig string) string {
- return strings.SplitN(orig, ";", 2)[0]
+ const maxParts = 2
+ return strings.SplitN(orig, ";", maxParts)[0]
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go
index bc6942a0f1..4d286a6c8c 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
@@ -22,7 +11,7 @@ import (
type errorResp struct {
code int
- response interface{}
+ response any
headers http.Header
}
@@ -42,14 +31,14 @@ 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
-func Error(code int, data interface{}, headers ...http.Header) Responder {
+// 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 {
for k, v := range h {
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/operation.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/operation.go
index 1175a63cf2..24f466b597 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/operation.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/operation.go
@@ -1,22 +1,11 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
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/test/tools/vendor/github.com/go-openapi/runtime/middleware/parameter.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/parameter.go
index 9c3353a95c..a9d2a36460 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/parameter.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/parameter.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
@@ -24,12 +13,12 @@ import (
"strconv"
"github.com/go-openapi/errors"
+ "github.com/go-openapi/runtime"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/conv"
+ "github.com/go-openapi/swag/stringutils"
"github.com/go-openapi/validate"
-
- "github.com/go-openapi/runtime"
)
const defaultMaxMemory = 32 << 20
@@ -39,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)
@@ -66,85 +55,6 @@ func (p *untypedParamBinder) Type() reflect.Type {
return p.typeForSchema(p.parameter.Type, p.parameter.Format, p.parameter.Items)
}
-func (p *untypedParamBinder) typeForSchema(tpe, format string, items *spec.Items) reflect.Type {
- switch tpe {
- case "boolean":
- return reflect.TypeOf(true)
-
- case typeString:
- if tt, ok := p.formats.GetType(format); ok {
- return tt
- }
- return reflect.TypeOf("")
-
- case "integer":
- switch format {
- case "int8":
- return reflect.TypeOf(int8(0))
- case "int16":
- return reflect.TypeOf(int16(0))
- case "int32":
- return reflect.TypeOf(int32(0))
- case "int64":
- return reflect.TypeOf(int64(0))
- default:
- return reflect.TypeOf(int64(0))
- }
-
- case "number":
- switch format {
- case "float":
- return reflect.TypeOf(float32(0))
- case "double":
- return reflect.TypeOf(float64(0))
- }
-
- case typeArray:
- if items == nil {
- return nil
- }
- itemsType := p.typeForSchema(items.Type, items.Format, items.Items)
- if itemsType == nil {
- return nil
- }
- return reflect.MakeSlice(reflect.SliceOf(itemsType), 0, 0).Type()
-
- case "file":
- return reflect.TypeOf(&runtime.File{}).Elem()
-
- case "object":
- return reflect.TypeOf(map[string]interface{}{})
- }
- return nil
-}
-
-func (p *untypedParamBinder) allowsMulti() bool {
- return p.parameter.In == "query" || p.parameter.In == "formData"
-}
-
-func (p *untypedParamBinder) readValue(values runtime.Gettable, target reflect.Value) ([]string, bool, bool, error) {
- name, in, cf, tpe := p.parameter.Name, p.parameter.In, p.parameter.CollectionFormat, p.parameter.Type
- if tpe == typeArray {
- if cf == "multi" {
- if !p.allowsMulti() {
- return nil, false, false, errors.InvalidCollectionFormat(name, in, cf)
- }
- vv, hasKey, _ := values.GetOK(name)
- return vv, false, hasKey, nil
- }
-
- v, hk, hv := values.GetOK(name)
- if !hv {
- return nil, false, hk, nil
- }
- d, c, e := p.readFormattedSliceFieldValue(v[len(v)-1], target)
- return d, c, hk, e
- }
-
- vv, hk, _ := values.GetOK(name)
- return vv, false, hk, nil
-}
-
func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, target reflect.Value) error {
// fmt.Println("binding", p.name, "as", p.Type())
switch p.parameter.In {
@@ -264,10 +174,89 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams
target.Set(reflect.Indirect(newValue))
return nil
default:
- return errors.New(500, fmt.Sprintf("invalid parameter location %q", p.parameter.In))
+ return fmt.Errorf("%d: invalid parameter location %q", http.StatusInternalServerError, p.parameter.In)
}
}
+func (p *untypedParamBinder) typeForSchema(tpe, format string, items *spec.Items) reflect.Type {
+ switch tpe {
+ case "boolean":
+ return reflect.TypeFor[bool]()
+
+ case typeString:
+ if tt, ok := p.formats.GetType(format); ok {
+ return tt
+ }
+ return reflect.TypeFor[string]()
+
+ case "integer":
+ switch format {
+ case "int8":
+ return reflect.TypeFor[int8]()
+ case "int16":
+ return reflect.TypeFor[int16]()
+ case "int32":
+ return reflect.TypeFor[int32]()
+ case "int64":
+ return reflect.TypeFor[int64]()
+ default:
+ return reflect.TypeFor[int64]()
+ }
+
+ case "number":
+ switch format {
+ case "float":
+ return reflect.TypeFor[float32]()
+ case "double":
+ return reflect.TypeFor[float64]()
+ }
+
+ case typeArray:
+ if items == nil {
+ return nil
+ }
+ itemsType := p.typeForSchema(items.Type, items.Format, items.Items)
+ if itemsType == nil {
+ return nil
+ }
+ return reflect.MakeSlice(reflect.SliceOf(itemsType), 0, 0).Type()
+
+ case "file":
+ return reflect.TypeFor[runtime.File]()
+
+ case "object":
+ return reflect.TypeFor[map[string]any]()
+ }
+ return nil
+}
+
+func (p *untypedParamBinder) allowsMulti() bool {
+ return p.parameter.In == "query" || p.parameter.In == "formData"
+}
+
+func (p *untypedParamBinder) readValue(values runtime.Gettable, target reflect.Value) ([]string, bool, bool, error) {
+ name, in, cf, tpe := p.parameter.Name, p.parameter.In, p.parameter.CollectionFormat, p.parameter.Type
+ if tpe == typeArray {
+ if cf == "multi" {
+ if !p.allowsMulti() {
+ return nil, false, false, errors.InvalidCollectionFormat(name, in, cf)
+ }
+ vv, hasKey, _ := values.GetOK(name)
+ return vv, false, hasKey, nil
+ }
+
+ v, hk, hv := values.GetOK(name)
+ if !hv {
+ return nil, false, hk, nil
+ }
+ d, c, e := p.readFormattedSliceFieldValue(v[len(v)-1], target)
+ return d, c, hk, e
+ }
+
+ vv, hk, _ := values.GetOK(name)
+ return vv, false, hk, nil
+}
+
func (p *untypedParamBinder) bindValue(data []string, hasKey bool, target reflect.Value) error {
if p.parameter.Type == typeArray {
return p.setSliceFieldValue(target, p.parameter.Default, data, hasKey)
@@ -279,7 +268,7 @@ func (p *untypedParamBinder) bindValue(data []string, hasKey bool, target reflec
return p.setFieldValue(target, p.parameter.Default, d, hasKey)
}
-func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue interface{}, data string, hasKey bool) error { //nolint:gocyclo
+func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue any, data string, hasKey bool) error { //nolint:gocyclo
tpe := p.parameter.Type
if p.parameter.Format != "" {
tpe = p.parameter.Format
@@ -331,7 +320,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in
}
return nil
}
- b, err := swag.ConvertBool(data)
+ b, err := conv.ConvertBool(data)
if err != nil {
return err
}
@@ -341,7 +330,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if data == "" {
if target.CanSet() {
- rd := defVal.Convert(reflect.TypeOf(int64(0)))
+ rd := defVal.Convert(reflect.TypeFor[int64]())
target.SetInt(rd.Int())
}
return nil
@@ -360,7 +349,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if data == "" {
if target.CanSet() {
- rd := defVal.Convert(reflect.TypeOf(uint64(0)))
+ rd := defVal.Convert(reflect.TypeFor[uint64]())
target.SetUint(rd.Uint())
}
return nil
@@ -379,7 +368,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in
case reflect.Float32, reflect.Float64:
if data == "" {
if target.CanSet() {
- rd := defVal.Convert(reflect.TypeOf(float64(0)))
+ rd := defVal.Convert(reflect.TypeFor[float64]())
target.SetFloat(rd.Float())
}
return nil
@@ -426,12 +415,12 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in
return nil
}
-func (p *untypedParamBinder) tryUnmarshaler(target reflect.Value, defaultValue interface{}, data string) (bool, error) {
+func (p *untypedParamBinder) tryUnmarshaler(target reflect.Value, defaultValue any, data string) (bool, error) {
if !target.CanSet() {
return false, nil
}
// When a type implements encoding.TextUnmarshaler we'll use that instead of reflecting some more
- if reflect.PtrTo(target.Type()).Implements(textUnmarshalType) {
+ if reflect.PointerTo(target.Type()).Implements(textUnmarshalType) {
if defaultValue != nil && len(data) == 0 {
target.Set(reflect.ValueOf(defaultValue))
return true, nil
@@ -455,10 +444,10 @@ func (p *untypedParamBinder) readFormattedSliceFieldValue(data string, target re
return nil, true, nil
}
- return swag.SplitByFormat(data, p.parameter.CollectionFormat), false, nil
+ return stringutils.SplitByFormat(data, p.parameter.CollectionFormat), false, nil
}
-func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue interface{}, data []string, hasKey bool) error {
+func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue any, data []string, hasKey bool) error {
sz := len(data)
if (!hasKey || (!p.parameter.AllowEmptyValue && (sz == 0 || (sz == 1 && data[0] == "")))) && p.parameter.Required && defaultValue == nil {
return errors.Required(p.Name, p.parameter.In, data)
@@ -479,7 +468,7 @@ func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultVal
value := reflect.MakeSlice(reflect.SliceOf(target.Type().Elem()), sz, sz)
- for i := 0; i < sz; i++ {
+ for i := range sz {
if err := p.setFieldValue(value.Index(i), nil, data[i], hasKey); err != nil {
return err
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go
index ef75e7441f..1574defb41 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package middleware
import (
@@ -8,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
@@ -47,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/test/tools/vendor/github.com/go-openapi/runtime/middleware/redoc.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/redoc.go
index b96b01e7f3..1007409a30 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/redoc.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/redoc.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package middleware
import (
@@ -8,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
@@ -33,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()
@@ -48,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/test/tools/vendor/github.com/go-openapi/runtime/middleware/request.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/request.go
index 82e1436652..ad781663b8 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/request.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/request.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
@@ -25,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
@@ -49,8 +38,8 @@ func NewUntypedRequestBinder(parameters map[string]spec.Parameter, spec *spec.Sw
}
}
-// Bind perform the databinding and validation
-func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, data interface{}) error {
+// 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
var result []error
@@ -68,16 +57,16 @@ func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RoutePara
tpe := binder.Type()
if tpe == nil {
if param.Schema.Type.Contains(typeArray) {
- tpe = reflect.TypeOf([]interface{}{})
+ tpe = reflect.TypeFor[[]any]()
} else {
- tpe = reflect.TypeOf(map[string]interface{}{})
+ tpe = reflect.TypeFor[map[string]any]()
}
}
target = reflect.Indirect(reflect.New(tpe))
}
if !target.IsValid() {
- result = append(result, errors.New(500, "parameter name %q is an unknown field", binder.Name))
+ result = append(result, errors.New(http.StatusInternalServerError, "parameter name %q is an unknown field", binder.Name))
continue
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/router.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/router.go
index 3a6aee90e5..e828653be7 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/router.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/router.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
@@ -22,32 +11,30 @@ import (
"regexp"
"strings"
- "github.com/go-openapi/runtime/logger"
- "github.com/go-openapi/runtime/security"
- "github.com/go-openapi/swag"
-
"github.com/go-openapi/analysis"
"github.com/go-openapi/errors"
"github.com/go-openapi/loads"
+ "github.com/go-openapi/runtime"
+ "github.com/go-openapi/runtime/logger"
+ "github.com/go-openapi/runtime/middleware/denco"
+ "github.com/go-openapi/runtime/security"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
-
- "github.com/go-openapi/runtime"
- "github.com/go-openapi/runtime/middleware/denco"
+ "github.com/go-openapi/swag/stringutils"
)
// 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 {
@@ -57,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 {
@@ -69,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))
@@ -81,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)
@@ -105,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
@@ -166,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 {
@@ -183,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
@@ -198,25 +189,25 @@ 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
-func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
+// Authenticate Authenticator interface implementation.
+func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, any, error) {
if ra.allowAnonymous {
route.Authenticator = ra
return true, nil, nil
}
// iterate in proper order
- var lastResult interface{}
+ var lastResult any
for _, scheme := range ra.Schemes {
if authenticator, ok := ra.Authenticator[scheme]; ok {
applies, princ, err := authenticator.Authenticate(&security.ScopedAuthRequest{
@@ -275,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() {
@@ -288,8 +279,8 @@ func (ras RouteAuthenticators) AllowsAnonymous() bool {
return false
}
-// Authenticate method implemention so this collection can be used as authenticator
-func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
+// 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
var anonAuth RouteAuthenticator
@@ -333,22 +324,23 @@ 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
+
Params RouteParams
Consumer runtime.Consumer
Producer runtime.Producer
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
}
@@ -377,7 +369,8 @@ func (d *defaultRouter) Lookup(method, path string) (*MatchedRoute, bool) {
}
// a workaround to handle fragment/composing parameters until they are supported in denco router
// check if this parameter is a fragment within a path segment
- if xpos := strings.Index(entry.PathPattern, fmt.Sprintf("{%s}", p.Name)) + len(p.Name) + 2; xpos < len(entry.PathPattern) && entry.PathPattern[xpos] != '/' {
+ const enclosureSize = 2
+ if xpos := strings.Index(entry.PathPattern, fmt.Sprintf("{%s}", p.Name)) + len(p.Name) + enclosureSize; xpos < len(entry.PathPattern) && entry.PathPattern[xpos] != '/' {
// extract fragment parameters
ep := strings.Split(entry.PathPattern[xpos:], "/")[0]
pnames, pvalues := decodeCompositParams(p.Name, v, ep, nil, nil)
@@ -418,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) {
@@ -460,11 +453,11 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper
parameters := d.analyzer.ParamsFor(method, strings.TrimPrefix(path, bp))
// add API defaults if not part of the spec
- if defConsumes := d.api.DefaultConsumes(); defConsumes != "" && !swag.ContainsStringsCI(consumes, defConsumes) {
+ if defConsumes := d.api.DefaultConsumes(); defConsumes != "" && !stringutils.ContainsStringsCI(consumes, defConsumes) {
consumes = append(consumes, defConsumes)
}
- if defProduces := d.api.DefaultProduces(); defProduces != "" && !swag.ContainsStringsCI(produces, defProduces) {
+ if defProduces := d.api.DefaultProduces(); defProduces != "" && !stringutils.ContainsStringsCI(produces, defProduces) {
produces = append(produces, defProduces)
}
@@ -489,6 +482,20 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper
}
}
+func (d *defaultRouteBuilder) Build() *defaultRouter {
+ routers := make(map[string]*denco.Router)
+ for method, records := range d.records {
+ router := denco.New()
+ _ = router.Build(records)
+ routers[method] = router
+ }
+ return &defaultRouter{
+ spec: d.spec,
+ routers: routers,
+ debugLogf: d.debugLogf,
+ }
+}
+
func (d *defaultRouteBuilder) buildAuthenticators(operation *spec.Operation) RouteAuthenticators {
requirements := d.analyzer.SecurityRequirementsFor(operation)
auths := make([]RouteAuthenticator, 0, len(requirements))
@@ -515,17 +522,3 @@ func (d *defaultRouteBuilder) buildAuthenticators(operation *spec.Operation) Rou
}
return auths
}
-
-func (d *defaultRouteBuilder) Build() *defaultRouter {
- routers := make(map[string]*denco.Router)
- for method, records := range d.records {
- router := denco.New()
- _ = router.Build(records)
- routers[method] = router
- }
- return &defaultRouter{
- spec: d.spec,
- routers: routers,
- debugLogf: d.debugLogf,
- }
-}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/security.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/security.go
index 2b061caefc..37ecfa6fd4 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/security.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/security.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/spec.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/spec.go
index 87e17e3424..0a64a9572b 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/spec.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/spec.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
@@ -24,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{
@@ -46,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 = "/"
@@ -79,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 {
@@ -90,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/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go
index ec3c10cbaf..14ed37ced6 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package middleware
import (
@@ -8,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
@@ -44,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()
@@ -87,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/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go
index e81212f71c..879bdbaade 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package middleware
import (
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/ui_options.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/ui_options.go
index b86efa0089..ed255426ad 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/ui_options.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/ui_options.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package middleware
import (
@@ -10,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"
@@ -39,7 +42,7 @@ type uiOptions struct {
// toCommonUIOptions converts any UI option type to retain the common options.
//
// This uses gob encoding/decoding to convert common fields from one struct to another.
-func toCommonUIOptions(opts interface{}) uiOptions {
+func toCommonUIOptions(opts any) uiOptions {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
dec := gob.NewDecoder(&buf)
@@ -72,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 {
@@ -87,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, "/") {
@@ -108,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
@@ -117,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
@@ -126,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 = "/"
@@ -168,6 +171,6 @@ func serveUI(pth string, assets []byte, next http.Handler) http.Handler {
rw.Header().Set(contentTypeHeader, "text/plain")
rw.WriteHeader(http.StatusNotFound)
- _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
+ _, _ = fmt.Fprintf(rw, "%q not found", pth)
})
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go
index 7b7269bd19..f4c966bacd 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package untyped
@@ -29,27 +18,12 @@ import (
"github.com/go-openapi/runtime"
)
-// NewAPI creates the default untyped API
-func NewAPI(spec *loads.Document) *API {
- var an *analysis.Spec
- if spec != nil && spec.Spec() != nil {
- an = analysis.New(spec.Spec())
- }
- api := &API{
- spec: spec,
- analyzer: an,
- consumers: make(map[string]runtime.Consumer, 10),
- producers: make(map[string]runtime.Producer, 10),
- authenticators: make(map[string]runtime.Authenticator),
- operations: make(map[string]map[string]runtime.OperationHandler),
- ServeError: errors.ServeError,
- Models: make(map[string]func() interface{}),
- formats: strfmt.NewFormats(),
- }
- return api.WithJSONDefaults()
-}
+const (
+ smallPreallocatedSlots = 10
+ 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
@@ -61,11 +35,32 @@ type API struct {
authorizer runtime.Authorizer
operations map[string]map[string]runtime.OperationHandler
ServeError func(http.ResponseWriter, *http.Request, error)
- Models map[string]func() interface{}
+ Models map[string]func() any
formats strfmt.Registry
}
-// WithJSONDefaults loads the json defaults for this api
+// NewAPI creates the default untyped API.
+func NewAPI(spec *loads.Document) *API {
+ var an *analysis.Spec
+ if spec != nil && spec.Spec() != nil {
+ an = analysis.New(spec.Spec())
+ }
+ api := &API{
+ spec: spec,
+ analyzer: an,
+ consumers: make(map[string]runtime.Consumer, smallPreallocatedSlots),
+ producers: make(map[string]runtime.Producer, smallPreallocatedSlots),
+ authenticators: make(map[string]runtime.Authenticator),
+ operations: make(map[string]map[string]runtime.OperationHandler),
+ ServeError: errors.ServeError,
+ Models: make(map[string]func() any),
+ formats: strfmt.NewFormats(),
+ }
+
+ return api.WithJSONDefaults()
+}
+
+// WithJSONDefaults loads the json defaults for this api.
func (d *API) WithJSONDefaults() *API {
d.DefaultConsumes = runtime.JSONMime
d.DefaultProduces = runtime.JSONMime
@@ -74,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 = ""
@@ -83,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()
@@ -91,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()
@@ -99,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)
@@ -107,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,23 +110,23 @@ func (d *API) RegisterAuthorizer(handler runtime.Authorizer) {
// RegisterConsumer registers a consumer for a media type.
func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) {
if d.consumers == nil {
- d.consumers = make(map[string]runtime.Consumer, 10)
+ d.consumers = make(map[string]runtime.Consumer, smallPreallocatedSlots)
}
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, 10)
+ d.producers = make(map[string]runtime.Producer, smallPreallocatedSlots)
}
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, 30)
+ d.operations = make(map[string]map[string]runtime.OperationHandler, mediumPreallocatedSlots)
}
um := strings.ToUpper(method)
if b, ok := d.operations[um]; !ok || b == nil {
@@ -140,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
@@ -152,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 {
@@ -163,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 {
@@ -174,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 {
@@ -185,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/test/tools/vendor/github.com/go-openapi/runtime/middleware/validation.go b/test/tools/vendor/github.com/go-openapi/runtime/middleware/validation.go
index 0a5356c607..8a56490639 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/middleware/validation.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/middleware/validation.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package middleware
@@ -20,9 +9,8 @@ import (
"strings"
"github.com/go-openapi/errors"
- "github.com/go-openapi/swag"
-
"github.com/go-openapi/runtime"
+ "github.com/go-openapi/swag/stringutils"
)
type validation struct {
@@ -30,10 +18,10 @@ type validation struct {
result []error
request *http.Request
route *MatchedRoute
- bound map[string]interface{}
+ 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
@@ -42,14 +30,14 @@ func validateContentType(allowed []string, actual string) error {
if err != nil {
return errors.InvalidContentType(actual, allowed)
}
- if swag.ContainsStringsCI(allowed, mt) {
+ if stringutils.ContainsStringsCI(allowed, mt) {
return nil
}
- if swag.ContainsStringsCI(allowed, "*/*") {
+ if stringutils.ContainsStringsCI(allowed, "*/*") {
return nil
}
parts := strings.Split(actual, "/")
- if len(parts) == 2 && swag.ContainsStringsCI(allowed, parts[0]+"/*") {
+ if len(parts) == 2 && stringutils.ContainsStringsCI(allowed, parts[0]+"/*") {
return nil
}
return errors.InvalidContentType(actual, allowed)
@@ -60,7 +48,7 @@ func validateRequest(ctx *Context, request *http.Request, route *MatchedRoute) *
context: ctx,
request: request,
route: route,
- bound: make(map[string]interface{}),
+ bound: make(map[string]any),
}
validate.debugLogf("validating request %s %s", request.Method, request.URL.EscapedPath())
@@ -83,7 +71,7 @@ func (v *validation) parameters() {
v.debugLogf("validating request parameters for %s %s", v.request.Method, v.request.URL.EscapedPath())
if result := v.route.Binder.Bind(v.request, v.route.Params, v.route.Consumer, v.bound); result != nil {
if result.Error() == "validation failure list" {
- for _, e := range result.(*errors.Validation).Value.([]interface{}) {
+ for _, e := range result.(*errors.Validation).Value.([]any) {
v.result = append(v.result, e.(error))
}
return
@@ -111,7 +99,7 @@ func (v *validation) contentType() {
if ct != "" && v.route.Consumer == nil {
cons, ok := v.route.Consumers[ct]
if !ok {
- v.result = append(v.result, errors.New(500, "no consumer registered for %s", ct))
+ v.result = append(v.result, errors.New(http.StatusInternalServerError, "no consumer registered for %s", ct))
} else {
v.route.Consumer = cons
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/request.go b/test/tools/vendor/github.com/go-openapi/runtime/request.go
index 9e3e1ecb14..5c45339aa4 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/request.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/request.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -22,35 +11,35 @@ import (
"net/http"
"strings"
- "github.com/go-openapi/swag"
+ "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 {
return true
}
- if r.Header.Get("content-length") != "" {
+ if r.Header.Get("Content-Length") != "" {
// in this case, no Transfer-Encoding should be present
// we have a header set but it was explicitly set to 0, so we assume no body
return false
@@ -115,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 {
@@ -128,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 {
@@ -142,8 +131,8 @@ 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 swag.SplitByFormat(v, collectionFormat)
+ return stringutils.SplitByFormat(v, collectionFormat)
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/security/authenticator.go b/test/tools/vendor/github.com/go-openapi/runtime/security/authenticator.go
index bb30472bbe..4c09101826 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/security/authenticator.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/security/authenticator.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package security
@@ -30,9 +19,9 @@ const (
accessTokenParam = "access_token"
)
-// HttpAuthenticator is a function that authenticates a HTTP request
-func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator { //nolint:revive,stylecheck
- return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
+// 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 {
return handler(request)
}
@@ -43,9 +32,9 @@ func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) r
})
}
-// ScopedAuthenticator is a function that authenticates a HTTP request against a list of valid scopes
-func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, error)) runtime.Authenticator {
- return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
+// 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 {
return handler(request)
}
@@ -53,23 +42,23 @@ func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, er
})
}
-// UserPassAuthentication authentication function
-type UserPassAuthentication func(string, string) (interface{}, error)
+// UserPassAuthentication authentication function.
+type UserPassAuthentication func(string, string) (any, error)
-// UserPassAuthenticationCtx authentication function with context.Context
-type UserPassAuthenticationCtx func(context.Context, string, string) (context.Context, interface{}, error)
+// UserPassAuthenticationCtx authentication function with [context.Context].
+type UserPassAuthenticationCtx func(context.Context, string, string) (context.Context, any, error)
-// TokenAuthentication authentication function
-type TokenAuthentication func(string) (interface{}, error)
+// TokenAuthentication authentication function.
+type TokenAuthentication func(string) (any, error)
-// TokenAuthenticationCtx authentication function with context.Context
-type TokenAuthenticationCtx func(context.Context, string) (context.Context, interface{}, error)
+// TokenAuthenticationCtx authentication function with [context.Context].
+type TokenAuthenticationCtx func(context.Context, string) (context.Context, any, error)
-// ScopedTokenAuthentication authentication function
-type ScopedTokenAuthentication func(string, []string) (interface{}, error)
+// ScopedTokenAuthentication authentication function.
+type ScopedTokenAuthentication func(string, []string) (any, error)
-// ScopedTokenAuthenticationCtx authentication function with context.Context
-type ScopedTokenAuthenticationCtx func(context.Context, string, []string) (context.Context, interface{}, error)
+// ScopedTokenAuthenticationCtx authentication function with [context.Context].
+type ScopedTokenAuthenticationCtx func(context.Context, string, []string) (context.Context, any, error)
var DefaultRealmName = "API"
@@ -104,18 +93,18 @@ 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
}
- return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
+ return HttpAuthenticator(func(r *http.Request) (bool, any, error) {
if usr, pass, ok := r.BasicAuth(); ok {
p, err := authenticate(usr, pass)
if err != nil {
@@ -128,18 +117,18 @@ 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
}
- return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
+ return HttpAuthenticator(func(r *http.Request) (bool, any, error) {
if usr, pass, ok := r.BasicAuth(); ok {
ctx, p, err := authenticate(r.Context(), usr, pass)
if err != nil {
@@ -154,12 +143,12 @@ 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 {
// panic because this is most likely a typo
- panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\""))
+ panic(errors.New(http.StatusInternalServerError, "api key auth: in value needs to be either \"query\" or \"header\""))
}
var getToken func(*http.Request) string
@@ -170,7 +159,7 @@ func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authe
getToken = func(r *http.Request) string { return r.URL.Query().Get(name) }
}
- return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
+ return HttpAuthenticator(func(r *http.Request) (bool, any, error) {
token := getToken(r)
if token == "" {
return false, nil, nil
@@ -181,13 +170,13 @@ 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 {
// panic because this is most likely a typo
- panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\""))
+ panic(errors.New(http.StatusInternalServerError, "api key auth: in value needs to be either \"query\" or \"header\""))
}
var getToken func(*http.Request) string
@@ -198,7 +187,7 @@ func APIKeyAuthCtx(name, in string, authenticate TokenAuthenticationCtx) runtime
getToken = func(r *http.Request) string { return r.URL.Query().Get(name) }
}
- return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
+ return HttpAuthenticator(func(r *http.Request) (bool, any, error) {
token := getToken(r)
if token == "" {
return false, nil, nil
@@ -210,20 +199,20 @@ 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, interface{}, error) {
+ return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, any, error) {
var token string
hdr := r.Request.Header.Get(runtime.HeaderAuthorization)
- if strings.HasPrefix(hdr, prefix) {
- token = strings.TrimPrefix(hdr, prefix)
+ if after, ok := strings.CutPrefix(hdr, prefix); ok {
+ token = after
}
if token == "" {
qs := r.Request.URL.Query()
@@ -246,14 +235,14 @@ 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, interface{}, error) {
+ return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, any, error) {
var token string
hdr := r.Request.Header.Get(runtime.HeaderAuthorization)
- if strings.HasPrefix(hdr, prefix) {
- token = strings.TrimPrefix(hdr, prefix)
+ if after, ok := strings.CutPrefix(hdr, prefix); ok {
+ token = after
}
if token == "" {
qs := r.Request.URL.Query()
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/security/authorizer.go b/test/tools/vendor/github.com/go-openapi/runtime/security/authorizer.go
index 00c1a4d6a4..8beef19f09 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/security/authorizer.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/security/authorizer.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package security
@@ -20,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, _ interface{}) error { return nil })
+ return runtime.AuthorizerFunc(func(_ *http.Request, _ any) error { return nil })
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/statuses.go b/test/tools/vendor/github.com/go-openapi/runtime/statuses.go
index 3b011a0bff..c0f3e6b447 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/statuses.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/statuses.go
@@ -1,20 +1,9 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
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/test/tools/vendor/github.com/go-openapi/runtime/text.go b/test/tools/vendor/github.com/go-openapi/runtime/text.go
index f33320b7dd..1252ac88c7 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/text.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/text.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -22,12 +11,12 @@ import (
"io"
"reflect"
- "github.com/go-openapi/swag"
+ "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 interface{}) error {
+ return ConsumerFunc(func(reader io.Reader, data any) error {
if reader == nil {
return errors.New("TextConsumer requires a reader") // early exit
}
@@ -67,9 +56,9 @@ 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 interface{}) error {
+ return ProducerFunc(func(writer io.Writer, data any) error {
if writer == nil {
return errors.New("TextProducer requires a writer") // early exit
}
@@ -99,7 +88,7 @@ func TextProducer() Producer {
v := reflect.Indirect(reflect.ValueOf(data))
if t := v.Type(); t.Kind() == reflect.Struct || t.Kind() == reflect.Slice {
- b, err := swag.WriteJSON(data)
+ b, err := jsonutils.WriteJSON(data)
if err != nil {
return err
}
diff --git a/test/tools/vendor/github.com/go-openapi/runtime/values.go b/test/tools/vendor/github.com/go-openapi/runtime/values.go
index 11f5732af4..af4d9be794 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/values.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/values.go
@@ -1,6 +1,9 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
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/test/tools/vendor/github.com/go-openapi/runtime/xml.go b/test/tools/vendor/github.com/go-openapi/runtime/xml.go
index 821c7393df..9cd2540c30 100644
--- a/test/tools/vendor/github.com/go-openapi/runtime/xml.go
+++ b/test/tools/vendor/github.com/go-openapi/runtime/xml.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package runtime
@@ -19,17 +8,17 @@ import (
"io"
)
-// XMLConsumer creates a new XML consumer
+// XMLConsumer creates a new XML consumer.
func XMLConsumer() Consumer {
- return ConsumerFunc(func(reader io.Reader, data interface{}) error {
+ return ConsumerFunc(func(reader io.Reader, data any) error {
dec := xml.NewDecoder(reader)
return dec.Decode(data)
})
}
-// XMLProducer creates a new XML producer
+// XMLProducer creates a new XML producer.
func XMLProducer() Producer {
- return ProducerFunc(func(writer io.Writer, data interface{}) error {
+ return ProducerFunc(func(writer io.Writer, data any) error {
enc := xml.NewEncoder(writer)
return enc.Encode(data)
})
diff --git a/test/tools/vendor/github.com/go-openapi/spec/.gitignore b/test/tools/vendor/github.com/go-openapi/spec/.gitignore
index f47cb2045f..885dc27ab0 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/.gitignore
+++ b/test/tools/vendor/github.com/go-openapi/spec/.gitignore
@@ -1 +1,6 @@
*.out
+*.cov
+.idea
+.env
+.mcp.json
+.claude/
diff --git a/test/tools/vendor/github.com/go-openapi/spec/.golangci.yml b/test/tools/vendor/github.com/go-openapi/spec/.golangci.yml
index 22f8d21cca..dc7c96053d 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/spec/.golangci.yml
@@ -1,61 +1,67 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
+ - depguard
- funlen
- godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- exhaustruct
- - varnamelen
- - gci
- - depguard
- - errchkjson
- - inamedparam
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 20
+ gocyclo:
+ min-complexity: 20
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/spec/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/spec/CONTRIBUTORS.md
new file mode 100644
index 0000000000..2967e3cedd
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/spec/CONTRIBUTORS.md
@@ -0,0 +1,50 @@
+# Contributors
+
+- Repository: ['go-openapi/spec']
+
+| Total Contributors | Total Contributions |
+| --- | --- |
+| 38 | 392 |
+
+| Username | All Time Contribution Count | All Commits |
+| --- | --- | --- |
+| @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/test/tools/vendor/github.com/go-openapi/spec/README.md b/test/tools/vendor/github.com/go-openapi/spec/README.md
index 7fd2810c69..134809fd77 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/README.md
+++ b/test/tools/vendor/github.com/go-openapi/spec/README.md
@@ -1,11 +1,38 @@
-# OpenAPI v2 object model [](https://github.com/go-openapi/spec/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/spec)
+# spec
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/spec/master/LICENSE)
-[](https://pkg.go.dev/github.com/go-openapi/spec)
-[](https://goreportcard.com/report/github.com/go-openapi/spec)
+
+[![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]
-The object model for OpenAPI specification documents.
+---
+
+The object model for OpenAPI v2 specification 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/spec
+```
### FAQ
@@ -28,7 +55,7 @@ The object model for OpenAPI specification documents.
> 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?
@@ -37,13 +64,13 @@ The object model for OpenAPI specification documents.
> 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?
@@ -51,4 +78,71 @@ The object model for OpenAPI specification documents.
> 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
+
+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/spec/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/spec/actions/workflows/go-test.yml/badge.svg
+[test-url]: https://github.com/go-openapi/spec/actions/workflows/go-test.yml
+[cov-badge]: https://codecov.io/gh/go-openapi/spec/branch/master/graph/badge.svg
+[cov-url]: https://codecov.io/gh/go-openapi/spec
+[vuln-scan-badge]: https://github.com/go-openapi/spec/actions/workflows/scanner.yml/badge.svg
+[vuln-scan-url]: https://github.com/go-openapi/spec/actions/workflows/scanner.yml
+[codeql-badge]: https://github.com/go-openapi/spec/actions/workflows/codeql.yml/badge.svg
+[codeql-url]: https://github.com/go-openapi/spec/actions/workflows/codeql.yml
+
+[release-badge]: https://badge.fury.io/gh/go-openapi%2Fspec.svg
+[release-url]: https://badge.fury.io/gh/go-openapi%2Fspec
+[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fspec.svg
+[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fspec
+
+[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/spec
+[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/spec
+[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/spec
+[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/spec
+
+[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/spec
+[godoc-url]: http://pkg.go.dev/github.com/go-openapi/spec
+[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/spec/?tab=Apache-2.0-1-ov-file#readme
+
+[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/spec
+[goversion-url]: https://github.com/go-openapi/spec/blob/master/go.mod
+[top-badge]: https://img.shields.io/github/languages/top/go-openapi/spec
+[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/spec/latest
diff --git a/test/tools/vendor/github.com/go-openapi/spec/SECURITY.md b/test/tools/vendor/github.com/go-openapi/spec/SECURITY.md
new file mode 100644
index 0000000000..1fea2c5736
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/spec/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/test/tools/vendor/github.com/go-openapi/spec/cache.go b/test/tools/vendor/github.com/go-openapi/spec/cache.go
index 122993b44b..06495d2c3d 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/cache.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/cache.go
@@ -1,40 +1,28 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
import (
+ "maps"
"sync"
)
-// ResolutionCache a cache for resolving urls
+// ResolutionCache a cache for resolving urls.
type ResolutionCache interface {
- Get(string) (interface{}, bool)
- Set(string, interface{})
+ Get(uri string) (any, bool)
+ Set(uri string, data any)
}
type simpleCache struct {
lock sync.RWMutex
- store map[string]interface{}
+ store map[string]any
}
-func (s *simpleCache) ShallowClone() ResolutionCache {
- store := make(map[string]interface{}, len(s.store))
+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()
- for k, v := range s.store {
- store[k] = v
- }
+ maps.Copy(store, s.store)
s.lock.RUnlock()
return &simpleCache{
@@ -42,8 +30,8 @@ func (s *simpleCache) ShallowClone() ResolutionCache {
}
}
-// Get retrieves a cached URI
-func (s *simpleCache) Get(uri string) (interface{}, bool) {
+// Get retrieves a cached URI.
+func (s *simpleCache) Get(uri string) (any, bool) {
s.lock.RLock()
v, ok := s.store[uri]
@@ -51,8 +39,8 @@ func (s *simpleCache) Get(uri string) (interface{}, bool) {
return v, ok
}
-// Set caches a URI
-func (s *simpleCache) Set(uri string, data interface{}) {
+// Set caches a URI.
+func (s *simpleCache) Set(uri string, data any) {
s.lock.Lock()
s.store[uri] = data
s.lock.Unlock()
@@ -68,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{}
)
@@ -80,13 +68,13 @@ func initResolutionCache() {
}
func defaultResolutionCache() *simpleCache {
- return &simpleCache{store: map[string]interface{}{
+ return &simpleCache{store: map[string]any{
"http://swagger.io/v2/schema.json": MustLoadSwagger20Schema(),
"http://json-schema.org/draft-04/schema": MustLoadJSONSchemaDraft04(),
}}
}
-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/test/tools/vendor/github.com/go-openapi/spec/contact_info.go b/test/tools/vendor/github.com/go-openapi/spec/contact_info.go
index 2f7bb219b5..46fada5dff 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/contact_info.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/contact_info.go
@@ -1,23 +1,12 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
import (
"encoding/json"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
// ContactInfo contact information for the exposed API.
@@ -28,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
@@ -43,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 {
@@ -53,5 +42,5 @@ func (c ContactInfo) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2), nil
+ return jsonutils.ConcatJSON(b1, b2), nil
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/debug.go b/test/tools/vendor/github.com/go-openapi/spec/debug.go
index fc889f6d0b..fa52b0c7f7 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/debug.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/debug.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -25,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()
}
@@ -40,7 +27,7 @@ func debugOptions() {
specLogger = log.New(os.Stdout, "spec:", log.LstdFlags)
}
-func debugLog(msg string, args ...interface{}) {
+func debugLog(msg string, args ...any) {
// A private, trivial trace logger, based on go-openapi/spec/expander.go:debugLog()
if Debug {
_, file1, pos1, _ := runtime.Caller(1)
diff --git a/test/tools/vendor/github.com/go-openapi/spec/doc.go b/test/tools/vendor/github.com/go-openapi/spec/doc.go
new file mode 100644
index 0000000000..04eea35758
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/spec/doc.go
@@ -0,0 +1,7 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
+// Package spec exposes an object model for OpenAPIv2 specifications (swagger).
+//
+// The exposed data structures know how to serialize to and deserialize from JSON.
+package spec
diff --git a/test/tools/vendor/github.com/go-openapi/spec/embed.go b/test/tools/vendor/github.com/go-openapi/spec/embed.go
index 1f4284750a..0d0b69996c 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/embed.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/embed.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package spec
import (
diff --git a/test/tools/vendor/github.com/go-openapi/spec/errors.go b/test/tools/vendor/github.com/go-openapi/spec/errors.go
index 6992c7ba73..eaca01cc83 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/errors.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/errors.go
@@ -1,19 +1,25 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
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 = errors.New("spec error")
)
diff --git a/test/tools/vendor/github.com/go-openapi/spec/expander.go b/test/tools/vendor/github.com/go-openapi/spec/expander.go
index b81a5699a0..f9c2fa327a 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/expander.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/expander.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -19,6 +8,8 @@ import (
"fmt"
)
+const smallPrealloc = 10
+
// ExpandOptions provides options for the spec expander.
//
// RelativeBase is the path to the root document. This can be a remote URL or a path to a local file.
@@ -47,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)
@@ -56,7 +47,7 @@ func ExpandSpec(spec *Swagger, options *ExpandOptions) error {
if !options.SkipSchemas {
for key, definition := range spec.Definitions {
- parentRefs := make([]string, 0, 10)
+ parentRefs := make([]string, 0, smallPrealloc)
parentRefs = append(parentRefs, "#/definitions/"+key)
def, err := expandSchema(definition, parentRefs, resolver, specBasePath)
@@ -101,8 +92,8 @@ 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
-func baseForRoot(root interface{}, cache ResolutionCache) string {
+// for further $ref resolution.
+func baseForRoot(root any, cache ResolutionCache) string {
// cache the root document to resolve $ref's
normalizedBase := normalizeBase(rootBase)
@@ -114,7 +105,7 @@ func baseForRoot(root interface{}, cache ResolutionCache) string {
return normalizedBase
}
- root = map[string]interface{}{}
+ root = map[string]any{}
}
cache.Set(normalizedBase, root)
@@ -130,7 +121,7 @@ func baseForRoot(root interface{}, cache ResolutionCache) string {
// (use ExpandSchemaWithBasePath to resolve external references).
//
// Setting the cache is optional and this parameter may safely be left to nil.
-func ExpandSchema(schema *Schema, root interface{}, cache ResolutionCache) error {
+func ExpandSchema(schema *Schema, root any, cache ResolutionCache) error {
cache = cacheOrDefault(cache)
if root == nil {
root = schema
@@ -160,7 +151,7 @@ func ExpandSchemaWithBasePath(schema *Schema, cache ResolutionCache, opts *Expan
resolver := defaultSchemaLoader(nil, opts, cache, nil)
- parentRefs := make([]string, 0, 10)
+ parentRefs := make([]string, 0, smallPrealloc)
s, err := expandSchema(*schema, parentRefs, resolver, opts.RelativeBase)
if err != nil {
return err
@@ -199,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)
@@ -386,7 +378,7 @@ func expandPathItem(pathItem *PathItem, resolver *schemaLoader, basePath string)
return nil
}
- parentRefs := make([]string, 0, 10)
+ parentRefs := make([]string, 0, smallPrealloc)
if err := resolver.deref(pathItem, parentRefs, basePath); resolver.shouldStopOnError(err) {
return err
}
@@ -461,7 +453,7 @@ func expandOperation(op *Operation, resolver *schemaLoader, basePath string) err
// (use ExpandResponse to resolve external references).
//
// Setting the cache is optional and this parameter may safely be left to nil.
-func ExpandResponseWithRoot(response *Response, root interface{}, cache ResolutionCache) error {
+func ExpandResponseWithRoot(response *Response, root any, cache ResolutionCache) error {
cache = cacheOrDefault(cache)
opts := &ExpandOptions{
RelativeBase: baseForRoot(root, cache),
@@ -473,7 +465,7 @@ func ExpandResponseWithRoot(response *Response, root interface{}, cache Resoluti
// 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,
@@ -487,7 +479,7 @@ func ExpandResponse(response *Response, basePath string) error {
//
// Notice that it is impossible to reference a json schema in a different document other than root
// (use ExpandParameter to resolve external references).
-func ExpandParameterWithRoot(parameter *Parameter, root interface{}, cache ResolutionCache) error {
+func ExpandParameterWithRoot(parameter *Parameter, root any, cache ResolutionCache) error {
cache = cacheOrDefault(cache)
opts := &ExpandOptions{
@@ -500,7 +492,7 @@ func ExpandParameterWithRoot(parameter *Parameter, root interface{}, cache Resol
// 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,
@@ -510,7 +502,7 @@ func ExpandParameter(parameter *Parameter, basePath string) error {
return expandParameterOrResponse(parameter, resolver, opts.RelativeBase)
}
-func getRefAndSchema(input interface{}) (*Ref, *Schema, error) {
+func getRefAndSchema(input any) (*Ref, *Schema, error) {
var (
ref *Ref
sch *Schema
@@ -536,7 +528,7 @@ func getRefAndSchema(input interface{}) (*Ref, *Schema, error) {
return ref, sch, nil
}
-func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePath string) error {
+func expandParameterOrResponse(input any, resolver *schemaLoader, basePath string) error {
ref, sch, err := getRefAndSchema(input)
if err != nil {
return err
@@ -546,7 +538,7 @@ func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePa
return nil
}
- parentRefs := make([]string, 0, 10)
+ parentRefs := make([]string, 0, smallPrealloc)
if ref != nil {
// dereference this $ref
if err = resolver.deref(input, parentRefs, basePath); resolver.shouldStopOnError(err) {
@@ -554,6 +546,9 @@ func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePa
}
ref, sch, _ = getRefAndSchema(input)
+ if ref == nil {
+ ref = &Ref{} // empty ref
+ }
}
if ref.String() != "" {
@@ -571,7 +566,7 @@ func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePa
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/test/tools/vendor/github.com/go-openapi/spec/external_docs.go b/test/tools/vendor/github.com/go-openapi/spec/external_docs.go
index 88add91b2b..17b8efbf10 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/external_docs.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/external_docs.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
diff --git a/test/tools/vendor/github.com/go-openapi/spec/header.go b/test/tools/vendor/github.com/go-openapi/spec/header.go
index 9dfd17b185..599ba2c5d7 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/header.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/header.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -19,14 +8,14 @@ import (
"strings"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
const (
jsonArray = "array"
)
-// HeaderProps describes a response header
+// HeaderProps describes a response header.
type HeaderProps struct {
Description string `json:"description,omitempty"`
}
@@ -41,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
@@ -67,87 +56,87 @@ func (h *Header) CollectionOf(items *Items, format string) *Header {
return h
}
-// WithDefault sets the default value on this item
-func (h *Header) WithDefault(defaultValue interface{}) *Header {
+// 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
-func (h *Header) WithMaxLength(max int64) *Header {
- h.MaxLength = &max
+// WithMaxLength sets a max length value.
+func (h *Header) WithMaxLength(maximum int64) *Header {
+ h.MaxLength = &maximum
return h
}
-// WithMinLength sets a min length value
-func (h *Header) WithMinLength(min int64) *Header {
- h.MinLength = &min
+// 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
-func (h *Header) WithMaximum(max float64, exclusive bool) *Header {
- h.Maximum = &max
+// 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
-func (h *Header) WithMinimum(min float64, exclusive bool) *Header {
- h.Minimum = &min
+// 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)
-func (h *Header) WithEnum(values ...interface{}) *Header {
- h.Enum = append([]interface{}{}, values...)
+// 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 {
@@ -161,10 +150,10 @@ func (h Header) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2, b3), nil
+ 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
@@ -178,8 +167,8 @@ func (h *Header) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &h.HeaderProps)
}
-// JSONLookup look up a value by the json property name
-func (h Header) JSONLookup(token string) (interface{}, error) {
+// 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/test/tools/vendor/github.com/go-openapi/spec/info.go b/test/tools/vendor/github.com/go-openapi/spec/info.go
index 582f0fd4c4..0ccfdcccd9 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/info.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/info.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -20,19 +9,19 @@ import (
"strings"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
-// Extensions vendor specific extensions
-type Extensions map[string]interface{}
+// Extensions vendor specific extensions.
+type Extensions map[string]any
-// Add adds a value to these extensions
-func (e Extensions) Add(key string, value interface{}) {
+// 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)
@@ -41,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)
@@ -59,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)
@@ -68,10 +57,10 @@ 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.([]interface{})
+ arr, isSlice := v.([]any)
if !isSlice {
return nil, false
}
@@ -93,20 +82,20 @@ type VendorExtensible struct {
Extensions Extensions
}
-// AddExtension adds an extension to this extensible object
-func (v *VendorExtensible) AddExtension(key string, value interface{}) {
+// AddExtension adds an extension to this extensible object.
+func (v *VendorExtensible) AddExtension(key string, value any) {
if value == nil {
return
}
if v.Extensions == nil {
- v.Extensions = make(map[string]interface{})
+ v.Extensions = make(map[string]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]interface{})
+ toser := make(map[string]any)
for k, v := range v.Extensions {
lk := strings.ToLower(k)
if strings.HasPrefix(lk, "x-") {
@@ -116,9 +105,9 @@ 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]interface{}
+ var d map[string]any
if err := json.Unmarshal(data, &d); err != nil {
return err
}
@@ -126,7 +115,7 @@ func (v *VendorExtensible) UnmarshalJSON(data []byte) error {
lk := strings.ToLower(k)
if strings.HasPrefix(lk, "x-") {
if v.Extensions == nil {
- v.Extensions = map[string]interface{}{}
+ v.Extensions = map[string]any{}
}
v.Extensions[k] = vv
}
@@ -134,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"`
@@ -153,8 +142,8 @@ type Info struct {
InfoProps
}
-// JSONLookup look up a value by the json property name
-func (i Info) JSONLookup(token string) (interface{}, error) {
+// 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
}
@@ -162,7 +151,7 @@ func (i Info) JSONLookup(token string) (interface{}, 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 {
@@ -172,10 +161,10 @@ func (i Info) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2), nil
+ 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/test/tools/vendor/github.com/go-openapi/spec/items.go b/test/tools/vendor/github.com/go-openapi/spec/items.go
index e2afb2133b..daf5a4fd42 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/items.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/items.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -19,25 +8,25 @@ import (
"strings"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
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"`
- Format string `json:"format,omitempty"`
- Items *Items `json:"items,omitempty"`
- CollectionFormat string `json:"collectionFormat,omitempty"`
- Default interface{} `json:"default,omitempty"`
- Example interface{} `json:"example,omitempty"`
+ Type string `json:"type,omitempty"`
+ Nullable bool `json:"nullable,omitempty"`
+ Format string `json:"format,omitempty"`
+ Items *Items `json:"items,omitempty"`
+ CollectionFormat string `json:"collectionFormat,omitempty"`
+ Default any `json:"default,omitempty"`
+ 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
@@ -45,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 ""
@@ -64,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
@@ -82,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
@@ -90,87 +79,87 @@ func (i *Items) CollectionOf(items *Items, format string) *Items {
return i
}
-// WithDefault sets the default value on this item
-func (i *Items) WithDefault(defaultValue interface{}) *Items {
+// 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
-func (i *Items) WithMaxLength(max int64) *Items {
- i.MaxLength = &max
+// WithMaxLength sets a max length value.
+func (i *Items) WithMaxLength(maximum int64) *Items {
+ i.MaxLength = &maximum
return i
}
-// WithMinLength sets a min length value
-func (i *Items) WithMinLength(min int64) *Items {
- i.MinLength = &min
+// 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
-func (i *Items) WithMaximum(max float64, exclusive bool) *Items {
- i.Maximum = &max
+// 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
-func (i *Items) WithMinimum(min float64, exclusive bool) *Items {
- i.Minimum = &min
+// 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)
-func (i *Items) WithEnum(values ...interface{}) *Items {
- i.Enum = append([]interface{}{}, values...)
+// 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 {
@@ -195,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 {
@@ -213,11 +202,11 @@ func (i Items) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b4, b3, b1, b2), nil
+ return jsonutils.ConcatJSON(b4, b3, b1, b2), nil
}
-// JSONLookup look up a value by the json property name
-func (i Items) JSONLookup(token string) (interface{}, error) {
+// 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/test/tools/vendor/github.com/go-openapi/spec/license.go b/test/tools/vendor/github.com/go-openapi/spec/license.go
index b42f80368e..8209f218b5 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/license.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/license.go
@@ -1,23 +1,12 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
import (
"encoding/json"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
// License information for the exposed API.
@@ -28,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
@@ -42,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 {
@@ -52,5 +41,5 @@ func (l License) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2), nil
+ return jsonutils.ConcatJSON(b1, b2), nil
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/normalizer.go b/test/tools/vendor/github.com/go-openapi/spec/normalizer.go
index e8b6009945..68252dc30b 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/normalizer.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/normalizer.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -95,7 +84,7 @@ func denormalizeRef(ref *Ref, originalRelativeBase, id string) Ref {
if id != "" {
idBaseURL, err := parseURL(id)
if err == nil { // if the schema id is not usable as a URI, ignore it
- if ref, ok := rebase(ref, idBaseURL, true); ok { // rebase, but keep references to root unchaged (do not want $ref: "")
+ if ref, ok := rebase(ref, idBaseURL, true); ok { // rebase, but keep references to root unchanged (do not want $ref: "")
// $ref relative to the ID of the schema in the root document
return ref
}
@@ -129,8 +118,8 @@ func rebase(ref *Ref, v *url.URL, notEqual bool) (Ref, bool) {
newBase.Fragment = u.Fragment
- if strings.HasPrefix(u.Path, docPath) {
- newBase.Path = strings.TrimPrefix(u.Path, docPath)
+ if after, ok := strings.CutPrefix(u.Path, docPath); ok {
+ newBase.Path = after
} else {
newBase.Path = strings.TrimPrefix(u.Path, v.Path)
}
@@ -149,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/test/tools/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go b/test/tools/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go
index f19f1a8fb6..0d55632349 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go
@@ -1,19 +1,7 @@
//go:build !windows
-// +build !windows
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
diff --git a/test/tools/vendor/github.com/go-openapi/spec/normalizer_windows.go b/test/tools/vendor/github.com/go-openapi/spec/normalizer_windows.go
index a66c532dbc..61515c9a16 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/normalizer_windows.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/normalizer_windows.go
@@ -1,18 +1,7 @@
// -build windows
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
diff --git a/test/tools/vendor/github.com/go-openapi/spec/operation.go b/test/tools/vendor/github.com/go-openapi/spec/operation.go
index a69cca8814..cd70d2547c 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/operation.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/operation.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -21,19 +10,19 @@ import (
"sort"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
-func init() {
- gob.Register(map[string]interface{}{})
- gob.Register([]interface{}{})
+func init() { //nolint:gochecknoinits // registers gob types for Operation serialization
+ gob.Register(map[string]any{})
+ gob.Register([]any{})
}
// OperationProps describes an operation
//
// 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"`
@@ -58,19 +47,22 @@ func (op OperationProps) MarshalJSON() ([]byte, error) {
type Alias OperationProps
if op.Security == nil {
return json.Marshal(&struct {
- Security []map[string][]string `json:"security,omitempty"`
*Alias
+
+ Security []map[string][]string `json:"security,omitempty"`
}{
- Security: op.Security,
Alias: (*Alias)(&op),
+ Security: op.Security,
})
}
+
return json.Marshal(&struct {
- Security []map[string][]string `json:"security"`
*Alias
+
+ Security []map[string][]string `json:"security"`
}{
- Security: op.Security,
Alias: (*Alias)(&op),
+ Security: op.Security,
})
}
@@ -82,7 +74,15 @@ type Operation struct {
OperationProps
}
-// SuccessResponse gets a success response model
+// NewOperation creates a new operation instance.
+// It expects an ID as parameter but not passing an ID is also valid.
+func NewOperation(id string) *Operation {
+ op := new(Operation)
+ op.ID = id
+ return op
+}
+
+// SuccessResponse gets a success response model.
func (o *Operation) SuccessResponse() (*Response, int, bool) {
if o.Responses == nil {
return nil, 0, false
@@ -103,8 +103,8 @@ func (o *Operation) SuccessResponse() (*Response, int, bool) {
return o.Responses.Default, 0, false
}
-// JSONLookup look up a value by the json property name
-func (o Operation) JSONLookup(token string) (interface{}, error) {
+// 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) (interface{}, 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 {
@@ -130,31 +130,23 @@ func (o Operation) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- concated := swag.ConcatJSON(b1, b2)
+ concated := jsonutils.ConcatJSON(b1, b2)
return concated, nil
}
-// NewOperation creates a new operation instance.
-// It expects an ID as parameter but not passing an ID is also valid.
-func NewOperation(id string) *Operation {
- op := new(Operation)
- op.ID = id
- return op
-}
-
// WithID sets the ID property on this operation, allows for chaining.
func (o *Operation) WithID(id string) *Operation {
o.ID = id
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
@@ -178,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 deprected
+// 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
@@ -231,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 {
@@ -249,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)
@@ -287,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
@@ -301,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
@@ -318,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),
@@ -363,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/test/tools/vendor/github.com/go-openapi/spec/parameter.go b/test/tools/vendor/github.com/go-openapi/spec/parameter.go
index bd4f1cdb07..516f5d95c5 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/parameter.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/parameter.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -19,48 +8,54 @@ import (
"strings"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "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)
@@ -71,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"`
@@ -115,8 +110,8 @@ type Parameter struct {
ParamProps
}
-// JSONLookup look up a value by the json property name
-func (p Parameter) JSONLookup(token string) (interface{}, error) {
+// 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
}
@@ -142,32 +137,32 @@ func (p Parameter) JSONLookup(token string) (interface{}, 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
@@ -175,32 +170,32 @@ func (p *Parameter) CollectionOf(items *Items, format string) *Parameter {
return p
}
-// WithDefault sets the default value on this parameter
-func (p *Parameter) WithDefault(defaultValue interface{}) *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
@@ -209,81 +204,81 @@ func (p *Parameter) AsRequired() *Parameter {
return p
}
-// WithMaxLength sets a max length value
-func (p *Parameter) WithMaxLength(max int64) *Parameter {
- p.MaxLength = &max
+// WithMaxLength sets a max length value.
+func (p *Parameter) WithMaxLength(maximum int64) *Parameter {
+ p.MaxLength = &maximum
return p
}
-// WithMinLength sets a min length value
-func (p *Parameter) WithMinLength(min int64) *Parameter {
- p.MinLength = &min
+// 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
-func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter {
- p.Maximum = &max
+// 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
-func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter {
- p.Minimum = &min
+// 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)
-func (p *Parameter) WithEnum(values ...interface{}) *Parameter {
- p.Enum = append([]interface{}{}, values...)
+// 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
@@ -300,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 {
@@ -322,5 +317,5 @@ func (p Parameter) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b3, b1, b2, b4, b5), nil
+ return jsonutils.ConcatJSON(b3, b1, b2, b4, b5), nil
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/path_item.go b/test/tools/vendor/github.com/go-openapi/spec/path_item.go
index 68fc8e9014..4408ece465 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/path_item.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/path_item.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -18,10 +7,10 @@ import (
"encoding/json"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "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"`
@@ -45,8 +34,8 @@ type PathItem struct {
PathItemProps
}
-// JSONLookup look up a value by the json property name
-func (p PathItem) JSONLookup(token string) (interface{}, error) {
+// 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
}
@@ -57,7 +46,7 @@ func (p PathItem) JSONLookup(token string) (interface{}, 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
@@ -68,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 {
@@ -82,6 +71,6 @@ func (p PathItem) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- concated := swag.ConcatJSON(b3, b4, b5)
+ concated := jsonutils.ConcatJSON(b3, b4, b5)
return concated, nil
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/paths.go b/test/tools/vendor/github.com/go-openapi/spec/paths.go
index 9dc82a2901..5daf5a6709 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/paths.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/paths.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -19,7 +8,7 @@ import (
"fmt"
"strings"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
// Paths holds the relative paths to the individual endpoints.
@@ -30,21 +19,22 @@ import (
// For more information: http://goo.gl/8us55a#pathsObject
type Paths struct {
VendorExtensible
+
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
-func (p Paths) JSONLookup(token string) (interface{}, error) {
+// 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
}
if ex, ok := p.Extensions[token]; ok {
return &ex, nil
}
- return nil, fmt.Errorf("object has no field %q", token)
+ 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 {
@@ -53,9 +43,9 @@ func (p *Paths) UnmarshalJSON(data []byte) error {
for k, v := range res {
if strings.HasPrefix(strings.ToLower(k), "x-") {
if p.Extensions == nil {
- p.Extensions = make(map[string]interface{})
+ p.Extensions = make(map[string]any)
}
- var d interface{}
+ var d any
if err := json.Unmarshal(v, &d); err != nil {
return err
}
@@ -75,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 {
@@ -92,6 +82,6 @@ func (p Paths) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- concated := swag.ConcatJSON(b1, b2)
+ concated := jsonutils.ConcatJSON(b1, b2)
return concated, nil
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/properties.go b/test/tools/vendor/github.com/go-openapi/spec/properties.go
index 91d2435f01..b8e97271e1 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/properties.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/properties.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package spec
import (
@@ -7,10 +10,11 @@ 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 {
- Name string
Schema
+
+ Name string
}
// OrderSchemaItems is a sortable slice of named schemas.
@@ -21,21 +25,26 @@ type OrderSchemaItems []OrderSchemaItem
// of the OrderSchemaItems slice, keeping the original order of the slice.
func (items OrderSchemaItems) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(nil)
- buf.WriteString("{")
- for i := range items {
- if i > 0 {
- buf.WriteString(",")
- }
- buf.WriteString("\"")
- buf.WriteString(items[i].Name)
- buf.WriteString("\":")
- bs, err := json.Marshal(&items[i].Schema)
- if err != nil {
+ buf.WriteByte('{')
+
+ if len(items) == 0 {
+ buf.WriteByte('}')
+
+ return buf.Bytes(), nil
+ }
+
+ if err := items.marshalJSONItem(items[0], buf); err != nil {
+ return nil, err
+ }
+
+ for _, item := range items[1:] {
+ buf.WriteByte(',')
+ if err := items.marshalJSONItem(item, buf); err != nil {
return nil, err
}
- buf.Write(bs)
}
- buf.WriteString("}")
+ buf.WriteByte('}')
+
return buf.Bytes(), nil
}
@@ -44,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 {
@@ -65,11 +74,27 @@ func (items OrderSchemaItems) Less(i, j int) (ret bool) {
return items[i].Name < items[j].Name
}
+func (items OrderSchemaItems) marshalJSONItem(item OrderSchemaItem, output *bytes.Buffer) error {
+ nameJSON, err := json.Marshal(item.Name)
+ if err != nil {
+ return err
+ }
+ output.Write(nameJSON)
+ output.WriteByte(':')
+ schemaJSON, err := json.Marshal(&item.Schema)
+ if err != nil {
+ return err
+ }
+ output.Write(schemaJSON)
+
+ return nil
+}
+
// SchemaProperties is a map representing the properties of a Schema object.
// 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/test/tools/vendor/github.com/go-openapi/spec/ref.go b/test/tools/vendor/github.com/go-openapi/spec/ref.go
index b0ef9bd9c9..40b7d486c9 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/ref.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/ref.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -25,27 +14,44 @@ 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 unmarshalss 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
}
-// RemoteURI gets the remote uri part of the ref
+// NewRef creates a new instance of a ref object
+// 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 {
+ return Ref{}, err
+ }
+
+ return Ref{Ref: ref}, nil
+}
+
+// MustCreateRef creates a ref object but panics when refURI is invalid.
+// Use the NewRef method for a version that returns an error.
+func MustCreateRef(refURI string) Ref {
+ return Ref{Ref: jsonreference.MustCreateRef(refURI)}
+}
+
+// RemoteURI gets the remote uri part of the ref.
func (r *Ref) RemoteURI() string {
if r.String() == "" {
return ""
@@ -56,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
@@ -75,10 +81,11 @@ func (r *Ref) IsValidURI(basepaths ...string) bool {
}
defer rr.Body.Close()
- return rr.StatusCode/100 == 2
+ // true if the response is >= 200 and < 300
+ return rr.StatusCode/100 == 2 //nolint:mnd
}
- if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) {
+ if !r.HasFileScheme && !r.HasFullFilePath && !r.HasURLPathOnly {
return false
}
@@ -105,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 {
@@ -114,23 +121,7 @@ func (r *Ref) Inherits(child Ref) (*Ref, error) {
return &Ref{Ref: *ref}, nil
}
-// NewRef creates a new instance of a ref object
-// 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 {
- return Ref{}, err
- }
- return Ref{Ref: ref}, nil
-}
-
-// MustCreateRef creates a ref object but panics when refURI is invalid.
-// Use the NewRef method for a version that returns an error.
-func MustCreateRef(refURI string) Ref {
- return Ref{Ref: jsonreference.MustCreateRef(refURI)}
-}
-
-// 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 == "" {
@@ -139,20 +130,20 @@ func (r Ref) MarshalJSON() ([]byte, error) {
}
return []byte("{}"), nil
}
- v := map[string]interface{}{"$ref": str}
+ v := map[string]any{"$ref": str}
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]interface{}
+ var v map[string]any
if err := json.Unmarshal(d, &v); err != nil {
return err
}
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()
@@ -163,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)
@@ -174,7 +165,7 @@ func (r *Ref) GobDecode(b []byte) error {
return json.Unmarshal(raw, r)
}
-func (r *Ref) fromMap(v map[string]interface{}) error {
+func (r *Ref) fromMap(v map[string]any) error {
if v == nil {
return nil
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/resolver.go b/test/tools/vendor/github.com/go-openapi/spec/resolver.go
index 47d1ee13fc..1bf90c8682 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/resolver.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/resolver.go
@@ -1,12 +1,15 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package spec
import (
"fmt"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
-func resolveAnyWithBase(root interface{}, ref *Ref, result interface{}, options *ExpandOptions) error {
+func resolveAnyWithBase(root any, ref *Ref, result any, options *ExpandOptions) error {
options = optionsOrDefault(options)
resolver := defaultSchemaLoader(root, options, nil, nil)
@@ -17,8 +20,8 @@ func resolveAnyWithBase(root interface{}, ref *Ref, result interface{}, options
return nil
}
-// ResolveRefWithBase resolves a reference against a context root with preservation of base path
-func ResolveRefWithBase(root interface{}, ref *Ref, options *ExpandOptions) (*Schema, error) {
+// 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)
if err := resolveAnyWithBase(root, ref, result, options); err != nil {
@@ -31,8 +34,8 @@ func ResolveRefWithBase(root interface{}, ref *Ref, options *ExpandOptions) (*Sc
// 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
-func ResolveRef(root interface{}, ref *Ref) (*Schema, error) {
+// 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 {
return nil, err
@@ -43,9 +46,9 @@ func ResolveRef(root interface{}, ref *Ref) (*Schema, error) {
return &sch, nil
case *Schema:
return sch, nil
- case map[string]interface{}:
+ case map[string]any:
newSch := new(Schema)
- if err = swag.DynamicJSONToStruct(sch, newSch); err != nil {
+ if err = jsonutils.FromDynamicJSON(sch, newSch); err != nil {
return nil, err
}
return newSch, nil
@@ -54,8 +57,8 @@ func ResolveRef(root interface{}, ref *Ref) (*Schema, error) {
}
}
-// ResolveParameterWithBase resolves a parameter reference against a context root and base path
-func ResolveParameterWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Parameter, error) {
+// 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)
if err := resolveAnyWithBase(root, &ref, result, options); err != nil {
@@ -65,13 +68,13 @@ func ResolveParameterWithBase(root interface{}, ref Ref, options *ExpandOptions)
return result, nil
}
-// ResolveParameter resolves a parameter reference against a context root
-func ResolveParameter(root interface{}, ref Ref) (*Parameter, error) {
+// 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
-func ResolveResponseWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Response, error) {
+// 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)
err := resolveAnyWithBase(root, &ref, result, options)
@@ -82,13 +85,13 @@ func ResolveResponseWithBase(root interface{}, ref Ref, options *ExpandOptions)
return result, nil
}
-// ResolveResponse resolves response a reference against a context root
-func ResolveResponse(root interface{}, ref Ref) (*Response, error) {
+// 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
-func ResolvePathItemWithBase(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) {
+// 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)
if err := resolveAnyWithBase(root, &ref, result, options); err != nil {
@@ -100,16 +103,16 @@ func ResolvePathItemWithBase(root interface{}, ref Ref, options *ExpandOptions)
// ResolvePathItem resolves response a path item against a context root and base path
//
-// Deprecated: use ResolvePathItemWithBase instead
-func ResolvePathItem(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) {
+// Deprecated: use ResolvePathItemWithBase instead.
+func ResolvePathItem(root any, ref Ref, options *ExpandOptions) (*PathItem, error) {
return ResolvePathItemWithBase(root, ref, options)
}
// ResolveItemsWithBase resolves parameter items reference against a context root and base path.
//
-// NOTE: stricly speaking, this construct is not supported by Swagger 2.0.
+// NOTE: strictly speaking, this construct is not supported by Swagger 2.0.
// Similarly, $ref are forbidden in response headers.
-func ResolveItemsWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) {
+func ResolveItemsWithBase(root any, ref Ref, options *ExpandOptions) (*Items, error) {
result := new(Items)
if err := resolveAnyWithBase(root, &ref, result, options); err != nil {
@@ -121,7 +124,7 @@ func ResolveItemsWithBase(root interface{}, ref Ref, options *ExpandOptions) (*I
// ResolveItems resolves parameter items reference against a context root and base path.
//
-// Deprecated: use ResolveItemsWithBase instead
-func ResolveItems(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) {
+// Deprecated: use ResolveItemsWithBase instead.
+func ResolveItems(root any, ref Ref, options *ExpandOptions) (*Items, error) {
return ResolveItemsWithBase(root, ref, options)
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/response.go b/test/tools/vendor/github.com/go-openapi/spec/response.go
index 0340b60d84..4bb6a2bcd2 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/response.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/response.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -18,15 +7,15 @@ import (
"encoding/json"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "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"`
- Headers map[string]Header `json:"headers,omitempty"`
- Examples map[string]interface{} `json:"examples,omitempty"`
+ Description string `json:"description"`
+ Schema *Schema `json:"schema,omitempty"`
+ Headers map[string]Header `json:"headers,omitempty"`
+ Examples map[string]any `json:"examples,omitempty"`
}
// Response describes a single response from an API Operation.
@@ -38,8 +27,20 @@ type Response struct {
VendorExtensible
}
-// JSONLookup look up a value by the json property name
-func (r Response) JSONLookup(token string) (interface{}, error) {
+// NewResponse creates a new response instance.
+func NewResponse() *Response {
+ return new(Response)
+}
+
+// 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.
+func (r Response) JSONLookup(token string) (any, error) {
if ex, ok := r.Extensions[token]; ok {
return &ex, nil
}
@@ -50,7 +51,7 @@ func (r Response) JSONLookup(token string) (interface{}, 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
@@ -61,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
@@ -74,14 +75,14 @@ func (r Response) MarshalJSON() ([]byte, error) {
} else {
// when there is $ref inside the schema, description should be omitempty-ied
b1, err = json.Marshal(struct {
- Description string `json:"description,omitempty"`
- Schema *Schema `json:"schema,omitempty"`
- Headers map[string]Header `json:"headers,omitempty"`
- Examples map[string]interface{} `json:"examples,omitempty"`
+ Description string `json:"description,omitempty"`
+ Schema *Schema `json:"schema,omitempty"`
+ Headers map[string]Header `json:"headers,omitempty"`
+ Examples map[string]any `json:"examples,omitempty"`
}{
- Description: r.ResponseProps.Description,
- Schema: r.ResponseProps.Schema,
- Examples: r.ResponseProps.Examples,
+ Description: r.Description,
+ Schema: r.Schema,
+ Examples: r.Examples,
})
}
if err != nil {
@@ -96,35 +97,23 @@ func (r Response) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2, b3), nil
+ return jsonutils.ConcatJSON(b1, b2, b3), nil
}
-// NewResponse creates a new response instance
-func NewResponse() *Response {
- return new(Response)
-}
-
-// ResponseRef creates a response as a json reference
-func ResponseRef(url string) *Response {
- resp := NewResponse()
- resp.Ref = MustCreateRef(url)
- return resp
-}
-
-// 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)
@@ -136,16 +125,16 @@ 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
-func (r *Response) AddExample(mediaType string, example interface{}) *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]interface{})
+ r.Examples = make(map[string]any)
}
r.Examples[mediaType] = example
return r
diff --git a/test/tools/vendor/github.com/go-openapi/spec/responses.go b/test/tools/vendor/github.com/go-openapi/spec/responses.go
index 16c3076fe8..fb369e4a6b 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/responses.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/responses.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -21,7 +10,7 @@ import (
"strconv"
"strings"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
// Responses is a container for the expected responses of an operation.
@@ -42,8 +31,8 @@ type Responses struct {
ResponsesProps
}
-// JSONLookup implements an interface to customize json pointer lookup
-func (r Responses) JSONLookup(token string) (interface{}, error) {
+// JSONLookup implements an interface to customize json pointer lookup.
+func (r Responses) JSONLookup(token string) (any, error) {
if token == "default" {
return r.Default, nil
}
@@ -55,10 +44,10 @@ func (r Responses) JSONLookup(token string) (interface{}, error) {
return scr, nil
}
}
- return nil, fmt.Errorf("object has no field %q", token)
+ 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
@@ -73,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 {
@@ -83,7 +72,7 @@ func (r Responses) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- concated := swag.ConcatJSON(b1, b2)
+ concated := jsonutils.ConcatJSON(b1, b2)
return concated, nil
}
@@ -95,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 {
@@ -107,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/test/tools/vendor/github.com/go-openapi/spec/schema.go b/test/tools/vendor/github.com/go-openapi/spec/schema.go
index 4e9be8576b..d7a481bf1a 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/schema.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/schema.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -20,89 +9,92 @@ import (
"strings"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonname"
+ "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"}}}
@@ -110,35 +102,35 @@ 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
}
- v := map[string]interface{}{"$schema": string(r)}
+ v := map[string]any{"$schema": string(r)}
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]interface{}
+ var v map[string]any
if err := json.Unmarshal(data, &v); err != nil {
return err
}
return r.fromMap(v)
}
-func (r *SchemaURL) fromMap(v map[string]interface{}) error {
+func (r *SchemaURL) fromMap(v map[string]any) error {
if v == nil {
return nil
}
@@ -155,7 +147,7 @@ func (r *SchemaURL) fromMap(v map[string]interface{}) 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:"-"`
@@ -165,7 +157,7 @@ type SchemaProps struct {
Nullable bool `json:"nullable,omitempty"`
Format string `json:"format,omitempty"`
Title string `json:"title,omitempty"`
- Default interface{} `json:"default,omitempty"`
+ Default any `json:"default,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
@@ -177,7 +169,7 @@ type SchemaProps struct {
MinItems *int64 `json:"minItems,omitempty"`
UniqueItems bool `json:"uniqueItems,omitempty"`
MultipleOf *float64 `json:"multipleOf,omitempty"`
- Enum []interface{} `json:"enum,omitempty"`
+ Enum []any `json:"enum,omitempty"`
MaxProperties *int64 `json:"maxProperties,omitempty"`
MinProperties *int64 `json:"minProperties,omitempty"`
Required []string `json:"required,omitempty"`
@@ -194,13 +186,13 @@ 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"`
XML *XMLObject `json:"xml,omitempty"`
ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
- Example interface{} `json:"example,omitempty"`
+ Example any `json:"example,omitempty"`
}
// Schema the schema object allows the definition of input and output data types.
@@ -214,11 +206,12 @@ type Schema struct {
VendorExtensible
SchemaProps
SwaggerSchemaProps
- ExtraProps map[string]interface{} `json:"-"`
+
+ ExtraProps map[string]any `json:"-"`
}
-// JSONLookup implements an interface to customize json pointer lookup
-func (s Schema) JSONLookup(token string) (interface{}, error) {
+// 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
}
@@ -235,31 +228,31 @@ func (s Schema) JSONLookup(token string) (interface{}, 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)
@@ -268,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
-func (s *Schema) WithMaxProperties(max int64) *Schema {
- s.MaxProperties = &max
+// 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
-func (s *Schema) WithMinProperties(min int64) *Schema {
- s.MinProperties = &min
+// 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 != "" {
@@ -308,125 +301,125 @@ 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
-func (s *Schema) WithDefault(defaultValue interface{}) *Schema {
+// 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
-func (s *Schema) WithMaxLength(max int64) *Schema {
- s.MaxLength = &max
+// WithMaxLength sets a max length value.
+func (s *Schema) WithMaxLength(maximum int64) *Schema {
+ s.MaxLength = &maximum
return s
}
-// WithMinLength sets a min length value
-func (s *Schema) WithMinLength(min int64) *Schema {
- s.MinLength = &min
+// 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
-func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema {
- s.Maximum = &max
+// 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
-func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema {
- s.Minimum = &min
+// 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)
-func (s *Schema) WithEnum(values ...interface{}) *Schema {
- s.Enum = append([]interface{}{}, values...)
+// 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
-func (s *Schema) WithExample(example interface{}) *Schema {
+// WithExample sets the example for this schema.
+func (s *Schema) WithExample(example any) *Schema {
s.Example = example
return s
}
@@ -449,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)
@@ -458,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)
@@ -467,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)
@@ -476,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)
@@ -485,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)
@@ -494,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)
@@ -503,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)
@@ -533,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{
@@ -562,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", err)
+ 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", err)
+ 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", err)
+ 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", err)
+ 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", err)
+ 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", err)
+ return nil, fmt.Errorf("extra props %w: %w", err, ErrSpec)
}
b6 = jj
}
- return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil
+ 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
@@ -610,7 +603,7 @@ func (s *Schema) UnmarshalJSON(data []byte) error {
SwaggerSchemaProps: props.SwaggerSchemaProps,
}
- var d map[string]interface{}
+ var d map[string]any
if err := json.Unmarshal(data, &d); err != nil {
return err
}
@@ -620,7 +613,7 @@ func (s *Schema) UnmarshalJSON(data []byte) error {
delete(d, "$ref")
delete(d, "$schema")
- for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) {
+ for _, pn := range jsonname.DefaultJSONNameProvider.GetJSONNames(s) {
delete(d, pn)
}
@@ -628,13 +621,13 @@ func (s *Schema) UnmarshalJSON(data []byte) error {
lk := strings.ToLower(k)
if strings.HasPrefix(lk, "x-") {
if sch.Extensions == nil {
- sch.Extensions = map[string]interface{}{}
+ sch.Extensions = map[string]any{}
}
sch.Extensions[k] = vv
continue
}
if sch.ExtraProps == nil {
- sch.ExtraProps = map[string]interface{}{}
+ sch.ExtraProps = map[string]any{}
}
sch.ExtraProps[k] = vv
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/schema_loader.go b/test/tools/vendor/github.com/go-openapi/spec/schema_loader.go
index 0059b99aed..0894c932c6 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/schema_loader.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/schema_loader.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -22,7 +11,9 @@ import (
"reflect"
"strings"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
+ "github.com/go-openapi/swag/loading"
+ "github.com/go-openapi/swag/stringutils"
)
// PathLoader is a function to use when loading remote refs.
@@ -33,8 +24,8 @@ 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) {
- data, err := swag.LoadFromFileOrHTTP(pth)
+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
}
@@ -73,12 +64,23 @@ func newResolverContext(options *ExpandOptions) *resolverContext {
}
type schemaLoader struct {
- root interface{}
+ root any
options *ExpandOptions
cache ResolutionCache
context *resolverContext
}
+// Resolve resolves a reference against basePath and stores the result in target.
+//
+// Resolve is not in charge of following references: it only resolves ref by following its URL.
+//
+// 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.
+func (r *schemaLoader) Resolve(ref *Ref, target any, basePath string) error {
+ return r.resolveRef(ref, target, basePath)
+}
+
func (r *schemaLoader) transitiveResolver(basePath string, ref Ref) *schemaLoader {
if ref.IsRoot() || ref.HasFragmentOnly {
return r
@@ -113,7 +115,7 @@ func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string)
return basePath
}
-func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error {
+func (r *schemaLoader) resolveRef(ref *Ref, target any, basePath string) error {
tgt := reflect.ValueOf(target)
if tgt.Kind() != reflect.Ptr {
return ErrResolveRefNeedsAPointer
@@ -124,8 +126,8 @@ func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string)
}
var (
- res interface{}
- data interface{}
+ res any
+ data any
err error
)
@@ -134,7 +136,7 @@ func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string)
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())
}
}
@@ -142,7 +144,7 @@ func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string)
data = root
} else {
baseRef := normalizeRef(ref, basePath)
- data, _, _, err = r.load(baseRef.GetURL())
+ data, err = r.load(baseRef.GetURL())
if err != nil {
return err
}
@@ -155,36 +157,35 @@ func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string)
return err
}
}
- return swag.DynamicJSONToStruct(res, target)
+ return jsonutils.FromDynamicJSON(res, target)
}
-func (r *schemaLoader) load(refURL *url.URL) (interface{}, 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 interface{}
+ 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.
@@ -197,25 +198,14 @@ func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...strin
foundCycle = true
return
}
- foundCycle = swag.ContainsStrings(parentRefs, normalizedRef) // normalized windows url's are lower cased
+ foundCycle = stringutils.ContainsStrings(parentRefs, normalizedRef) // normalized windows url's are lower cased
if foundCycle {
r.context.circulars[normalizedRef] = true
}
return
}
-// Resolve resolves a reference against basePath and stores the result in target.
-//
-// Resolve is not in charge of following references: it only resolves ref by following its URL.
-//
-// 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
-func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error {
- return r.resolveRef(ref, target, basePath)
-}
-
-func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error {
+func (r *schemaLoader) deref(input any, parentRefs []string, basePath string) error {
var ref *Ref
switch refable := input.(type) {
case *Schema:
@@ -267,7 +257,7 @@ func (r *schemaLoader) shouldStopOnError(err error) bool {
return false
}
-func (r *schemaLoader) setSchemaID(target interface{}, id, basePath string) (string, string) {
+func (r *schemaLoader) setSchemaID(target any, id, basePath string) (string, string) {
debugLog("schema has ID: %s", id)
// handling the case when id is a folder
@@ -299,11 +289,11 @@ func (r *schemaLoader) setSchemaID(target interface{}, id, basePath string) (str
}
func defaultSchemaLoader(
- root interface{},
+ root any,
expandOptions *ExpandOptions,
cache ResolutionCache,
- context *resolverContext) *schemaLoader {
-
+ context *resolverContext,
+) *schemaLoader {
if expandOptions == nil {
expandOptions = &ExpandOptions{}
}
diff --git a/test/tools/vendor/github.com/go-openapi/spec/security_scheme.go b/test/tools/vendor/github.com/go-openapi/spec/security_scheme.go
index 9d0bdae908..6d9019e749 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/security_scheme.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/security_scheme.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -18,7 +7,7 @@ import (
"encoding/json"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
const (
@@ -31,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,
@@ -50,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,
@@ -59,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,
@@ -68,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,
@@ -78,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"`
@@ -90,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)
@@ -108,8 +97,8 @@ type SecurityScheme struct {
SecuritySchemeProps
}
-// JSONLookup implements an interface to customize json pointer lookup
-func (s SecurityScheme) JSONLookup(token string) (interface{}, error) {
+// 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
}
@@ -118,7 +107,7 @@ func (s SecurityScheme) JSONLookup(token string) (interface{}, error) {
return r, err
}
-// MarshalJSON marshal this to JSON
+// MarshalJSON marshal this to JSON.
func (s SecurityScheme) MarshalJSON() ([]byte, error) {
var (
b1 []byte
@@ -158,10 +147,10 @@ func (s SecurityScheme) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2), nil
+ 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/test/tools/vendor/github.com/go-openapi/spec/spec.go b/test/tools/vendor/github.com/go-openapi/spec/spec.go
index 876aa12759..4eba04b2d1 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/spec.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/spec.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -24,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 {
@@ -39,7 +28,7 @@ func MustLoadJSONSchemaDraft04() *Schema {
return d
}
-// JSONSchemaDraft04 loads the json schema document for json shema draft04
+// JSONSchemaDraft04 loads the json schema document for json schema draft04.
func JSONSchemaDraft04() (*Schema, error) {
b, err := jsonschemaDraft04JSONBytes()
if err != nil {
@@ -53,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 {
@@ -62,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/test/tools/vendor/github.com/go-openapi/spec/swagger.go b/test/tools/vendor/github.com/go-openapi/spec/swagger.go
index 1590fd1751..dbe32db8a3 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/swagger.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/swagger.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -19,10 +8,11 @@ import (
"encoding/gob"
"encoding/json"
"fmt"
+ "slices"
"strconv"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "github.com/go-openapi/swag/jsonutils"
)
// Swagger this is the root document object for the API specification.
@@ -35,8 +25,8 @@ type Swagger struct {
SwaggerProps
}
-// JSONLookup look up a value by the json property name
-func (s Swagger) JSONLookup(token string) (interface{}, error) {
+// 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
}
@@ -44,7 +34,7 @@ func (s Swagger) JSONLookup(token string) (interface{}, 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 {
@@ -54,10 +44,10 @@ func (s Swagger) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2), nil
+ 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 {
@@ -70,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 {
@@ -84,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
@@ -105,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"`
@@ -136,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),
@@ -181,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
@@ -217,17 +207,17 @@ 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
-func (s SchemaOrBool) JSONLookup(token string) (interface{}, error) {
+// JSONLookup implements an interface to customize json pointer lookup.
+func (s SchemaOrBool) JSONLookup(token string) (any, error) {
if token == "allows" {
return s.Allows, nil
}
@@ -235,10 +225,12 @@ func (s SchemaOrBool) JSONLookup(token string) (interface{}, 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)
@@ -250,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 {
@@ -267,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
-func (s SchemaOrStringArray) JSONLookup(token string) (interface{}, error) {
+// 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)
@@ -290,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 {
@@ -328,21 +320,16 @@ 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 {
- for _, str := range s {
- if str == value {
- return true
- }
- }
- return false
+ return slices.Contains(s, value)
}
-// JSONLookup implements an interface to customize json pointer lookup
-func (s SchemaOrArray) JSONLookup(token string) (interface{}, error) {
+// 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)
return r, err
@@ -351,7 +338,7 @@ func (s SchemaOrArray) JSONLookup(token string) (interface{}, 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 {
@@ -367,7 +354,7 @@ func (s *StringOrArray) UnmarshalJSON(data []byte) error {
return nil
}
- var single interface{}
+ var single any
if err := json.Unmarshal(data, &single); err != nil {
return err
}
@@ -379,11 +366,11 @@ func (s *StringOrArray) UnmarshalJSON(data []byte) error {
*s = StringOrArray([]string{v})
return nil
default:
- return fmt.Errorf("only string or array is allowed, not %T", single)
+ return fmt.Errorf("only string or array is allowed, not %T: %w", single, ErrSpec)
}
}
-// 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])
@@ -392,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
@@ -406,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)
@@ -414,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)
@@ -422,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/test/tools/vendor/github.com/go-openapi/spec/tag.go b/test/tools/vendor/github.com/go-openapi/spec/tag.go
index faa3d3de1e..af3fb0a4e8 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/tag.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/tag.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -18,21 +7,16 @@ import (
"encoding/json"
"github.com/go-openapi/jsonpointer"
- "github.com/go-openapi/swag"
+ "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"`
ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
}
-// NewTag creates a new tag
-func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag {
- return Tag{TagProps: TagProps{Description: description, Name: name, ExternalDocs: externalDocs}}
-}
-
// Tag allows adding meta data to a single tag that is used by the
// [Operation Object](http://goo.gl/8us55a#operationObject).
// It is not mandatory to have a Tag Object per tag used there.
@@ -43,8 +27,13 @@ type Tag struct {
TagProps
}
-// JSONLookup implements an interface to customize json pointer lookup
-func (t Tag) JSONLookup(token string) (interface{}, error) {
+// 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.
+func (t Tag) JSONLookup(token string) (any, error) {
if ex, ok := t.Extensions[token]; ok {
return &ex, nil
}
@@ -53,7 +42,7 @@ func (t Tag) JSONLookup(token string) (interface{}, 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 {
@@ -63,10 +52,10 @@ func (t Tag) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return swag.ConcatJSON(b1, b2), nil
+ 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/test/tools/vendor/github.com/go-openapi/spec/url_go19.go b/test/tools/vendor/github.com/go-openapi/spec/url_go19.go
index 5bdfe40bcc..8d0c81acd6 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/url_go19.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/url_go19.go
@@ -1,3 +1,6 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
package spec
import "net/url"
diff --git a/test/tools/vendor/github.com/go-openapi/spec/validations.go b/test/tools/vendor/github.com/go-openapi/spec/validations.go
index 6360a8ea77..a82c2ffe13 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/validations.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/validations.go
@@ -1,19 +1,22 @@
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
+
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"`
- Minimum *float64 `json:"minimum,omitempty"`
- ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
- MaxLength *int64 `json:"maxLength,omitempty"`
- MinLength *int64 `json:"minLength,omitempty"`
- Pattern string `json:"pattern,omitempty"`
- MaxItems *int64 `json:"maxItems,omitempty"`
- MinItems *int64 `json:"minItems,omitempty"`
- UniqueItems bool `json:"uniqueItems,omitempty"`
- MultipleOf *float64 `json:"multipleOf,omitempty"`
- Enum []interface{} `json:"enum,omitempty"`
+ Maximum *float64 `json:"maximum,omitempty"`
+ ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
+ Minimum *float64 `json:"minimum,omitempty"`
+ ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
+ MaxLength *int64 `json:"maxLength,omitempty"`
+ MinLength *int64 `json:"minLength,omitempty"`
+ Pattern string `json:"pattern,omitempty"`
+ MaxItems *int64 `json:"maxItems,omitempty"`
+ MinItems *int64 `json:"minItems,omitempty"`
+ UniqueItems bool `json:"uniqueItems,omitempty"`
+ MultipleOf *float64 `json:"multipleOf,omitempty"`
+ Enum []any `json:"enum,omitempty"`
}
// SetValidations defines all validations for a simple schema.
@@ -37,12 +40,12 @@ func (v *CommonValidations) SetValidations(val SchemaValidations) {
type clearedValidation struct {
Validation string
- Value interface{}
+ Value any
}
type clearedValidations []clearedValidation
-func (c clearedValidations) apply(cbs []func(string, interface{})) {
+func (c clearedValidations) apply(cbs []func(string, any)) {
for _, cb := range cbs {
for _, cleared := range c {
cb(cleared.Validation, cleared.Value)
@@ -53,8 +56,9 @@ func (c clearedValidations) apply(cbs []func(string, interface{})) {
// ClearNumberValidations clears all number validations.
//
// Some callbacks may be set by the caller to capture changed values.
-func (v *CommonValidations) ClearNumberValidations(cbs ...func(string, interface{})) {
- done := make(clearedValidations, 0, 5)
+func (v *CommonValidations) ClearNumberValidations(cbs ...func(string, any)) {
+ const maxNumberValidations = 5
+ done := make(clearedValidations, 0, maxNumberValidations)
defer func() {
done.apply(cbs)
}()
@@ -84,8 +88,9 @@ func (v *CommonValidations) ClearNumberValidations(cbs ...func(string, interface
// ClearStringValidations clears all string validations.
//
// Some callbacks may be set by the caller to capture changed values.
-func (v *CommonValidations) ClearStringValidations(cbs ...func(string, interface{})) {
- done := make(clearedValidations, 0, 3)
+func (v *CommonValidations) ClearStringValidations(cbs ...func(string, any)) {
+ const maxStringValidations = 3
+ done := make(clearedValidations, 0, maxStringValidations)
defer func() {
done.apply(cbs)
}()
@@ -107,8 +112,9 @@ func (v *CommonValidations) ClearStringValidations(cbs ...func(string, interface
// ClearArrayValidations clears all array validations.
//
// Some callbacks may be set by the caller to capture changed values.
-func (v *CommonValidations) ClearArrayValidations(cbs ...func(string, interface{})) {
- done := make(clearedValidations, 0, 3)
+func (v *CommonValidations) ClearArrayValidations(cbs ...func(string, any)) {
+ const maxArrayValidations = 3
+ done := make(clearedValidations, 0, maxArrayValidations)
defer func() {
done.apply(cbs)
}()
@@ -137,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
}
@@ -160,7 +166,7 @@ func (v CommonValidations) HasEnum() bool {
// SchemaValidations describes the validation properties of a schema
//
// NOTE: at this moment, this is not embedded in SchemaProps because this would induce a breaking change
-// in the exported members: all initializers using litterals would fail.
+// in the exported members: all initializers using literals would fail.
type SchemaValidations struct {
CommonValidations
@@ -169,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
@@ -182,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
@@ -194,8 +200,9 @@ func (v SchemaValidations) Validations() SchemaValidations {
// ClearObjectValidations returns a clone of the validations with all object validations cleared.
//
// Some callbacks may be set by the caller to capture changed values.
-func (v *SchemaValidations) ClearObjectValidations(cbs ...func(string, interface{})) {
- done := make(clearedValidations, 0, 3)
+func (v *SchemaValidations) ClearObjectValidations(cbs ...func(string, any)) {
+ const maxObjectValidations = 3
+ done := make(clearedValidations, 0, maxObjectValidations)
defer func() {
done.apply(cbs)
}()
diff --git a/test/tools/vendor/github.com/go-openapi/spec/xml_object.go b/test/tools/vendor/github.com/go-openapi/spec/xml_object.go
index 945a46703d..07f7ef8ccd 100644
--- a/test/tools/vendor/github.com/go-openapi/spec/xml_object.go
+++ b/test/tools/vendor/github.com/go-openapi/spec/xml_object.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package spec
@@ -25,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/test/tools/vendor/github.com/go-openapi/strfmt/.codecov.yml b/test/tools/vendor/github.com/go-openapi/strfmt/.codecov.yml
new file mode 100644
index 0000000000..a5ba8e96d8
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/strfmt/.codecov.yml
@@ -0,0 +1,9 @@
+codecov:
+ notify:
+ after_n_builds: 2
+
+coverage:
+ status:
+ patch:
+ default:
+ target: 80%
diff --git a/test/tools/vendor/github.com/go-openapi/strfmt/.gitignore b/test/tools/vendor/github.com/go-openapi/strfmt/.gitignore
index dd91ed6a04..885dc27ab0 100644
--- a/test/tools/vendor/github.com/go-openapi/strfmt/.gitignore
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/strfmt/.golangci.yml b/test/tools/vendor/github.com/go-openapi/strfmt/.golangci.yml
index 22f8d21cca..3c4cd489a1 100644
--- a/test/tools/vendor/github.com/go-openapi/strfmt/.golangci.yml
+++ b/test/tools/vendor/github.com/go-openapi/strfmt/.golangci.yml
@@ -1,61 +1,68 @@
-linters-settings:
- govet:
- check-shadowing: true
- golint:
- min-confidence: 0
- gocyclo:
- min-complexity: 45
- maligned:
- suggest-new: true
- dupl:
- threshold: 200
- goconst:
- min-len: 2
- min-occurrences: 3
-
+version: "2"
linters:
- enable-all: true
+ default: all
disable:
- - maligned
- - unparam
- - lll
- - gochecknoinits
- - gochecknoglobals
- - funlen
- - godox
- - gocognit
- - whitespace
- - wsl
- - wrapcheck
- - testpackage
- - nlreturn
- - gomnd
- - exhaustivestruct
- - goerr113
- - errorlint
- - nestif
- - godot
- - gofumpt
- - paralleltest
- - tparallel
- - thelper
- - ifshort
- - exhaustruct
- - varnamelen
- - gci
- depguard
- - errchkjson
- - inamedparam
+ - funlen
+ - gomoddirectives
+ - godox
+ - exhaustruct
+ - nlreturn
- nonamedreturns
- - musttag
- - ireturn
- - forcetypeassert
- - cyclop
- # deprecated linters
- - deadcode
- - interfacer
- - scopelint
- - varcheck
- - structcheck
- - golint
- - nosnakecase
+ - noinlineerr
+ - paralleltest
+ - recvcheck
+ - testpackage
+ - thelper
+ - tparallel
+ - varnamelen
+ - whitespace
+ - wrapcheck
+ - wsl
+ - wsl_v5
+ settings:
+ dupl:
+ threshold: 200
+ goconst:
+ min-len: 2
+ min-occurrences: 3
+ cyclop:
+ max-complexity: 20
+ gocyclo:
+ min-complexity: 20
+ exhaustive:
+ default-signifies-exhaustive: true
+ default-case-required: true
+ lll:
+ line-length: 180
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ - goimports
+ - gofumpt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ # Maximum issues count per one linter.
+ # Set to 0 to disable.
+ # Default: 50
+ max-issues-per-linter: 0
+ # Maximum count of issues with the same text.
+ # Set to 0 to disable.
+ # Default: 3
+ max-same-issues: 0
diff --git a/test/tools/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md b/test/tools/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md
index 9322b065e3..bac878f216 100644
--- a/test/tools/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/strfmt/CONTRIBUTORS.md b/test/tools/vendor/github.com/go-openapi/strfmt/CONTRIBUTORS.md
new file mode 100644
index 0000000000..e49700d4d2
--- /dev/null
+++ b/test/tools/vendor/github.com/go-openapi/strfmt/CONTRIBUTORS.md
@@ -0,0 +1,52 @@
+# Contributors
+
+- Repository: ['go-openapi/strfmt']
+
+| Total Contributors | Total Contributions |
+| --- | --- |
+| 40 | 225 |
+
+| Username | All Time Contribution Count | All Commits |
+| --- | --- | --- |
+| @casualjim | 88 | |
+| @fredbi | 57 | |
+| @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-community-projects/contributors)_
diff --git a/test/tools/vendor/github.com/go-openapi/strfmt/README.md b/test/tools/vendor/github.com/go-openapi/strfmt/README.md
index f6b39c6c56..a0cf642754 100644
--- a/test/tools/vendor/github.com/go-openapi/strfmt/README.md
+++ b/test/tools/vendor/github.com/go-openapi/strfmt/README.md
@@ -1,15 +1,61 @@
-# Strfmt [](https://github.com/go-openapi/strfmt/actions?query=workflow%3A"go+test") [](https://codecov.io/gh/go-openapi/strfmt)
-[](https://slackin.goswagger.io)
-[](https://raw.githubusercontent.com/go-openapi/strfmt/master/LICENSE)
-[](http://godoc.org/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.
-## Supported data formats
-go-openapi/strfmt follows the swagger 2.0 specification with the following formats
+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
+
+`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.
@@ -35,7 +81,7 @@ It also provides convenient extensions to go-openapi users.
- mac (e.g "01:02:03:04:05:06")
- rgbcolor (e.g. "rgb(100,100,100)")
- ssn
- - uuid, uuid3, uuid4, uuid5
+ - uuid, uuid3, uuid4, uuid5, uuid7
- cidr (e.g. "192.0.2.1/24", "2001:db8:a0b:12f0::1/32")
- ulid (e.g. "00000PP9HGSBSSDZ1JTEXBJ0PW", [spec](https://github.com/ulid/spec))
@@ -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
@@ -81,7 +128,103 @@ List of defined types:
- SSN
- URI
- UUID
-- UUID3
-- UUID4
-- UUID5
+- [UUID3](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-3)
+- [UUID4](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-4)
+- [UUID5](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-5)
+- [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/FfnFYaC3k5
+
+
+[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/test/tools/vendor/github.com/go-openapi/strfmt/SECURITY.md b/test/tools/vendor/github.com/go-openapi/strfmt/SECURITY.md
new file mode 100644
index 0000000000..6ceb159ca2
--- /dev/null
+++ b/test/tools/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/test/tools/vendor/github.com/go-openapi/strfmt/bson.go b/test/tools/vendor/github.com/go-openapi/strfmt/bson.go
index cfa9a526fe..16a83f6408 100644
--- a/test/tools/vendor/github.com/go-openapi/strfmt/bson.go
+++ b/test/tools/vendor/github.com/go-openapi/strfmt/bson.go
@@ -1,81 +1,67 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package strfmt
import (
"database/sql/driver"
+ "encoding/hex"
+ "encoding/json"
"fmt"
-
- "go.mongodb.org/mongo-driver/bson"
-
- "go.mongodb.org/mongo-driver/bson/bsontype"
- 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,stylecheck
+// swagger:strfmt bsonobjectid.
+type ObjectId [12]byte //nolint:revive
-// NewObjectId creates a ObjectId from a Hex String
-func NewObjectId(hex string) ObjectId { //nolint:revive,stylecheck
- oid, err := bsonprim.ObjectIDFromHex(hex)
+// nilObjectID is the zero-value ObjectId.
+var nilObjectID ObjectId //nolint:gochecknoglobals // package-level sentinel
+
+// NewObjectId creates a [ObjectId] from a hexadecimal String.
+func NewObjectId(hex string) ObjectId { //nolint:revive
+ 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
-func (id *ObjectId) Scan(raw interface{}) error {
+// Scan read a value from a database driver.
+func (id *ObjectId) Scan(raw any) error {
var data []byte
switch v := raw.(type) {
case []byte:
@@ -83,69 +69,42 @@ func (id *ObjectId) Scan(raw interface{}) error {
case string:
data = []byte(v)
default:
- return fmt.Errorf("cannot sql.Scan() strfmt.URI from: %#v", v)
+ return fmt.Errorf("cannot sql.Scan() strfmt.URI from: %#v: %w", v, ErrFormat)
}
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
}
- *id = ObjectId(obj)
- return nil
-}
-
-// MarshalBSON renders the object id as a BSON document
-func (id ObjectId) MarshalBSON() ([]byte, error) {
- return bson.Marshal(bson.M{"data": bsonprim.ObjectID(id)})
-}
-
-// 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 {
+ oid, err := objectIDFromHex(hexStr)
+ if err != nil {
return err
}
- *id = ObjectId(obj.Data)
- 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
- copy(oid[:], data)
- *id = ObjectId(oid)
+ *id = oid
return nil
}
@@ -154,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
@@ -163,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/test/tools/vendor/github.com/go-openapi/strfmt/date.go b/test/tools/vendor/github.com/go-openapi/strfmt/date.go
index 3c93381c7c..59ee1f1121 100644
--- a/test/tools/vendor/github.com/go-openapi/strfmt/date.go
+++ b/test/tools/vendor/github.com/go-openapi/strfmt/date.go
@@ -1,58 +1,43 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package strfmt
import (
"database/sql/driver"
"encoding/json"
- "errors"
"fmt"
"time"
-
- "go.mongodb.org/mongo-driver/bson"
)
-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
@@ -65,13 +50,13 @@ 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
}
// Scan scans a Date value from database driver type.
-func (d *Date) Scan(raw interface{}) error {
+func (d *Date) Scan(raw any) error {
switch v := raw.(type) {
case []byte:
return d.UnmarshalText(v)
@@ -84,7 +69,7 @@ func (d *Date) Scan(raw interface{}) error {
*d = Date{}
return nil
default:
- return fmt.Errorf("cannot sql.Scan() strfmt.Date from: %#v", v)
+ return fmt.Errorf("cannot sql.Scan() strfmt.Date from: %#v: %w", v, ErrFormat)
}
}
@@ -93,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
@@ -115,28 +100,6 @@ func (d *Date) UnmarshalJSON(data []byte) error {
return nil
}
-func (d Date) MarshalBSON() ([]byte, error) {
- return bson.Marshal(bson.M{"data": d.String()})
-}
-
-func (d *Date) UnmarshalBSON(data []byte) error {
- var m bson.M
- if err := bson.Unmarshal(data, &m); 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
- }
-
- return errors.New("couldn't unmarshal bson bytes value as Date")
-}
-
// DeepCopyInto copies the receiver and writes its value into out.
func (d *Date) DeepCopyInto(out *Date) {
*out = *d
@@ -162,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
@@ -181,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/test/tools/vendor/github.com/go-openapi/strfmt/default.go b/test/tools/vendor/github.com/go-openapi/strfmt/default.go
index 2813714060..87d3856ad2 100644
--- a/test/tools/vendor/github.com/go-openapi/strfmt/default.go
+++ b/test/tools/vendor/github.com/go-openapi/strfmt/default.go
@@ -1,16 +1,5 @@
-// Copyright 2015 go-swagger maintainers
-//
-// 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.
+// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
+// SPDX-License-Identifier: Apache-2.0
package strfmt
@@ -18,121 +7,367 @@ import (
"database/sql/driver"
"encoding/base64"
"encoding/json"
- "errors"
"fmt"
+ "net"
"net/mail"
+ "net/netip"
+ "net/url"
"regexp"
+ "strconv"
"strings"
- "github.com/asaskevich/govalidator"
"github.com/google/uuid"
- "go.mongodb.org/mongo-driver/bson"
+ "golang.org/x/net/idna"
)
const (
- // HostnamePattern http://json-schema.org/latest/json-schema-validation.html#anchor114
- // A string instance is valid against this attribute if it is a valid
- // representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034].
- // http://tools.ietf.org/html/rfc1034#section-3.5
- // ::= any one of the ten digits 0 through 9
- // var digit = /[0-9]/;
- // ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
- // var letter = /[a-zA-Z]/;
- // ::= |
- // var letDig = /[0-9a-zA-Z]/;
- // ::= | "-"
- // var letDigHyp = /[-0-9a-zA-Z]/;
- // ::= |
- // var ldhStr = /[-0-9a-zA-Z]+/;
- //