diff --git a/go.mod b/go.mod index e760278a..a0aab77c 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ toolchain go1.24.6 require ( github.com/stretchr/testify v1.11.1 - github.com/tektoncd/pipeline v0.66.0 + github.com/tektoncd/pipeline v1.3.1 github.com/tektoncd/plumbing v0.0.0-20250805154627-25448098dea2 go.opentelemetry.io/otel v1.38.0 go.opentelemetry.io/otel/metric v1.38.0 @@ -60,15 +60,13 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect github.com/golang/protobuf v1.5.4 // indirect - github.com/google/cel-go v0.23.2 // indirect + github.com/google/cel-go v0.26.0 // indirect github.com/google/gnostic-models v0.6.9 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/go-containerregistry v0.20.6 // indirect github.com/google/uuid v1.6.0 // indirect github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect @@ -82,7 +80,7 @@ require ( github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_golang v1.23.0 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.65.0 // indirect @@ -120,10 +118,10 @@ require ( golang.org/x/sys v0.35.0 // indirect golang.org/x/term v0.34.0 // indirect golang.org/x/text v0.28.0 // indirect - golang.org/x/time v0.10.0 // indirect + golang.org/x/time v0.12.0 // indirect golang.org/x/tools v0.36.0 // indirect gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect - google.golang.org/api v0.183.0 // indirect + google.golang.org/api v0.233.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250811230008-5f3141c8851a // indirect google.golang.org/grpc v1.74.2 // indirect diff --git a/go.sum b/go.sum index 721348e9..04b85c84 100644 --- a/go.sum +++ b/go.sum @@ -69,8 +69,8 @@ github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWR github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cloudevents/sdk-go/v2 v2.15.2 h1:54+I5xQEnI73RBhWHxbI1XJcqOFOVJN85vb41+8mHUc= -github.com/cloudevents/sdk-go/v2 v2.15.2/go.mod h1:lL7kSWAE/V8VI4Wh0jbL2v/jvqsm6tjmaQBSvxcv4uE= +github.com/cloudevents/sdk-go/v2 v2.16.1 h1:G91iUdqvl88BZ1GYYr9vScTj5zzXSyEuqbfE63gbu9Q= +github.com/cloudevents/sdk-go/v2 v2.16.1/go.mod h1:v/kVOaWjNfbvc6tkhhlkhvLapj8Aa8kvXiH5GiOHCKI= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/containerd/stargz-snapshotter/estargz v0.16.3 h1:7evrXtoh1mSbGj/pfRccTampEyKpjpOnS3CyiV1Ebr8= github.com/containerd/stargz-snapshotter/estargz v0.16.3/go.mod h1:uyr4BfYfOj3G9WBVE8cOlQmXAbPN9VEQpBBeJIuOipU= @@ -166,8 +166,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/cel-go v0.23.2 h1:UdEe3CvQh3Nv+E/j9r1Y//WO0K0cSyD7/y0bzyLIMI4= -github.com/google/cel-go v0.23.2/go.mod h1:52Pb6QsDbC5kvgxvZhiL9QX1oZEkcUF/ZqaPx1J5Wwo= +github.com/google/cel-go v0.26.0 h1:DPGjXackMpJWH680oGY4lZhYjIameYmR+/6RBdDGmaI= +github.com/google/cel-go v0.26.0/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM= github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -209,11 +209,6 @@ github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc/go.mod h1:+JKpmjMGh github.com/grpc-ecosystem/grpc-gateway v1.14.6/go.mod h1:zdiPV4Yse/1gnckTHtghG4GkDEdKCRJduHpTxT3/jcw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 h1:X5VWvz21y3gzm9Nw/kaUeku/1+uBhcekkmy4IkffJww= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1/go.mod h1:Zanoh4+gvIgluNqcfMVTJueD4wSS5hT7zTt4Mrutd90= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c= @@ -277,8 +272,9 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 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/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= @@ -346,8 +342,8 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stvp/go-udp-testing v0.0.0-20201019212854-469649b16807/go.mod h1:7jxmlfBCDBXRzr0eAQJ48XC1hBu1np4CS5+cHEYfwpc= -github.com/tektoncd/pipeline v0.66.0 h1:WLL98YEgWzblSAD2mPbpZN97tkOC50wiftaW+8+6zTY= -github.com/tektoncd/pipeline v0.66.0/go.mod h1:V3cyfxxc7b3GLT2a13GX2mWA86qmxWhh4mOp4gfFQwQ= +github.com/tektoncd/pipeline v1.3.1 h1:GOp49pAMPCXYX1E/cSc2JAm7j4vEB68DOOhGkSoaAmI= +github.com/tektoncd/pipeline v1.3.1/go.mod h1:924mFZJC0FXYruna4kDisnfFnRowJQgRgLpJuGbjNPQ= github.com/tektoncd/plumbing v0.0.0-20250805154627-25448098dea2 h1:v4UPEbe6MEto5i4ELtiXWBxUAUIAWL5U1DznfPhi4WE= github.com/tektoncd/plumbing v0.0.0-20250805154627-25448098dea2/go.mod h1:BC6F3DlZc+wpUT9YcwG9MoSfb4tUiH2olB9xYoIsB4I= github.com/vbatts/tar-split v0.12.1 h1:CqKoORW7BUWBe7UL/iqTVvkTBOF8UvOMKOIZykxnnbo= @@ -571,8 +567,8 @@ golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4= -golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -644,8 +640,8 @@ google.golang.org/api v0.25.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0M google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.183.0 h1:PNMeRDwo1pJdgNcFQ9GstuLe/noWKIc89pRWRLMvLwE= -google.golang.org/api v0.183.0/go.mod h1:q43adC5/pHoSZTx5h2mSmdF7NcyfW9JuDyIOJAgS9ZQ= +google.golang.org/api v0.233.0 h1:iGZfjXAJiUFSSaekVB7LzXl6tRfEKhUN7FkZN++07tI= +google.golang.org/api v0.233.0/go.mod h1:TCIVLLlcwunlMpZIhIp7Ltk77W+vUSdUKAAIlbxY44c= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/vendor/github.com/google/cel-go/cel/BUILD.bazel b/vendor/github.com/google/cel-go/cel/BUILD.bazel index 81549fb4..c12e4904 100644 --- a/vendor/github.com/google/cel-go/cel/BUILD.bazel +++ b/vendor/github.com/google/cel-go/cel/BUILD.bazel @@ -11,15 +11,17 @@ go_library( "decls.go", "env.go", "folding.go", - "io.go", "inlining.go", + "io.go", "library.go", "macro.go", "optimizer.go", "options.go", "program.go", + "prompt.go", "validator.go", ], + embedsrcs = ["//cel/templates"], importpath = "github.com/google/cel-go/cel", visibility = ["//visibility:public"], deps = [ @@ -29,6 +31,7 @@ go_library( "//common/ast:go_default_library", "//common/containers:go_default_library", "//common/decls:go_default_library", + "//common/env:go_default_library", "//common/functions:go_default_library", "//common/operators:go_default_library", "//common/overloads:go_default_library", @@ -61,9 +64,10 @@ go_test( "decls_test.go", "env_test.go", "folding_test.go", - "io_test.go", "inlining_test.go", + "io_test.go", "optimizer_test.go", + "prompt_test.go", "validator_test.go", ], data = [ @@ -72,6 +76,9 @@ go_test( embed = [ ":go_default_library", ], + embedsrcs = [ + "//cel/testdata:prompts", + ], deps = [ "//common/operators:go_default_library", "//common/overloads:go_default_library", @@ -83,8 +90,8 @@ go_test( "//test/proto2pb:go_default_library", "//test/proto3pb:go_default_library", "@org_golang_google_genproto_googleapis_api//expr/v1alpha1:go_default_library", - "@org_golang_google_protobuf//proto:go_default_library", "@org_golang_google_protobuf//encoding/prototext:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", "@org_golang_google_protobuf//types/known/structpb:go_default_library", "@org_golang_google_protobuf//types/known/wrapperspb:go_default_library", ], diff --git a/vendor/github.com/google/cel-go/cel/decls.go b/vendor/github.com/google/cel-go/cel/decls.go index 41880602..4d4873bd 100644 --- a/vendor/github.com/google/cel-go/cel/decls.go +++ b/vendor/github.com/google/cel-go/cel/decls.go @@ -142,8 +142,23 @@ func Constant(name string, t *Type, v ref.Val) EnvOption { // Variable creates an instance of a variable declaration with a variable name and type. func Variable(name string, t *Type) EnvOption { + return VariableWithDoc(name, t, "") +} + +// VariableWithDoc creates an instance of a variable declaration with a variable name, type, and doc string. +func VariableWithDoc(name string, t *Type, doc string) EnvOption { + return func(e *Env) (*Env, error) { + e.variables = append(e.variables, decls.NewVariableWithDoc(name, t, doc)) + return e, nil + } +} + +// VariableDecls configures a set of fully defined cel.VariableDecl instances in the environment. +func VariableDecls(vars ...*decls.VariableDecl) EnvOption { return func(e *Env) (*Env, error) { - e.variables = append(e.variables, decls.NewVariable(name, t)) + for _, v := range vars { + e.variables = append(e.variables, v) + } return e, nil } } @@ -183,13 +198,38 @@ func Function(name string, opts ...FunctionOpt) EnvOption { if err != nil { return nil, err } - if existing, found := e.functions[fn.Name()]; found { - fn, err = existing.Merge(fn) - if err != nil { - return nil, err + return FunctionDecls(fn)(e) + } +} + +// OverloadSelector selects an overload associated with a given function when it returns true. +// +// Used in combination with the FunctionDecl.Subset method. +type OverloadSelector = decls.OverloadSelector + +// IncludeOverloads defines an OverloadSelector which allow-lists a set of overloads by their ids. +func IncludeOverloads(overloadIDs ...string) OverloadSelector { + return decls.IncludeOverloads(overloadIDs...) +} + +// ExcludeOverloads defines an OverloadSelector which deny-lists a set of overloads by their ids. +func ExcludeOverloads(overloadIDs ...string) OverloadSelector { + return decls.ExcludeOverloads(overloadIDs...) +} + +// FunctionDecls provides one or more fully formed function declarations to be added to the environment. +func FunctionDecls(funcs ...*decls.FunctionDecl) EnvOption { + return func(e *Env) (*Env, error) { + var err error + for _, fn := range funcs { + if existing, found := e.functions[fn.Name()]; found { + fn, err = existing.Merge(fn) + if err != nil { + return nil, err + } } + e.functions[fn.Name()] = fn } - e.functions[fn.Name()] = fn return e, nil } } @@ -197,6 +237,13 @@ func Function(name string, opts ...FunctionOpt) EnvOption { // FunctionOpt defines a functional option for configuring a function declaration. type FunctionOpt = decls.FunctionOpt +// FunctionDocs provides a general usage documentation for the function. +// +// Use OverloadExamples to provide example usage instructions for specific overloads. +func FunctionDocs(docs ...string) FunctionOpt { + return decls.FunctionDocs(docs...) +} + // SingletonUnaryBinding creates a singleton function definition to be used for all function overloads. // // Note, this approach works well if operand is expected to have a specific trait which it implements, @@ -270,6 +317,11 @@ func MemberOverload(overloadID string, args []*Type, resultType *Type, opts ...O // OverloadOpt is a functional option for configuring a function overload. type OverloadOpt = decls.OverloadOpt +// OverloadExamples configures an example of how to invoke the overload. +func OverloadExamples(docs ...string) OverloadOpt { + return decls.OverloadExamples(docs...) +} + // UnaryBinding provides the implementation of a unary overload. The provided function is protected by a runtime // type-guard which ensures runtime type agreement between the overload signature and runtime argument types. func UnaryBinding(binding functions.UnaryOp) OverloadOpt { @@ -288,6 +340,12 @@ func FunctionBinding(binding functions.FunctionOp) OverloadOpt { return decls.FunctionBinding(binding) } +// LateFunctionBinding indicates that the function has a binding which is not known at compile time. +// This is useful for functions which have side-effects or are not deterministically computable. +func LateFunctionBinding() OverloadOpt { + return decls.LateFunctionBinding() +} + // OverloadIsNonStrict enables the function to be called with error and unknown argument values. // // Note: do not use this option unless absoluately necessary as it should be an uncommon feature. diff --git a/vendor/github.com/google/cel-go/cel/env.go b/vendor/github.com/google/cel-go/cel/env.go index 3bfe4289..bb301446 100644 --- a/vendor/github.com/google/cel-go/cel/env.go +++ b/vendor/github.com/google/cel-go/cel/env.go @@ -16,6 +16,8 @@ package cel import ( "errors" + "fmt" + "math" "sync" "github.com/google/cel-go/checker" @@ -24,12 +26,15 @@ import ( celast "github.com/google/cel-go/common/ast" "github.com/google/cel-go/common/containers" "github.com/google/cel-go/common/decls" + "github.com/google/cel-go/common/env" + "github.com/google/cel-go/common/stdlib" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" "github.com/google/cel-go/interpreter" "github.com/google/cel-go/parser" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" + "google.golang.org/protobuf/reflect/protoreflect" ) // Source interface representing a user-provided expression. @@ -127,12 +132,13 @@ type Env struct { Container *containers.Container variables []*decls.VariableDecl functions map[string]*decls.FunctionDecl - macros []parser.Macro + macros []Macro + contextProto protoreflect.MessageDescriptor adapter types.Adapter provider types.Provider features map[int]bool appliedFeatures map[int]bool - libraries map[string]bool + libraries map[string]SingletonLibrary validators []ASTValidator costOptions []checker.CostOption @@ -151,6 +157,134 @@ type Env struct { progOpts []ProgramOption } +// ToConfig produces a YAML-serializable env.Config object from the given environment. +// +// The serialized configuration value is intended to represent a baseline set of config +// options which could be used as input to an EnvOption to configure the majority of the +// environment from a file. +// +// Note: validators, features, flags, and safe-guard settings are not yet supported by +// the serialize method. Since optimizers are a separate construct from the environment +// and the standard expression components (parse, check, evalute), they are also not +// supported by the serialize method. +func (e *Env) ToConfig(name string) (*env.Config, error) { + conf := env.NewConfig(name) + // Container settings + if e.Container != containers.DefaultContainer { + conf.SetContainer(e.Container.Name()) + } + for _, typeName := range e.Container.AliasSet() { + conf.AddImports(env.NewImport(typeName)) + } + + libOverloads := map[string][]string{} + for libName, lib := range e.libraries { + // Track the options which have been configured by a library and + // then diff the library version against the configured function + // to detect incremental overloads or rewrites. + libEnv, _ := NewCustomEnv() + libEnv, _ = Lib(lib)(libEnv) + for fnName, fnDecl := range libEnv.Functions() { + if len(fnDecl.OverloadDecls()) == 0 { + continue + } + overloads, exist := libOverloads[fnName] + if !exist { + overloads = make([]string, 0, len(fnDecl.OverloadDecls())) + } + for _, o := range fnDecl.OverloadDecls() { + overloads = append(overloads, o.ID()) + } + libOverloads[fnName] = overloads + } + subsetLib, canSubset := lib.(LibrarySubsetter) + alias := "" + if aliasLib, canAlias := lib.(LibraryAliaser); canAlias { + alias = aliasLib.LibraryAlias() + libName = alias + } + if libName == "stdlib" && canSubset { + conf.SetStdLib(subsetLib.LibrarySubset()) + continue + } + version := uint32(math.MaxUint32) + if versionLib, isVersioned := lib.(LibraryVersioner); isVersioned { + version = versionLib.LibraryVersion() + } + conf.AddExtensions(env.NewExtension(libName, version)) + } + + // If this is a custom environment without the standard env, mark the stdlib as disabled. + if conf.StdLib == nil && !e.HasLibrary("cel.lib.std") { + conf.SetStdLib(env.NewLibrarySubset().SetDisabled(true)) + } + + // Serialize the variables + vars := make([]*decls.VariableDecl, 0, len(e.Variables())) + stdTypeVars := map[string]*decls.VariableDecl{} + for _, v := range stdlib.Types() { + stdTypeVars[v.Name()] = v + } + for _, v := range e.Variables() { + if _, isStdType := stdTypeVars[v.Name()]; isStdType { + continue + } + vars = append(vars, v) + } + if e.contextProto != nil { + conf.SetContextVariable(env.NewContextVariable(string(e.contextProto.FullName()))) + skipVariables := map[string]bool{} + fields := e.contextProto.Fields() + for i := 0; i < fields.Len(); i++ { + field := fields.Get(i) + variable, err := fieldToVariable(field) + if err != nil { + return nil, fmt.Errorf("could not serialize context field variable %q, reason: %w", field.FullName(), err) + } + skipVariables[variable.Name()] = true + } + for _, v := range vars { + if _, found := skipVariables[v.Name()]; !found { + conf.AddVariableDecls(v) + } + } + } else { + conf.AddVariableDecls(vars...) + } + + // Serialize functions which are distinct from the ones configured by libraries. + for fnName, fnDecl := range e.Functions() { + if excludedOverloads, found := libOverloads[fnName]; found { + if newDecl := fnDecl.Subset(decls.ExcludeOverloads(excludedOverloads...)); newDecl != nil { + conf.AddFunctionDecls(newDecl) + } + } else { + conf.AddFunctionDecls(fnDecl) + } + } + + // Serialize validators + for _, val := range e.Validators() { + // Only add configurable validators to the env.Config as all others are + // expected to be implicitly enabled via extension libraries. + if confVal, ok := val.(ConfigurableASTValidator); ok { + conf.AddValidators(confVal.ToConfig()) + } + } + + // Serialize features + for featID, enabled := range e.features { + featName, found := featureNameByID(featID) + if !found { + // If the feature isn't named, it isn't intended to be publicly exposed + continue + } + conf.AddFeatures(env.NewFeature(featName, enabled)) + } + + return conf, nil +} + // NewEnv creates a program environment configured with the standard library of CEL functions and // macros. The Env value returned can parse and check any CEL program which builds upon the core // features documented in the CEL specification. @@ -194,7 +328,7 @@ func NewCustomEnv(opts ...EnvOption) (*Env, error) { provider: registry, features: map[int]bool{}, appliedFeatures: map[int]bool{}, - libraries: map[string]bool{}, + libraries: map[string]SingletonLibrary{}, validators: []ASTValidator{}, progOpts: []ProgramOption{}, costOptions: []checker.CostOption{}, @@ -362,7 +496,7 @@ func (e *Env) Extend(opts ...EnvOption) (*Env, error) { for k, v := range e.functions { funcsCopy[k] = v } - libsCopy := make(map[string]bool, len(e.libraries)) + libsCopy := make(map[string]SingletonLibrary, len(e.libraries)) for k, v := range e.libraries { libsCopy[k] = v } @@ -376,6 +510,7 @@ func (e *Env) Extend(opts ...EnvOption) (*Env, error) { variables: varsCopy, functions: funcsCopy, macros: macsCopy, + contextProto: e.contextProto, progOpts: progOptsCopy, adapter: adapter, features: featuresCopy, @@ -399,8 +534,8 @@ func (e *Env) HasFeature(flag int) bool { // HasLibrary returns whether a specific SingletonLibrary has been configured in the environment. func (e *Env) HasLibrary(libName string) bool { - configured, exists := e.libraries[libName] - return exists && configured + _, exists := e.libraries[libName] + return exists } // Libraries returns a list of SingletonLibrary that have been configured in the environment. @@ -418,9 +553,27 @@ func (e *Env) HasFunction(functionName string) bool { return ok } -// Functions returns map of Functions, keyed by function name, that have been configured in the environment. +// Functions returns a shallow copy of the Functions, keyed by function name, that have been configured in the environment. func (e *Env) Functions() map[string]*decls.FunctionDecl { - return e.functions + shallowCopy := make(map[string]*decls.FunctionDecl, len(e.functions)) + for nm, fn := range e.functions { + shallowCopy[nm] = fn + } + return shallowCopy +} + +// Variables returns a shallow copy of the variables associated with the environment. +func (e *Env) Variables() []*decls.VariableDecl { + shallowCopy := make([]*decls.VariableDecl, len(e.variables)) + copy(shallowCopy, e.variables) + return shallowCopy +} + +// Macros returns a shallow copy of macros associated with the environment. +func (e *Env) Macros() []Macro { + shallowCopy := make([]Macro, len(e.macros)) + copy(shallowCopy, e.macros) + return shallowCopy } // HasValidator returns whether a specific ASTValidator has been configured in the environment. @@ -433,6 +586,11 @@ func (e *Env) HasValidator(name string) bool { return false } +// Validators returns the set of ASTValidators configured on the environment. +func (e *Env) Validators() []ASTValidator { + return e.validators[:] +} + // Parse parses the input expression value `txt` to a Ast and/or a set of Issues. // // This form of Parse creates a Source value for the input `txt` and forwards to the @@ -502,31 +660,30 @@ func (e *Env) TypeProvider() ref.TypeProvider { return &interopLegacyTypeProvider{Provider: e.provider} } -// UnknownVars returns an interpreter.PartialActivation which marks all variables declared in the -// Env as unknown AttributePattern values. +// UnknownVars returns a PartialActivation which marks all variables declared in the Env as +// unknown AttributePattern values. // -// Note, the UnknownVars will behave the same as an interpreter.EmptyActivation unless the -// PartialAttributes option is provided as a ProgramOption. -func (e *Env) UnknownVars() interpreter.PartialActivation { +// Note, the UnknownVars will behave the same as an cel.NoVars() unless the PartialAttributes +// option is provided as a ProgramOption. +func (e *Env) UnknownVars() PartialActivation { act := interpreter.EmptyActivation() part, _ := PartialVars(act, e.computeUnknownVars(act)...) return part } -// PartialVars returns an interpreter.PartialActivation where all variables not in the input variable +// PartialVars returns a PartialActivation where all variables not in the input variable // set, but which have been configured in the environment, are marked as unknown. // -// The `vars` value may either be an interpreter.Activation or any valid input to the -// interpreter.NewActivation call. +// The `vars` value may either be an Activation or any valid input to the cel.NewActivation call. // // Note, this is equivalent to calling cel.PartialVars and manually configuring the set of unknown // variables. For more advanced use cases of partial state where portions of an object graph, rather // than top-level variables, are missing the PartialVars() method may be a more suitable choice. // -// Note, the PartialVars will behave the same as an interpreter.EmptyActivation unless the -// PartialAttributes option is provided as a ProgramOption. -func (e *Env) PartialVars(vars any) (interpreter.PartialActivation, error) { - act, err := interpreter.NewActivation(vars) +// Note, the PartialVars will behave the same as cel.NoVars() unless the PartialAttributes +// option is provided as a ProgramOption. +func (e *Env) PartialVars(vars any) (PartialActivation, error) { + act, err := NewActivation(vars) if err != nil { return nil, err } @@ -598,10 +755,15 @@ func (e *Env) configure(opts []EnvOption) (*Env, error) { } } - // If the default UTC timezone fix has been enabled, make sure the library is configured - e, err = e.maybeApplyFeature(featureDefaultUTCTimeZone, Lib(timeUTCLibrary{})) - if err != nil { - return nil, err + // If the default UTC timezone has been disabled, configure the legacy overloads + if utcTime, isSet := e.features[featureDefaultUTCTimeZone]; isSet && !utcTime { + if !e.appliedFeatures[featureDefaultUTCTimeZone] { + e.appliedFeatures[featureDefaultUTCTimeZone] = true + e, err = Lib(timeLegacyLibrary{})(e) + if err != nil { + return nil, err + } + } } // Configure the parser. @@ -685,30 +847,9 @@ func (e *Env) getCheckerOrError() (*checker.Env, error) { return e.chk, e.chkErr } -// maybeApplyFeature determines whether the feature-guarded option is enabled, and if so applies -// the feature if it has not already been enabled. -func (e *Env) maybeApplyFeature(feature int, option EnvOption) (*Env, error) { - if !e.HasFeature(feature) { - return e, nil - } - _, applied := e.appliedFeatures[feature] - if applied { - return e, nil - } - e, err := option(e) - if err != nil { - return nil, err - } - // record that the feature has been applied since it will generate declarations - // and functions which will be propagated on Extend() calls and which should only - // be registered once. - e.appliedFeatures[feature] = true - return e, nil -} - // computeUnknownVars determines a set of missing variables based on the input activation and the // environment's configured declaration set. -func (e *Env) computeUnknownVars(vars interpreter.Activation) []*interpreter.AttributePattern { +func (e *Env) computeUnknownVars(vars Activation) []*interpreter.AttributePattern { var unknownPatterns []*interpreter.AttributePattern for _, v := range e.variables { varName := v.Name() diff --git a/vendor/github.com/google/cel-go/cel/folding.go b/vendor/github.com/google/cel-go/cel/folding.go index d7060896..40d843ec 100644 --- a/vendor/github.com/google/cel-go/cel/folding.go +++ b/vendor/github.com/google/cel-go/cel/folding.go @@ -38,6 +38,23 @@ func MaxConstantFoldIterations(limit int) ConstantFoldingOption { } } +// Adds an Activation which provides known values for the folding evaluator +// +// Any values the activation provides will be used by the constant folder and turned into +// literals in the AST. +// +// Defaults to the NoVars() Activation +func FoldKnownValues(knownValues Activation) ConstantFoldingOption { + return func(opt *constantFoldingOptimizer) (*constantFoldingOptimizer, error) { + if knownValues != nil { + opt.knownValues = knownValues + } else { + opt.knownValues = NoVars() + } + return opt, nil + } +} + // NewConstantFoldingOptimizer creates an optimizer which inlines constant scalar an aggregate // literal values within function calls and select statements with their evaluated result. func NewConstantFoldingOptimizer(opts ...ConstantFoldingOption) (ASTOptimizer, error) { @@ -56,6 +73,7 @@ func NewConstantFoldingOptimizer(opts ...ConstantFoldingOption) (ASTOptimizer, e type constantFoldingOptimizer struct { maxFoldIterations int + knownValues Activation } // Optimize queries the expression graph for scalar and aggregate literal expressions within call and @@ -68,7 +86,8 @@ func (opt *constantFoldingOptimizer) Optimize(ctx *OptimizerContext, a *ast.AST) // Walk the list of foldable expression and continue to fold until there are no more folds left. // All of the fold candidates returned by the constantExprMatcher should succeed unless there's // a logic bug with the selection of expressions. - foldableExprs := ast.MatchDescendants(root, constantExprMatcher) + constantExprMatcherCapture := func(e ast.NavigableExpr) bool { return opt.constantExprMatcher(ctx, a, e) } + foldableExprs := ast.MatchDescendants(root, constantExprMatcherCapture) foldCount := 0 for len(foldableExprs) != 0 && foldCount < opt.maxFoldIterations { for _, fold := range foldableExprs { @@ -77,21 +96,27 @@ func (opt *constantFoldingOptimizer) Optimize(ctx *OptimizerContext, a *ast.AST) if fold.Kind() == ast.CallKind && maybePruneBranches(ctx, fold) { continue } + // Late-bound function calls cannot be folded. + if fold.Kind() == ast.CallKind && isLateBoundFunctionCall(ctx, a, fold) { + continue + } // Otherwise, assume all context is needed to evaluate the expression. - err := tryFold(ctx, a, fold) - if err != nil { + err := opt.tryFold(ctx, a, fold) + // Ignore errors for identifiers, since there is no guarantee that the environment + // has a value for them. + if err != nil && fold.Kind() != ast.IdentKind { ctx.ReportErrorAtID(fold.ID(), "constant-folding evaluation failed: %v", err.Error()) return a } } foldCount++ - foldableExprs = ast.MatchDescendants(root, constantExprMatcher) + foldableExprs = ast.MatchDescendants(root, constantExprMatcherCapture) } // Once all of the constants have been folded, try to run through the remaining comprehensions // one last time. In this case, there's no guarantee they'll run, so we only update the // target comprehension node with the literal value if the evaluation succeeds. for _, compre := range ast.MatchDescendants(root, ast.KindMatcher(ast.ComprehensionKind)) { - tryFold(ctx, a, compre) + opt.tryFold(ctx, a, compre) } // If the output is a list, map, or struct which contains optional entries, then prune it @@ -121,7 +146,7 @@ func (opt *constantFoldingOptimizer) Optimize(ctx *OptimizerContext, a *ast.AST) // // If the evaluation succeeds, the input expr value will be modified to become a literal, otherwise // the method will return an error. -func tryFold(ctx *OptimizerContext, a *ast.AST, expr ast.Expr) error { +func (opt *constantFoldingOptimizer) tryFold(ctx *OptimizerContext, a *ast.AST, expr ast.Expr) error { // Assume all context is needed to evaluate the expression. subAST := &Ast{ impl: ast.NewCheckedAST(ast.NewAST(expr, a.SourceInfo()), a.TypeMap(), a.ReferenceMap()), @@ -130,7 +155,11 @@ func tryFold(ctx *OptimizerContext, a *ast.AST, expr ast.Expr) error { if err != nil { return err } - out, _, err := prg.Eval(NoVars()) + activation := opt.knownValues + if activation == nil { + activation = NoVars() + } + out, _, err := prg.Eval(activation) if err != nil { return err } @@ -139,6 +168,15 @@ func tryFold(ctx *OptimizerContext, a *ast.AST, expr ast.Expr) error { return nil } +func isLateBoundFunctionCall(ctx *OptimizerContext, a *ast.AST, expr ast.Expr) bool { + call := expr.AsCall() + function := ctx.Functions()[call.FunctionName()] + if function == nil { + return false + } + return function.HasLateBinding() +} + // maybePruneBranches inspects the non-strict call expression to determine whether // a branch can be removed. Evaluation will naturally prune logical and / or calls, // but conditional will not be pruned cleanly, so this is one small area where the @@ -455,13 +493,15 @@ func adaptLiteral(ctx *OptimizerContext, val ref.Val) (ast.Expr, error) { // Only comprehensions which are not nested are included as possible constant folds, and only // if all variables referenced in the comprehension stack exist are only iteration or // accumulation variables. -func constantExprMatcher(e ast.NavigableExpr) bool { +func (opt *constantFoldingOptimizer) constantExprMatcher(ctx *OptimizerContext, a *ast.AST, e ast.NavigableExpr) bool { switch e.Kind() { case ast.CallKind: return constantCallMatcher(e) case ast.SelectKind: sel := e.AsSelect() // guaranteed to be a navigable value return constantMatcher(sel.Operand().(ast.NavigableExpr)) + case ast.IdentKind: + return opt.knownValues != nil && a.ReferenceMap()[e.ID()] != nil case ast.ComprehensionKind: if isNestedComprehension(e) { return false @@ -477,6 +517,10 @@ func constantExprMatcher(e ast.NavigableExpr) bool { if e.Kind() == ast.IdentKind && !vars[e.AsIdent()] { constantExprs = false } + // Late-bound function calls cannot be folded. + if e.Kind() == ast.CallKind && isLateBoundFunctionCall(ctx, a, e) { + constantExprs = false + } }) ast.PreOrderVisit(e, visitor) return constantExprs diff --git a/vendor/github.com/google/cel-go/cel/io.go b/vendor/github.com/google/cel-go/cel/io.go index a327c967..2e611228 100644 --- a/vendor/github.com/google/cel-go/cel/io.go +++ b/vendor/github.com/google/cel-go/cel/io.go @@ -99,7 +99,13 @@ func AstToParsedExpr(a *Ast) (*exprpb.ParsedExpr, error) { // Note, the conversion may not be an exact replica of the original expression, but will produce // a string that is semantically equivalent and whose textual representation is stable. func AstToString(a *Ast) (string, error) { - return parser.Unparse(a.NativeRep().Expr(), a.NativeRep().SourceInfo()) + return ExprToString(a.NativeRep().Expr(), a.NativeRep().SourceInfo()) +} + +// ExprToString converts an AST Expr node back to a string using macro call tracking metadata from +// source info if any macros are encountered within the expression. +func ExprToString(e ast.Expr, info *ast.SourceInfo) (string, error) { + return parser.Unparse(e, info) } // RefValueToValue converts between ref.Val and google.api.expr.v1alpha1.Value. @@ -120,6 +126,55 @@ func ValueAsAlphaProto(res ref.Val) (*exprpb.Value, error) { return alpha, err } +// RefValToExprValue converts between ref.Val and google.api.expr.v1alpha1.ExprValue. +// The result ExprValue is the serialized proto form. +func RefValToExprValue(res ref.Val) (*exprpb.ExprValue, error) { + return ExprValueAsAlphaProto(res) +} + +// ExprValueAsAlphaProto converts between ref.Val and google.api.expr.v1alpha1.ExprValue. +// The result ExprValue is the serialized proto form. +func ExprValueAsAlphaProto(res ref.Val) (*exprpb.ExprValue, error) { + canonical, err := ExprValueAsProto(res) + if err != nil { + return nil, err + } + alpha := &exprpb.ExprValue{} + err = convertProto(canonical, alpha) + return alpha, err +} + +// ExprValueAsProto converts between ref.Val and cel.expr.ExprValue. +// The result ExprValue is the serialized proto form. +func ExprValueAsProto(res ref.Val) (*celpb.ExprValue, error) { + switch res := res.(type) { + case *types.Unknown: + return &celpb.ExprValue{ + Kind: &celpb.ExprValue_Unknown{ + Unknown: &celpb.UnknownSet{ + Exprs: res.IDs(), + }, + }}, nil + case *types.Err: + return &celpb.ExprValue{ + Kind: &celpb.ExprValue_Error{ + Error: &celpb.ErrorSet{ + // Keeping the error code as UNKNOWN since there's no error codes associated with + // Cel-Go runtime errors. + Errors: []*celpb.Status{{Code: 2, Message: res.Error()}}, + }, + }, + }, nil + default: + val, err := ValueAsProto(res) + if err != nil { + return nil, err + } + return &celpb.ExprValue{ + Kind: &celpb.ExprValue_Value{Value: val}}, nil + } +} + // ValueAsProto converts between ref.Val and cel.expr.Value. // The result Value is the serialized proto form. The ref.Val must not be error or unknown. func ValueAsProto(res ref.Val) (*celpb.Value, error) { diff --git a/vendor/github.com/google/cel-go/cel/library.go b/vendor/github.com/google/cel-go/cel/library.go index c0aef501..59a10e81 100644 --- a/vendor/github.com/google/cel-go/cel/library.go +++ b/vendor/github.com/google/cel-go/cel/library.go @@ -17,11 +17,11 @@ package cel import ( "fmt" "math" - "strconv" - "strings" - "time" + "github.com/google/cel-go/common" "github.com/google/cel-go/common/ast" + "github.com/google/cel-go/common/decls" + "github.com/google/cel-go/common/env" "github.com/google/cel-go/common/operators" "github.com/google/cel-go/common/overloads" "github.com/google/cel-go/common/stdlib" @@ -71,6 +71,23 @@ type SingletonLibrary interface { LibraryName() string } +// LibraryAliaser generates a simple named alias for the library, for use during environment serialization. +type LibraryAliaser interface { + LibraryAlias() string +} + +// LibrarySubsetter provides the subset description associated with the library, nil if not subset. +type LibrarySubsetter interface { + LibrarySubset() *env.LibrarySubset +} + +// LibraryVersioner provides a version number for the library. +// +// If not implemented, the library version will be flagged as 'latest' during environment serialization. +type LibraryVersioner interface { + LibraryVersion() uint32 +} + // Lib creates an EnvOption out of a Library, allowing libraries to be provided as functional args, // and to be linked to each other. func Lib(l Library) EnvOption { @@ -80,7 +97,7 @@ func Lib(l Library) EnvOption { if e.HasLibrary(singleton.LibraryName()) { return e, nil } - e.libraries[singleton.LibraryName()] = true + e.libraries[singleton.LibraryName()] = singleton } var err error for _, opt := range l.CompileOptions() { @@ -94,26 +111,79 @@ func Lib(l Library) EnvOption { } } +// StdLibOption specifies a functional option for configuring the standard CEL library. +type StdLibOption func(*stdLibrary) *stdLibrary + +// StdLibSubset configures the standard library to use a subset of its functions and macros. +// +// Since the StdLib is a singleton library, only the first instance of the StdLib() environment options +// will be configured on the environment which means only the StdLibSubset() initially configured with +// the library will be used. +func StdLibSubset(subset *env.LibrarySubset) StdLibOption { + return func(lib *stdLibrary) *stdLibrary { + lib.subset = subset + return lib + } +} + // StdLib returns an EnvOption for the standard library of CEL functions and macros. -func StdLib() EnvOption { - return Lib(stdLibrary{}) +func StdLib(opts ...StdLibOption) EnvOption { + lib := &stdLibrary{} + for _, o := range opts { + lib = o(lib) + } + return Lib(lib) } // stdLibrary implements the Library interface and provides functional options for the core CEL // features documented in the specification. -type stdLibrary struct{} +type stdLibrary struct { + subset *env.LibrarySubset +} // LibraryName implements the SingletonLibrary interface method. -func (stdLibrary) LibraryName() string { +func (*stdLibrary) LibraryName() string { return "cel.lib.std" } +// LibraryAlias returns the simple name of the library. +func (*stdLibrary) LibraryAlias() string { + return "stdlib" +} + +// LibrarySubset returns the env.LibrarySubset definition associated with the CEL Library. +func (lib *stdLibrary) LibrarySubset() *env.LibrarySubset { + return lib.subset +} + // CompileOptions returns options for the standard CEL function declarations and macros. -func (stdLibrary) CompileOptions() []EnvOption { +func (lib *stdLibrary) CompileOptions() []EnvOption { + funcs := stdlib.Functions() + macros := StandardMacros + if lib.subset != nil { + subMacros := []Macro{} + for _, m := range macros { + if lib.subset.SubsetMacro(m.Function()) { + subMacros = append(subMacros, m) + } + } + macros = subMacros + subFuncs := []*decls.FunctionDecl{} + for _, fn := range funcs { + if f, include := lib.subset.SubsetFunction(fn); include { + subFuncs = append(subFuncs, f) + } + } + funcs = subFuncs + } return []EnvOption{ func(e *Env) (*Env, error) { var err error - for _, fn := range stdlib.Functions() { + if err = lib.subset.Validate(); err != nil { + return nil, err + } + e.variables = append(e.variables, stdlib.Types()...) + for _, fn := range funcs { existing, found := e.functions[fn.Name()] if found { fn, err = existing.Merge(fn) @@ -125,16 +195,12 @@ func (stdLibrary) CompileOptions() []EnvOption { } return e, nil }, - func(e *Env) (*Env, error) { - e.variables = append(e.variables, stdlib.Types()...) - return e, nil - }, - Macros(StandardMacros...), + Macros(macros...), } } // ProgramOptions returns function implementations for the standard CEL functions. -func (stdLibrary) ProgramOptions() []ProgramOption { +func (*stdLibrary) ProgramOptions() []ProgramOption { return []ProgramOption{} } @@ -263,7 +329,7 @@ func (stdLibrary) ProgramOptions() []ProgramOption { // be expressed with `optMap`. // // msg.?elements.optFlatMap(e, e[?0]) // return the first element if present. - +// // # First // // Introduced in version: 2 @@ -272,7 +338,7 @@ func (stdLibrary) ProgramOptions() []ProgramOption { // optional.None. // // [1, 2, 3].first().value() == 1 - +// // # Last // // Introduced in version: 2 @@ -283,7 +349,7 @@ func (stdLibrary) ProgramOptions() []ProgramOption { // [1, 2, 3].last().value() == 3 // // This is syntactic sugar for msg.elements[msg.elements.size()-1]. - +// // # Unwrap / UnwrapOpt // // Introduced in version: 2 @@ -293,7 +359,6 @@ func (stdLibrary) ProgramOptions() []ProgramOption { // // optional.unwrap([optional.of(42), optional.none()]) == [42] // [optional.of(42), optional.none()].unwrapOpt() == [42] - func OptionalTypes(opts ...OptionalTypesOption) EnvOption { lib := &optionalLib{version: math.MaxUint32} for _, opt := range opts { @@ -326,10 +391,20 @@ func OptionalTypesVersion(version uint32) OptionalTypesOption { } // LibraryName implements the SingletonLibrary interface method. -func (lib *optionalLib) LibraryName() string { +func (*optionalLib) LibraryName() string { return "cel.lib.optional" } +// LibraryAlias returns the simple name of the library. +func (*optionalLib) LibraryAlias() string { + return "optional" +} + +// LibraryVersion returns the version of the library. +func (lib *optionalLib) LibraryVersion() uint32 { + return lib.version +} + // CompileOptions implements the Library interface method. func (lib *optionalLib) CompileOptions() []EnvOption { paramTypeK := TypeParamType("K") @@ -347,16 +422,29 @@ func (lib *optionalLib) CompileOptions() []EnvOption { Types(types.OptionalType), // Configure the optMap and optFlatMap macros. - Macros(ReceiverMacro(optMapMacro, 2, optMap)), + Macros(ReceiverMacro(optMapMacro, 2, optMap, + MacroDocs(`perform computation on the value if present and return the result as an optional`), + MacroExamples( + common.MultilineDescription( + `// sub with the prefix 'dev.cel' or optional.none()`, + `request.auth.tokens.?sub.optMap(id, 'dev.cel.' + id)`), + `optional.none().optMap(i, i * 2) // optional.none()`))), // Global and member functions for working with optional values. Function(optionalOfFunc, + FunctionDocs(`create a new optional_type(T) with a value where any value is considered valid`), Overload("optional_of", []*Type{paramTypeV}, optionalTypeV, + OverloadExamples(`optional.of(1) // optional(1)`), UnaryBinding(func(value ref.Val) ref.Val { return types.OptionalOf(value) }))), Function(optionalOfNonZeroValueFunc, + FunctionDocs(`create a new optional_type(T) with a value, if the value is not a zero or empty value`), Overload("optional_ofNonZeroValue", []*Type{paramTypeV}, optionalTypeV, + OverloadExamples( + `optional.ofNonZeroValue(null) // optional.none()`, + `optional.ofNonZeroValue("") // optional.none()`, + `optional.ofNonZeroValue("hello") // optional.of('hello')`), UnaryBinding(func(value ref.Val) ref.Val { v, isZeroer := value.(traits.Zeroer) if !isZeroer || !v.IsZeroValue() { @@ -365,18 +453,26 @@ func (lib *optionalLib) CompileOptions() []EnvOption { return types.OptionalNone }))), Function(optionalNoneFunc, + FunctionDocs(`singleton value representing an optional without a value`), Overload("optional_none", []*Type{}, optionalTypeV, + OverloadExamples(`optional.none()`), FunctionBinding(func(values ...ref.Val) ref.Val { return types.OptionalNone }))), Function(valueFunc, + FunctionDocs(`obtain the value contained by the optional, error if optional.none()`), MemberOverload("optional_value", []*Type{optionalTypeV}, paramTypeV, + OverloadExamples( + `optional.of(1).value() // 1`, + `optional.none().value() // error`), UnaryBinding(func(value ref.Val) ref.Val { opt := value.(*types.Optional) return opt.GetValue() }))), Function(hasValueFunc, + FunctionDocs(`determine whether the optional contains a value`), MemberOverload("optional_hasValue", []*Type{optionalTypeV}, BoolType, + OverloadExamples(`optional.of({1: 2}).hasValue() // true`), UnaryBinding(func(value ref.Val) ref.Val { opt := value.(*types.Optional) return types.Bool(opt.HasValue()) @@ -385,21 +481,43 @@ func (lib *optionalLib) CompileOptions() []EnvOption { // Implementation of 'or' and 'orValue' are special-cased to support short-circuiting in the // evaluation chain. Function("or", - MemberOverload("optional_or_optional", []*Type{optionalTypeV, optionalTypeV}, optionalTypeV)), + FunctionDocs(`chain optional expressions together, picking the first valued optional expression`), + MemberOverload("optional_or_optional", []*Type{optionalTypeV, optionalTypeV}, optionalTypeV, + OverloadExamples( + `optional.none().or(optional.of(1)) // optional.of(1)`, + common.MultilineDescription( + `// either a value from the first list, a value from the second, or optional.none()`, + `[1, 2, 3][?x].or([3, 4, 5][?y])`)))), Function("orValue", - MemberOverload("optional_orValue_value", []*Type{optionalTypeV, paramTypeV}, paramTypeV)), + FunctionDocs(`chain optional expressions together picking the first valued optional or the default value`), + MemberOverload("optional_orValue_value", []*Type{optionalTypeV, paramTypeV}, paramTypeV, + OverloadExamples( + common.MultilineDescription( + `// pick the value for the given key if the key exists, otherwise return 'you'`, + `{'hello': 'world', 'goodbye': 'cruel world'}[?greeting].orValue('you')`)))), // OptSelect is handled specially by the type-checker, so the receiver's field type is used to determine the // optput type. Function(operators.OptSelect, - Overload("select_optional_field", []*Type{DynType, StringType}, optionalTypeV)), + FunctionDocs(`if the field is present create an optional of the field value, otherwise return optional.none()`), + Overload("select_optional_field", []*Type{DynType, StringType}, optionalTypeV, + OverloadExamples( + `msg.?field // optional.of(field) if non-empty, otherwise optional.none()`, + `msg.?field.?nested_field // optional.of(nested_field) if both field and nested_field are non-empty.`))), // OptIndex is handled mostly like any other indexing operation on a list or map, so the type-checker can use // these signatures to determine type-agreement without any special handling. Function(operators.OptIndex, - Overload("list_optindex_optional_int", []*Type{listTypeV, IntType}, optionalTypeV), + FunctionDocs(`if the index is present create an optional of the field value, otherwise return optional.none()`), + Overload("list_optindex_optional_int", []*Type{listTypeV, IntType}, optionalTypeV, + OverloadExamples(`[1, 2, 3][?x] // element value if x is in the list size, else optional.none()`)), Overload("optional_list_optindex_optional_int", []*Type{OptionalType(listTypeV), IntType}, optionalTypeV), - Overload("map_optindex_optional_value", []*Type{mapTypeKV, paramTypeK}, optionalTypeV), + Overload("map_optindex_optional_value", []*Type{mapTypeKV, paramTypeK}, optionalTypeV, + OverloadExamples( + `map_value[?key] // value at the key if present, else optional.none()`, + common.MultilineDescription( + `// map key-value if index is a valid map key, else optional.none()`, + `{0: 2, 2: 4, 6: 8}[?index]`))), Overload("optional_map_optindex_optional_value", []*Type{OptionalType(mapTypeKV), paramTypeK}, optionalTypeV)), // Index overloads to accommodate using an optional value as the operand. @@ -408,45 +526,62 @@ func (lib *optionalLib) CompileOptions() []EnvOption { Overload("optional_map_index_value", []*Type{OptionalType(mapTypeKV), paramTypeK}, optionalTypeV)), } if lib.version >= 1 { - opts = append(opts, Macros(ReceiverMacro(optFlatMapMacro, 2, optFlatMap))) + opts = append(opts, Macros(ReceiverMacro(optFlatMapMacro, 2, optFlatMap, + MacroDocs(`perform computation on the value if present and produce an optional value within the computation`), + MacroExamples( + common.MultilineDescription( + `// m = {'key': {}}`, + `m.?key.optFlatMap(k, k.?subkey) // optional.none()`), + common.MultilineDescription( + `// m = {'key': {'subkey': 'value'}}`, + `m.?key.optFlatMap(k, k.?subkey) // optional.of('value')`), + )))) } if lib.version >= 2 { opts = append(opts, Function("last", + FunctionDocs(`return the last value in a list if present, otherwise optional.none()`), MemberOverload("list_last", []*Type{listTypeV}, optionalTypeV, + OverloadExamples( + `[].last() // optional.none()`, + `[1, 2, 3].last() ? optional.of(3)`), UnaryBinding(func(v ref.Val) ref.Val { list := v.(traits.Lister) - sz := list.Size().Value().(int64) - - if sz == 0 { + sz := list.Size().(types.Int) + if sz == types.IntZero { return types.OptionalNone } - return types.OptionalOf(list.Get(types.Int(sz - 1))) }), ), )) opts = append(opts, Function("first", + FunctionDocs(`return the first value in a list if present, otherwise optional.none()`), MemberOverload("list_first", []*Type{listTypeV}, optionalTypeV, + OverloadExamples( + `[].first() // optional.none()`, + `[1, 2, 3].first() ? optional.of(1)`), UnaryBinding(func(v ref.Val) ref.Val { list := v.(traits.Lister) - sz := list.Size().Value().(int64) - - if sz == 0 { + sz := list.Size().(types.Int) + if sz == types.IntZero { return types.OptionalNone } - return types.OptionalOf(list.Get(types.Int(0))) }), ), )) opts = append(opts, Function(optionalUnwrapFunc, + FunctionDocs(`convert a list of optional values to a list containing only value which are not optional.none()`), Overload("optional_unwrap", []*Type{listOptionalTypeV}, listTypeV, + OverloadExamples(`optional.unwrap([optional.of(1), optional.none()]) // [1]`), UnaryBinding(optUnwrap)))) opts = append(opts, Function(unwrapOptFunc, + FunctionDocs(`convert a list of optional values to a list containing only value which are not optional.none()`), MemberOverload("optional_unwrapOpt", []*Type{listOptionalTypeV}, listTypeV, + OverloadExamples(`[optional.of(1), optional.none()].unwrapOpt() // [1]`), UnaryBinding(optUnwrap)))) } @@ -460,6 +595,11 @@ func (lib *optionalLib) ProgramOptions() []ProgramOption { } } +// Version returns the current version of the library. +func (lib *optionalLib) Version() uint32 { + return lib.version +} + func optMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) { varIdent := args[0] varName := "" @@ -633,250 +773,99 @@ func (opt *evalOptionalOrValue) Eval(ctx interpreter.Activation) ref.Val { return opt.rhs.Eval(ctx) } -type timeUTCLibrary struct{} +type timeLegacyLibrary struct{} -func (timeUTCLibrary) CompileOptions() []EnvOption { +func (timeLegacyLibrary) CompileOptions() []EnvOption { return timeOverloadDeclarations } -func (timeUTCLibrary) ProgramOptions() []ProgramOption { +func (timeLegacyLibrary) ProgramOptions() []ProgramOption { return []ProgramOption{} } // Declarations and functions which enable using UTC on time.Time inputs when the timezone is unspecified // in the CEL expression. var ( - utcTZ = types.String("UTC") - timeOverloadDeclarations = []EnvOption{ - Function(overloads.TimeGetHours, - MemberOverload(overloads.DurationToHours, []*Type{DurationType}, IntType, - UnaryBinding(types.DurationGetHours))), - Function(overloads.TimeGetMinutes, - MemberOverload(overloads.DurationToMinutes, []*Type{DurationType}, IntType, - UnaryBinding(types.DurationGetMinutes))), - Function(overloads.TimeGetSeconds, - MemberOverload(overloads.DurationToSeconds, []*Type{DurationType}, IntType, - UnaryBinding(types.DurationGetSeconds))), - Function(overloads.TimeGetMilliseconds, - MemberOverload(overloads.DurationToMilliseconds, []*Type{DurationType}, IntType, - UnaryBinding(types.DurationGetMilliseconds))), Function(overloads.TimeGetFullYear, MemberOverload(overloads.TimestampToYear, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetFullYear(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetFullYear, overloads.TimestampToYear, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToYearWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetFullYear), - ), ), Function(overloads.TimeGetMonth, MemberOverload(overloads.TimestampToMonth, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetMonth(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetMonth, overloads.TimestampToMonth, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToMonthWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetMonth), - ), ), Function(overloads.TimeGetDayOfYear, MemberOverload(overloads.TimestampToDayOfYear, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetDayOfYear(ts, utcTZ) - }), - ), - MemberOverload(overloads.TimestampToDayOfYearWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(func(ts, tz ref.Val) ref.Val { - return timestampGetDayOfYear(ts, tz) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYear, []ref.Val{}) }), ), ), Function(overloads.TimeGetDayOfMonth, MemberOverload(overloads.TimestampToDayOfMonthZeroBased, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetDayOfMonthZeroBased(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBased, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToDayOfMonthZeroBasedWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetDayOfMonthZeroBased), - ), ), Function(overloads.TimeGetDate, MemberOverload(overloads.TimestampToDayOfMonthOneBased, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetDayOfMonthOneBased(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBased, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToDayOfMonthOneBasedWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetDayOfMonthOneBased), - ), ), Function(overloads.TimeGetDayOfWeek, MemberOverload(overloads.TimestampToDayOfWeek, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetDayOfWeek(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetDayOfWeek, overloads.TimestampToDayOfWeek, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToDayOfWeekWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetDayOfWeek), - ), ), Function(overloads.TimeGetHours, MemberOverload(overloads.TimestampToHours, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetHours(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetHours, overloads.TimestampToHours, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToHoursWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetHours), - ), ), Function(overloads.TimeGetMinutes, MemberOverload(overloads.TimestampToMinutes, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetMinutes(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetMinutes, overloads.TimestampToMinutes, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToMinutesWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetMinutes), - ), ), Function(overloads.TimeGetSeconds, MemberOverload(overloads.TimestampToSeconds, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetSeconds(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetSeconds, overloads.TimestampToSeconds, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToSecondsWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetSeconds), - ), ), Function(overloads.TimeGetMilliseconds, MemberOverload(overloads.TimestampToMilliseconds, []*Type{TimestampType}, IntType, UnaryBinding(func(ts ref.Val) ref.Val { - return timestampGetMilliseconds(ts, utcTZ) + t := ts.(types.Timestamp) + return t.Receive(overloads.TimeGetMilliseconds, overloads.TimestampToMilliseconds, []ref.Val{}) }), ), - MemberOverload(overloads.TimestampToMillisecondsWithTz, []*Type{TimestampType, StringType}, IntType, - BinaryBinding(timestampGetMilliseconds), - ), ), } ) - -func timestampGetFullYear(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Year()) -} - -func timestampGetMonth(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - // CEL spec indicates that the month should be 0-based, but the Time value - // for Month() is 1-based. - return types.Int(t.Month() - 1) -} - -func timestampGetDayOfYear(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.YearDay() - 1) -} - -func timestampGetDayOfMonthZeroBased(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Day() - 1) -} - -func timestampGetDayOfMonthOneBased(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Day()) -} - -func timestampGetDayOfWeek(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Weekday()) -} - -func timestampGetHours(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Hour()) -} - -func timestampGetMinutes(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Minute()) -} - -func timestampGetSeconds(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Second()) -} - -func timestampGetMilliseconds(ts, tz ref.Val) ref.Val { - t, err := inTimeZone(ts, tz) - if err != nil { - return types.NewErrFromString(err.Error()) - } - return types.Int(t.Nanosecond() / 1000000) -} - -func inTimeZone(ts, tz ref.Val) (time.Time, error) { - t := ts.(types.Timestamp) - val := string(tz.(types.String)) - ind := strings.Index(val, ":") - if ind == -1 { - loc, err := time.LoadLocation(val) - if err != nil { - return time.Time{}, err - } - return t.In(loc), nil - } - - // If the input is not the name of a timezone (for example, 'US/Central'), it should be a numerical offset from UTC - // in the format ^(+|-)(0[0-9]|1[0-4]):[0-5][0-9]$. The numerical input is parsed in terms of hours and minutes. - hr, err := strconv.Atoi(string(val[0:ind])) - if err != nil { - return time.Time{}, err - } - min, err := strconv.Atoi(string(val[ind+1:])) - if err != nil { - return time.Time{}, err - } - var offset int - if string(val[0]) == "-" { - offset = hr*60 - min - } else { - offset = hr*60 + min - } - secondsEastOfUTC := int((time.Duration(offset) * time.Minute).Seconds()) - timezone := time.FixedZone("", secondsEastOfUTC) - return t.In(timezone), nil -} diff --git a/vendor/github.com/google/cel-go/cel/macro.go b/vendor/github.com/google/cel-go/cel/macro.go index 4db1fd57..3d3c5be1 100644 --- a/vendor/github.com/google/cel-go/cel/macro.go +++ b/vendor/github.com/google/cel-go/cel/macro.go @@ -142,24 +142,38 @@ type MacroExprHelper interface { NewError(exprID int64, message string) *Error } +// MacroOpt defines a functional option for configuring macro behavior. +type MacroOpt = parser.MacroOpt + +// MacroDocs configures a list of strings into a multiline description for the macro. +func MacroDocs(docs ...string) MacroOpt { + return parser.MacroDocs(docs...) +} + +// MacroExamples configures a list of examples, either as a string or common.MultilineString, +// into an example set to be provided with the macro Documentation() call. +func MacroExamples(examples ...string) MacroOpt { + return parser.MacroExamples(examples...) +} + // GlobalMacro creates a Macro for a global function with the specified arg count. -func GlobalMacro(function string, argCount int, factory MacroFactory) Macro { - return parser.NewGlobalMacro(function, argCount, factory) +func GlobalMacro(function string, argCount int, factory MacroFactory, opts ...MacroOpt) Macro { + return parser.NewGlobalMacro(function, argCount, factory, opts...) } // ReceiverMacro creates a Macro for a receiver function matching the specified arg count. -func ReceiverMacro(function string, argCount int, factory MacroFactory) Macro { - return parser.NewReceiverMacro(function, argCount, factory) +func ReceiverMacro(function string, argCount int, factory MacroFactory, opts ...MacroOpt) Macro { + return parser.NewReceiverMacro(function, argCount, factory, opts...) } // GlobalVarArgMacro creates a Macro for a global function with a variable arg count. -func GlobalVarArgMacro(function string, factory MacroFactory) Macro { - return parser.NewGlobalVarArgMacro(function, factory) +func GlobalVarArgMacro(function string, factory MacroFactory, opts ...MacroOpt) Macro { + return parser.NewGlobalVarArgMacro(function, factory, opts...) } // ReceiverVarArgMacro creates a Macro for a receiver function matching a variable arg count. -func ReceiverVarArgMacro(function string, factory MacroFactory) Macro { - return parser.NewReceiverVarArgMacro(function, factory) +func ReceiverVarArgMacro(function string, factory MacroFactory, opts ...MacroOpt) Macro { + return parser.NewReceiverVarArgMacro(function, factory, opts...) } // NewGlobalMacro creates a Macro for a global function with the specified arg count. diff --git a/vendor/github.com/google/cel-go/cel/options.go b/vendor/github.com/google/cel-go/cel/options.go index 85f777e9..fee67323 100644 --- a/vendor/github.com/google/cel-go/cel/options.go +++ b/vendor/github.com/google/cel-go/cel/options.go @@ -15,6 +15,7 @@ package cel import ( + "errors" "fmt" "google.golang.org/protobuf/proto" @@ -25,6 +26,8 @@ import ( "github.com/google/cel-go/checker" "github.com/google/cel-go/common/containers" + "github.com/google/cel-go/common/decls" + "github.com/google/cel-go/common/env" "github.com/google/cel-go/common/functions" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/pb" @@ -70,6 +73,26 @@ const ( featureIdentEscapeSyntax ) +var featureIDsToNames = map[int]string{ + featureEnableMacroCallTracking: "cel.feature.macro_call_tracking", + featureCrossTypeNumericComparisons: "cel.feature.cross_type_numeric_comparisons", + featureIdentEscapeSyntax: "cel.feature.backtick_escape_syntax", +} + +func featureNameByID(id int) (string, bool) { + name, found := featureIDsToNames[id] + return name, found +} + +func featureIDByName(name string) (int, bool) { + for id, n := range featureIDsToNames { + if n == name { + return id, true + } + } + return 0, false +} + // EnvOption is a functional interface for configuring the environment. type EnvOption func(e *Env) (*Env, error) @@ -112,6 +135,8 @@ func CustomTypeProvider(provider any) EnvOption { // Note: Declarations will by default be appended to the pre-existing declaration set configured // for the environment. The NewEnv call builds on top of the standard CEL declarations. For a // purely custom set of declarations use NewCustomEnv. +// +// Deprecated: use FunctionDecls and VariableDecls or FromConfig instead. func Declarations(decls ...*exprpb.Decl) EnvOption { declOpts := []EnvOption{} var err error @@ -379,7 +404,7 @@ type ProgramOption func(p *prog) (*prog, error) // InterpretableDecorators can be used to inspect, alter, or replace the Program plan. func CustomDecorator(dec interpreter.InterpretableDecorator) ProgramOption { return func(p *prog) (*prog, error) { - p.decorators = append(p.decorators, dec) + p.plannerOptions = append(p.plannerOptions, interpreter.CustomDecorator(dec)) return p, nil } } @@ -401,10 +426,10 @@ func Functions(funcs ...*functions.Overload) ProgramOption { // variables with the same name provided to the Eval() call. If Globals is used in a Library with // a Lib EnvOption, vars may shadow variables provided by previously added libraries. // -// The vars value may either be an `interpreter.Activation` instance or a `map[string]any`. +// The vars value may either be an `cel.Activation` instance or a `map[string]any`. func Globals(vars any) ProgramOption { return func(p *prog) (*prog, error) { - defaultVars, err := interpreter.NewActivation(vars) + defaultVars, err := NewActivation(vars) if err != nil { return nil, err } @@ -426,6 +451,174 @@ func OptimizeRegex(regexOptimizations ...*interpreter.RegexOptimization) Program } } +// ConfigOptionFactory declares a signature which accepts a configuration element, e.g. env.Extension +// and optionally produces an EnvOption in response. +// +// If there are multiple ConfigOptionFactory values which could apply to the same configuration node +// the first one that returns an EnvOption and a `true` response will be used, and the config node +// will not be passed along to any other option factory. +// +// Only the *env.Extension type is provided at this time, but validators, optimizers, and other tuning +// parameters may be supported in the future. +type ConfigOptionFactory func(any) (EnvOption, bool) + +// FromConfig produces and applies a set of EnvOption values derived from an env.Config object. +// +// For configuration elements which refer to features outside of the `cel` package, an optional set of +// ConfigOptionFactory values may be passed in to support the conversion from static configuration to +// configured cel.Env value. +// +// Note: disabling the standard library will clear the EnvOptions values previously set for the +// environment with the exception of propagating types and adapters over to the new environment. +// +// Note: to support custom types referenced in the configuration file, you must ensure that one of +// the following options appears before the FromConfig option: Types, TypeDescs, or CustomTypeProvider +// as the type provider configured at the time when the config is processed is the one used to derive +// type references from the configuration. +func FromConfig(config *env.Config, optFactories ...ConfigOptionFactory) EnvOption { + return func(e *Env) (*Env, error) { + if err := config.Validate(); err != nil { + return nil, err + } + opts, err := configToEnvOptions(config, e.CELTypeProvider(), optFactories) + if err != nil { + return nil, err + } + for _, o := range opts { + e, err = o(e) + if err != nil { + return nil, err + } + } + return e, nil + } +} + +// configToEnvOptions generates a set of EnvOption values (or error) based on a config, a type provider, +// and an optional set of environment options. +func configToEnvOptions(config *env.Config, provider types.Provider, optFactories []ConfigOptionFactory) ([]EnvOption, error) { + envOpts := []EnvOption{} + // Configure the standard lib subset. + if config.StdLib != nil { + envOpts = append(envOpts, func(e *Env) (*Env, error) { + if e.HasLibrary("cel.lib.std") { + return nil, errors.New("invalid subset of stdlib: create a custom env") + } + return e, nil + }) + if !config.StdLib.Disabled { + envOpts = append(envOpts, StdLib(StdLibSubset(config.StdLib))) + } + } else { + envOpts = append(envOpts, StdLib()) + } + + // Configure the container + if config.Container != "" { + envOpts = append(envOpts, Container(config.Container)) + } + + // Configure abbreviations + for _, imp := range config.Imports { + envOpts = append(envOpts, Abbrevs(imp.Name)) + } + + // Configure the context variable declaration + if config.ContextVariable != nil { + typeName := config.ContextVariable.TypeName + if _, found := provider.FindStructType(typeName); !found { + return nil, fmt.Errorf("invalid context proto type: %q", typeName) + } + // Attempt to instantiate the proto in order to reflect to its descriptor + msg := provider.NewValue(typeName, map[string]ref.Val{}) + pbMsg, ok := msg.Value().(proto.Message) + if !ok { + return nil, fmt.Errorf("unsupported context type: %T", msg.Value()) + } + envOpts = append(envOpts, DeclareContextProto(pbMsg.ProtoReflect().Descriptor())) + } + + // Configure variables + if len(config.Variables) != 0 { + vars := make([]*decls.VariableDecl, 0, len(config.Variables)) + for _, v := range config.Variables { + vDef, err := v.AsCELVariable(provider) + if err != nil { + return nil, err + } + vars = append(vars, vDef) + } + envOpts = append(envOpts, VariableDecls(vars...)) + } + + // Configure functions + if len(config.Functions) != 0 { + funcs := make([]*decls.FunctionDecl, 0, len(config.Functions)) + for _, f := range config.Functions { + fnDef, err := f.AsCELFunction(provider) + if err != nil { + return nil, err + } + funcs = append(funcs, fnDef) + } + envOpts = append(envOpts, FunctionDecls(funcs...)) + } + + // Configure features + for _, feat := range config.Features { + // Note, if a feature is not found, it is skipped as it is possible the feature + // is not intended to be supported publicly. In the future, a refinement of + // to this strategy to report unrecognized features and validators should probably + // be covered as a standard ConfigOptionFactory + if id, found := featureIDByName(feat.Name); found { + envOpts = append(envOpts, features(id, feat.Enabled)) + } + } + + // Configure validators + for _, val := range config.Validators { + if fac, found := astValidatorFactories[val.Name]; found { + envOpts = append(envOpts, func(e *Env) (*Env, error) { + validator, err := fac(val) + if err != nil { + return nil, fmt.Errorf("%w", err) + } + return ASTValidators(validator)(e) + }) + } else if opt, handled := handleExtendedConfigOption(val, optFactories); handled { + envOpts = append(envOpts, opt) + } + // we don't error when the validator isn't found as it may be part + // of an extension library and enabled implicitly. + } + + // Configure extensions + for _, ext := range config.Extensions { + // version number has been validated by the call to `Validate` + ver, _ := ext.VersionNumber() + if ext.Name == "optional" { + envOpts = append(envOpts, OptionalTypes(OptionalTypesVersion(ver))) + } else { + opt, handled := handleExtendedConfigOption(ext, optFactories) + if !handled { + return nil, fmt.Errorf("unrecognized extension: %s", ext.Name) + } + envOpts = append(envOpts, opt) + } + } + + return envOpts, nil +} + +func handleExtendedConfigOption(conf any, optFactories []ConfigOptionFactory) (EnvOption, bool) { + for _, optFac := range optFactories { + if opt, useOption := optFac(conf); useOption { + return opt, true + } + } + return nil, false +} + // EvalOption indicates an evaluation option that may affect the evaluation behavior or information // in the output result. type EvalOption int @@ -534,7 +727,7 @@ func fieldToCELType(field protoreflect.FieldDescriptor) (*Type, error) { return nil, fmt.Errorf("field %s type %s not implemented", field.FullName(), field.Kind().String()) } -func fieldToVariable(field protoreflect.FieldDescriptor) (EnvOption, error) { +func fieldToVariable(field protoreflect.FieldDescriptor) (*decls.VariableDecl, error) { name := string(field.Name()) if field.IsMap() { mapKey := field.MapKey() @@ -547,20 +740,20 @@ func fieldToVariable(field protoreflect.FieldDescriptor) (EnvOption, error) { if err != nil { return nil, err } - return Variable(name, MapType(keyType, valueType)), nil + return decls.NewVariable(name, MapType(keyType, valueType)), nil } if field.IsList() { elemType, err := fieldToCELType(field) if err != nil { return nil, err } - return Variable(name, ListType(elemType)), nil + return decls.NewVariable(name, ListType(elemType)), nil } celType, err := fieldToCELType(field) if err != nil { return nil, err } - return Variable(name, celType), nil + return decls.NewVariable(name, celType), nil } // DeclareContextProto returns an option to extend CEL environment with declarations from the given context proto. @@ -568,17 +761,25 @@ func fieldToVariable(field protoreflect.FieldDescriptor) (EnvOption, error) { // https://github.com/google/cel-spec/blob/master/doc/langdef.md#evaluation-environment func DeclareContextProto(descriptor protoreflect.MessageDescriptor) EnvOption { return func(e *Env) (*Env, error) { + if e.contextProto != nil { + return nil, fmt.Errorf("context proto already declared as %q, got %q", + e.contextProto.FullName(), descriptor.FullName()) + } + e.contextProto = descriptor fields := descriptor.Fields() + vars := make([]*decls.VariableDecl, 0, fields.Len()) for i := 0; i < fields.Len(); i++ { field := fields.Get(i) variable, err := fieldToVariable(field) if err != nil { return nil, err } - e, err = variable(e) - if err != nil { - return nil, err - } + vars = append(vars, variable) + } + var err error + e, err = VariableDecls(vars...)(e) + if err != nil { + return nil, err } return Types(dynamicpb.NewMessage(descriptor))(e) } @@ -588,7 +789,7 @@ func DeclareContextProto(descriptor protoreflect.MessageDescriptor) EnvOption { // // Consider using with `DeclareContextProto` to simplify variable type declarations and publishing when using // protocol buffers. -func ContextProtoVars(ctx proto.Message) (interpreter.Activation, error) { +func ContextProtoVars(ctx proto.Message) (Activation, error) { if ctx == nil || !ctx.ProtoReflect().IsValid() { return interpreter.EmptyActivation(), nil } @@ -612,7 +813,7 @@ func ContextProtoVars(ctx proto.Message) (interpreter.Activation, error) { } vars[field.TextName()] = fieldVal } - return interpreter.NewActivation(vars) + return NewActivation(vars) } // EnableMacroCallTracking ensures that call expressions which are replaced by macros diff --git a/vendor/github.com/google/cel-go/cel/program.go b/vendor/github.com/google/cel-go/cel/program.go index 49bd5378..24f41a4a 100644 --- a/vendor/github.com/google/cel-go/cel/program.go +++ b/vendor/github.com/google/cel-go/cel/program.go @@ -29,7 +29,7 @@ import ( type Program interface { // Eval returns the result of an evaluation of the Ast and environment against the input vars. // - // The vars value may either be an `interpreter.Activation` or a `map[string]any`. + // The vars value may either be an `Activation` or a `map[string]any`. // // If the `OptTrackState`, `OptTrackCost` or `OptExhaustiveEval` flags are used, the `details` response will // be non-nil. Given this caveat on `details`, the return state from evaluation will be: @@ -47,14 +47,39 @@ type Program interface { // to support cancellation and timeouts. This method must be used in conjunction with the // InterruptCheckFrequency() option for cancellation interrupts to be impact evaluation. // - // The vars value may either be an `interpreter.Activation` or `map[string]any`. + // The vars value may either be an `Activation` or `map[string]any`. // // The output contract for `ContextEval` is otherwise identical to the `Eval` method. ContextEval(context.Context, any) (ref.Val, *EvalDetails, error) } +// Activation used to resolve identifiers by name and references by id. +// +// An Activation is the primary mechanism by which a caller supplies input into a CEL program. +type Activation = interpreter.Activation + +// NewActivation returns an activation based on a map-based binding where the map keys are +// expected to be qualified names used with ResolveName calls. +// +// The input `bindings` may either be of type `Activation` or `map[string]any`. +// +// Lazy bindings may be supplied within the map-based input in either of the following forms: +// - func() any +// - func() ref.Val +// +// The output of the lazy binding will overwrite the variable reference in the internal map. +// +// Values which are not represented as ref.Val types on input may be adapted to a ref.Val using +// the types.Adapter configured in the environment. +func NewActivation(bindings any) (Activation, error) { + return interpreter.NewActivation(bindings) +} + +// PartialActivation extends the Activation interface with a set of unknown AttributePatterns. +type PartialActivation = interpreter.PartialActivation + // NoVars returns an empty Activation. -func NoVars() interpreter.Activation { +func NoVars() Activation { return interpreter.EmptyActivation() } @@ -64,10 +89,9 @@ func NoVars() interpreter.Activation { // This method relies on manually configured sets of missing attribute patterns. For a method which // infers the missing variables from the input and the configured environment, use Env.PartialVars(). // -// The `vars` value may either be an interpreter.Activation or any valid input to the -// interpreter.NewActivation call. +// The `vars` value may either be an Activation or any valid input to the NewActivation call. func PartialVars(vars any, - unknowns ...*interpreter.AttributePattern) (interpreter.PartialActivation, error) { + unknowns ...*AttributePatternType) (PartialActivation, error) { return interpreter.NewPartialActivation(vars, unknowns...) } @@ -84,12 +108,15 @@ func PartialVars(vars any, // fully qualified variable name may be `ns.app.a`, `ns.a`, or `a` per the CEL namespace resolution // rules. Pick the fully qualified variable name that makes sense within the container as the // AttributePattern `varName` argument. +func AttributePattern(varName string) *AttributePatternType { + return interpreter.NewAttributePattern(varName) +} + +// AttributePatternType represents a top-level variable with an optional set of qualifier patterns. // // See the interpreter.AttributePattern and interpreter.AttributeQualifierPattern for more info // about how to create and manipulate AttributePattern values. -func AttributePattern(varName string) *interpreter.AttributePattern { - return interpreter.NewAttributePattern(varName) -} +type AttributePatternType = interpreter.AttributePattern // EvalDetails holds additional information observed during the Eval() call. type EvalDetails struct { @@ -120,37 +147,24 @@ func (ed *EvalDetails) ActualCost() *uint64 { type prog struct { *Env evalOpts EvalOption - defaultVars interpreter.Activation + defaultVars Activation dispatcher interpreter.Dispatcher interpreter interpreter.Interpreter interruptCheckFrequency uint // Intermediate state used to configure the InterpretableDecorator set provided // to the initInterpretable call. - decorators []interpreter.InterpretableDecorator + plannerOptions []interpreter.PlannerOption regexOptimizations []*interpreter.RegexOptimization // Interpretable configured from an Ast and aggregate decorator set based on program options. interpretable interpreter.Interpretable + observable *interpreter.ObservableInterpretable callCostEstimator interpreter.ActualCostEstimator costOptions []interpreter.CostTrackerOption costLimit *uint64 } -func (p *prog) clone() *prog { - costOptsCopy := make([]interpreter.CostTrackerOption, len(p.costOptions)) - copy(costOptsCopy, p.costOptions) - - return &prog{ - Env: p.Env, - evalOpts: p.evalOpts, - defaultVars: p.defaultVars, - dispatcher: p.dispatcher, - interpreter: p.interpreter, - interruptCheckFrequency: p.interruptCheckFrequency, - } -} - // newProgram creates a program instance with an environment, an ast, and an optional list of // ProgramOption values. // @@ -162,10 +176,10 @@ func newProgram(e *Env, a *ast.AST, opts []ProgramOption) (Program, error) { // Ensure the default attribute factory is set after the adapter and provider are // configured. p := &prog{ - Env: e, - decorators: []interpreter.InterpretableDecorator{}, - dispatcher: disp, - costOptions: []interpreter.CostTrackerOption{}, + Env: e, + plannerOptions: []interpreter.PlannerOption{}, + dispatcher: disp, + costOptions: []interpreter.CostTrackerOption{}, } // Configure the program via the ProgramOption values. @@ -203,74 +217,71 @@ func newProgram(e *Env, a *ast.AST, opts []ProgramOption) (Program, error) { p.interpreter = interp // Translate the EvalOption flags into InterpretableDecorator instances. - decorators := make([]interpreter.InterpretableDecorator, len(p.decorators)) - copy(decorators, p.decorators) + plannerOptions := make([]interpreter.PlannerOption, len(p.plannerOptions)) + copy(plannerOptions, p.plannerOptions) // Enable interrupt checking if there's a non-zero check frequency if p.interruptCheckFrequency > 0 { - decorators = append(decorators, interpreter.InterruptableEval()) + plannerOptions = append(plannerOptions, interpreter.InterruptableEval()) } // Enable constant folding first. if p.evalOpts&OptOptimize == OptOptimize { - decorators = append(decorators, interpreter.Optimize()) + plannerOptions = append(plannerOptions, interpreter.Optimize()) p.regexOptimizations = append(p.regexOptimizations, interpreter.MatchesRegexOptimization) } // Enable regex compilation of constants immediately after folding constants. if len(p.regexOptimizations) > 0 { - decorators = append(decorators, interpreter.CompileRegexConstants(p.regexOptimizations...)) + plannerOptions = append(plannerOptions, interpreter.CompileRegexConstants(p.regexOptimizations...)) } // Enable exhaustive eval, state tracking and cost tracking last since they require a factory. if p.evalOpts&(OptExhaustiveEval|OptTrackState|OptTrackCost) != 0 { - factory := func(state interpreter.EvalState, costTracker *interpreter.CostTracker) (Program, error) { - costTracker.Estimator = p.callCostEstimator - costTracker.Limit = p.costLimit - for _, costOpt := range p.costOptions { - err := costOpt(costTracker) - if err != nil { - return nil, err - } - } - // Limit capacity to guarantee a reallocation when calling 'append(decs, ...)' below. This - // prevents the underlying memory from being shared between factory function calls causing - // undesired mutations. - decs := decorators[:len(decorators):len(decorators)] - var observers []interpreter.EvalObserver - - if p.evalOpts&(OptExhaustiveEval|OptTrackState) != 0 { - // EvalStateObserver is required for OptExhaustiveEval. - observers = append(observers, interpreter.EvalStateObserver(state)) - } - if p.evalOpts&OptTrackCost == OptTrackCost { - observers = append(observers, interpreter.CostObserver(costTracker)) - } - - // Enable exhaustive eval over a basic observer since it offers a superset of features. - if p.evalOpts&OptExhaustiveEval == OptExhaustiveEval { - decs = append(decs, interpreter.ExhaustiveEval(), interpreter.Observe(observers...)) - } else if len(observers) > 0 { - decs = append(decs, interpreter.Observe(observers...)) - } - - return p.clone().initInterpretable(a, decs) + costOptCount := len(p.costOptions) + if p.costLimit != nil { + costOptCount++ + } + costOpts := make([]interpreter.CostTrackerOption, 0, costOptCount) + costOpts = append(costOpts, p.costOptions...) + if p.costLimit != nil { + costOpts = append(costOpts, interpreter.CostTrackerLimit(*p.costLimit)) + } + trackerFactory := func() (*interpreter.CostTracker, error) { + return interpreter.NewCostTracker(p.callCostEstimator, costOpts...) + } + var observers []interpreter.PlannerOption + if p.evalOpts&(OptExhaustiveEval|OptTrackState) != 0 { + // EvalStateObserver is required for OptExhaustiveEval. + observers = append(observers, interpreter.EvalStateObserver()) + } + if p.evalOpts&OptTrackCost == OptTrackCost { + observers = append(observers, interpreter.CostObserver(interpreter.CostTrackerFactory(trackerFactory))) + } + // Enable exhaustive eval over a basic observer since it offers a superset of features. + if p.evalOpts&OptExhaustiveEval == OptExhaustiveEval { + plannerOptions = append(plannerOptions, + append([]interpreter.PlannerOption{interpreter.ExhaustiveEval()}, observers...)...) + } else if len(observers) > 0 { + plannerOptions = append(plannerOptions, observers...) } - return newProgGen(factory) } - return p.initInterpretable(a, decorators) + return p.initInterpretable(a, plannerOptions) } -func (p *prog) initInterpretable(a *ast.AST, decs []interpreter.InterpretableDecorator) (*prog, error) { +func (p *prog) initInterpretable(a *ast.AST, plannerOptions []interpreter.PlannerOption) (*prog, error) { // When the AST has been exprAST it contains metadata that can be used to speed up program execution. - interpretable, err := p.interpreter.NewInterpretable(a, decs...) + interpretable, err := p.interpreter.NewInterpretable(a, plannerOptions...) if err != nil { return nil, err } p.interpretable = interpretable + if oi, ok := interpretable.(*interpreter.ObservableInterpretable); ok { + p.observable = oi + } return p, nil } // Eval implements the Program interface method. -func (p *prog) Eval(input any) (v ref.Val, det *EvalDetails, err error) { +func (p *prog) Eval(input any) (out ref.Val, det *EvalDetails, err error) { // Configure error recovery for unexpected panics during evaluation. Note, the use of named // return values makes it possible to modify the error response during the recovery // function. @@ -285,9 +296,9 @@ func (p *prog) Eval(input any) (v ref.Val, det *EvalDetails, err error) { } }() // Build a hierarchical activation if there are default vars set. - var vars interpreter.Activation + var vars Activation switch v := input.(type) { - case interpreter.Activation: + case Activation: vars = v case map[string]any: vars = activationPool.Setup(v) @@ -298,12 +309,24 @@ func (p *prog) Eval(input any) (v ref.Val, det *EvalDetails, err error) { if p.defaultVars != nil { vars = interpreter.NewHierarchicalActivation(p.defaultVars, vars) } - v = p.interpretable.Eval(vars) + if p.observable != nil { + det = &EvalDetails{} + out = p.observable.ObserveEval(vars, func(observed any) { + switch o := observed.(type) { + case interpreter.EvalState: + det.state = o + case *interpreter.CostTracker: + det.costTracker = o + } + }) + } else { + out = p.interpretable.Eval(vars) + } // The output of an internal Eval may have a value (`v`) that is a types.Err. This step // translates the CEL value to a Go error response. This interface does not quite match the // RPC signature which allows for multiple errors to be returned, but should be sufficient. - if types.IsError(v) { - err = v.(*types.Err) + if types.IsError(out) { + err = out.(*types.Err) } return } @@ -315,9 +338,9 @@ func (p *prog) ContextEval(ctx context.Context, input any) (ref.Val, *EvalDetail } // Configure the input, making sure to wrap Activation inputs in the special ctxActivation which // exposes the #interrupted variable and manages rate-limited checks of the ctx.Done() state. - var vars interpreter.Activation + var vars Activation switch v := input.(type) { - case interpreter.Activation: + case Activation: vars = ctxActivationPool.Setup(v, ctx.Done(), p.interruptCheckFrequency) defer ctxActivationPool.Put(vars) case map[string]any: @@ -331,90 +354,8 @@ func (p *prog) ContextEval(ctx context.Context, input any) (ref.Val, *EvalDetail return p.Eval(vars) } -// progFactory is a helper alias for marking a program creation factory function. -type progFactory func(interpreter.EvalState, *interpreter.CostTracker) (Program, error) - -// progGen holds a reference to a progFactory instance and implements the Program interface. -type progGen struct { - factory progFactory -} - -// newProgGen tests the factory object by calling it once and returns a factory-based Program if -// the test is successful. -func newProgGen(factory progFactory) (Program, error) { - // Test the factory to make sure that configuration errors are spotted at config - tracker, err := interpreter.NewCostTracker(nil) - if err != nil { - return nil, err - } - _, err = factory(interpreter.NewEvalState(), tracker) - if err != nil { - return nil, err - } - return &progGen{factory: factory}, nil -} - -// Eval implements the Program interface method. -func (gen *progGen) Eval(input any) (ref.Val, *EvalDetails, error) { - // The factory based Eval() differs from the standard evaluation model in that it generates a - // new EvalState instance for each call to ensure that unique evaluations yield unique stateful - // results. - state := interpreter.NewEvalState() - costTracker, err := interpreter.NewCostTracker(nil) - if err != nil { - return nil, nil, err - } - det := &EvalDetails{state: state, costTracker: costTracker} - - // Generate a new instance of the interpretable using the factory configured during the call to - // newProgram(). It is incredibly unlikely that the factory call will generate an error given - // the factory test performed within the Program() call. - p, err := gen.factory(state, costTracker) - if err != nil { - return nil, det, err - } - - // Evaluate the input, returning the result and the 'state' within EvalDetails. - v, _, err := p.Eval(input) - if err != nil { - return v, det, err - } - return v, det, nil -} - -// ContextEval implements the Program interface method. -func (gen *progGen) ContextEval(ctx context.Context, input any) (ref.Val, *EvalDetails, error) { - if ctx == nil { - return nil, nil, fmt.Errorf("context can not be nil") - } - // The factory based Eval() differs from the standard evaluation model in that it generates a - // new EvalState instance for each call to ensure that unique evaluations yield unique stateful - // results. - state := interpreter.NewEvalState() - costTracker, err := interpreter.NewCostTracker(nil) - if err != nil { - return nil, nil, err - } - det := &EvalDetails{state: state, costTracker: costTracker} - - // Generate a new instance of the interpretable using the factory configured during the call to - // newProgram(). It is incredibly unlikely that the factory call will generate an error given - // the factory test performed within the Program() call. - p, err := gen.factory(state, costTracker) - if err != nil { - return nil, det, err - } - - // Evaluate the input, returning the result and the 'state' within EvalDetails. - v, _, err := p.ContextEval(ctx, input) - if err != nil { - return v, det, err - } - return v, det, nil -} - type ctxEvalActivation struct { - parent interpreter.Activation + parent Activation interrupt <-chan struct{} interruptCheckCount uint interruptCheckFrequency uint @@ -438,10 +379,15 @@ func (a *ctxEvalActivation) ResolveName(name string) (any, bool) { return a.parent.ResolveName(name) } -func (a *ctxEvalActivation) Parent() interpreter.Activation { +func (a *ctxEvalActivation) Parent() Activation { return a.parent } +func (a *ctxEvalActivation) AsPartialActivation() (interpreter.PartialActivation, bool) { + pa, ok := a.parent.(interpreter.PartialActivation) + return pa, ok +} + func newCtxEvalActivationPool() *ctxEvalActivationPool { return &ctxEvalActivationPool{ Pool: sync.Pool{ @@ -457,7 +403,7 @@ type ctxEvalActivationPool struct { } // Setup initializes a pooled Activation with the ability check for context.Context cancellation -func (p *ctxEvalActivationPool) Setup(vars interpreter.Activation, done <-chan struct{}, interruptCheckRate uint) *ctxEvalActivation { +func (p *ctxEvalActivationPool) Setup(vars Activation, done <-chan struct{}, interruptCheckRate uint) *ctxEvalActivation { a := p.Pool.Get().(*ctxEvalActivation) a.parent = vars a.interrupt = done @@ -506,8 +452,8 @@ func (a *evalActivation) ResolveName(name string) (any, bool) { } } -// Parent implements the interpreter.Activation interface -func (a *evalActivation) Parent() interpreter.Activation { +// Parent implements the Activation interface +func (a *evalActivation) Parent() Activation { return nil } diff --git a/vendor/github.com/google/cel-go/cel/prompt.go b/vendor/github.com/google/cel-go/cel/prompt.go new file mode 100644 index 00000000..929a26f9 --- /dev/null +++ b/vendor/github.com/google/cel-go/cel/prompt.go @@ -0,0 +1,155 @@ +// Copyright 2025 Google LLC +// +// 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 +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cel + +import ( + _ "embed" + "sort" + "strings" + "text/template" + + "github.com/google/cel-go/common" + "github.com/google/cel-go/common/operators" + "github.com/google/cel-go/common/overloads" +) + +//go:embed templates/authoring.tmpl +var authoringPrompt string + +// AuthoringPrompt creates a prompt template from a CEL environment for the purpose of AI-assisted authoring. +func AuthoringPrompt(env *Env) (*Prompt, error) { + funcMap := template.FuncMap{ + "split": func(str string) []string { return strings.Split(str, "\n") }, + } + tmpl := template.New("cel").Funcs(funcMap) + tmpl, err := tmpl.Parse(authoringPrompt) + if err != nil { + return nil, err + } + return &Prompt{ + Persona: defaultPersona, + FormatRules: defaultFormatRules, + GeneralUsage: defaultGeneralUsage, + tmpl: tmpl, + env: env, + }, nil +} + +// Prompt represents the core components of an LLM prompt based on a CEL environment. +// +// All fields of the prompt may be overwritten / modified with support for rendering the +// prompt to a human-readable string. +type Prompt struct { + // Persona indicates something about the kind of user making the request + Persona string + + // FormatRules indicate how the LLM should generate its output + FormatRules string + + // GeneralUsage specifies additional context on how CEL should be used. + GeneralUsage string + + // tmpl is the text template base-configuration for rendering text. + tmpl *template.Template + + // env reference used to collect variables, functions, and macros available to the prompt. + env *Env +} + +type promptInst struct { + *Prompt + + Variables []*common.Doc + Macros []*common.Doc + Functions []*common.Doc + UserPrompt string +} + +// Render renders the user prompt with the associated context from the prompt template +// for use with LLM generators. +func (p *Prompt) Render(userPrompt string) string { + var buffer strings.Builder + vars := make([]*common.Doc, len(p.env.Variables())) + for i, v := range p.env.Variables() { + vars[i] = v.Documentation() + } + sort.SliceStable(vars, func(i, j int) bool { + return vars[i].Name < vars[j].Name + }) + macs := make([]*common.Doc, len(p.env.Macros())) + for i, m := range p.env.Macros() { + macs[i] = m.(common.Documentor).Documentation() + } + funcs := make([]*common.Doc, 0, len(p.env.Functions())) + for _, f := range p.env.Functions() { + if _, hidden := hiddenFunctions[f.Name()]; hidden { + continue + } + funcs = append(funcs, f.Documentation()) + } + sort.SliceStable(funcs, func(i, j int) bool { + return funcs[i].Name < funcs[j].Name + }) + inst := &promptInst{ + Prompt: p, + Variables: vars, + Macros: macs, + Functions: funcs, + UserPrompt: userPrompt} + p.tmpl.Execute(&buffer, inst) + return buffer.String() +} + +const ( + defaultPersona = `You are a software engineer with expertise in networking and application security +authoring boolean Common Expression Language (CEL) expressions to ensure firewall, +networking, authentication, and data access is only permitted when all conditions +are satisfied.` + + defaultFormatRules = `Output your response as a CEL expression. + +Write the expression with the comment on the first line and the expression on the +subsequent lines. Format the expression using 80-character line limits commonly +found in C++ or Java code.` + + defaultGeneralUsage = `CEL supports Protocol Buffer and JSON types, as well as simple types and aggregate types. + +Simple types include bool, bytes, double, int, string, and uint: + +* double literals must always include a decimal point: 1.0, 3.5, -2.2 +* uint literals must be positive values suffixed with a 'u': 42u +* byte literals are strings prefixed with a 'b': b'1235' +* string literals can use either single quotes or double quotes: 'hello', "world" +* string literals can also be treated as raw strings that do not require any + escaping within the string by using the 'R' prefix: R"""quote: "hi" """ + +Aggregate types include list and map: + +* list literals consist of zero or more values between brackets: "['a', 'b', 'c']" +* map literal consist of colon-separated key-value pairs within braces: "{'key1': 1, 'key2': 2}" +* Only int, uint, string, and bool types are valid map keys. +* Maps containing HTTP headers must always use lower-cased string keys. + +Comments start with two-forward slashes followed by text and a newline.` +) + +var ( + hiddenFunctions = map[string]bool{ + overloads.DeprecatedIn: true, + operators.OldIn: true, + operators.OldNotStrictlyFalse: true, + operators.NotStrictlyFalse: true, + } +) diff --git a/vendor/github.com/google/cel-go/cel/templates/authoring.tmpl b/vendor/github.com/google/cel-go/cel/templates/authoring.tmpl new file mode 100644 index 00000000..d6b3da5c --- /dev/null +++ b/vendor/github.com/google/cel-go/cel/templates/authoring.tmpl @@ -0,0 +1,56 @@ +{{define "variable"}}{{.Name}} is a {{.Type}} +{{- end -}} + +{{define "macro" -}} +{{.Name}} macro{{if .Description}} - {{range split .Description}}{{.}} {{end}} +{{end}} +{{range .Children}}{{range split .Description}} {{.}} +{{end}} +{{- end -}} +{{- end -}} + +{{define "overload" -}} +{{if .Children}}{{range .Children}}{{range split .Description}} {{.}} +{{end}} +{{- end -}} +{{else}} {{.Signature}} +{{end}} +{{- end -}} + +{{define "function" -}} +{{.Name}}{{if .Description}} - {{range split .Description}}{{.}} {{end}} +{{end}} +{{range .Children}}{{template "overload" .}}{{end}} +{{- end -}} + +{{.Persona}} + +{{.FormatRules}} + +{{if or .Variables .Macros .Functions -}} +Only use the following variables, macros, and functions in expressions. +{{if .Variables}} +Variables: + +{{range .Variables}}* {{template "variable" .}} +{{end -}} + +{{end -}} +{{if .Macros}} +Macros: + +{{range .Macros}}* {{template "macro" .}} +{{end -}} + +{{end -}} +{{if .Functions}} +Functions: + +{{range .Functions}}* {{template "function" .}} +{{end -}} + +{{end -}} +{{- end -}} +{{.GeneralUsage}} + +{{.UserPrompt}} diff --git a/vendor/github.com/google/cel-go/cel/validator.go b/vendor/github.com/google/cel-go/cel/validator.go index b50c6745..5f06b2dd 100644 --- a/vendor/github.com/google/cel-go/cel/validator.go +++ b/vendor/github.com/google/cel-go/cel/validator.go @@ -20,11 +20,16 @@ import ( "regexp" "github.com/google/cel-go/common/ast" + "github.com/google/cel-go/common/env" "github.com/google/cel-go/common/overloads" ) const ( - homogeneousValidatorName = "cel.lib.std.validate.types.homogeneous" + durationValidatorName = "cel.validator.duration" + regexValidatorName = "cel.validator.matches" + timestampValidatorName = "cel.validator.timestamp" + homogeneousValidatorName = "cel.validator.homogeneous_literals" + nestingLimitValidatorName = "cel.validator.comprehension_nesting_limit" // HomogeneousAggregateLiteralExemptFunctions is the ValidatorConfig key used to configure // the set of function names which are exempt from homogeneous type checks. The expected type @@ -36,6 +41,35 @@ const ( HomogeneousAggregateLiteralExemptFunctions = homogeneousValidatorName + ".exempt" ) +var ( + astValidatorFactories = map[string]ASTValidatorFactory{ + nestingLimitValidatorName: func(val *env.Validator) (ASTValidator, error) { + if limit, found := val.ConfigValue("limit"); found { + if val, isInt := limit.(int); isInt { + return ValidateComprehensionNestingLimit(val), nil + } + return nil, fmt.Errorf("invalid validator: %s unsupported limit type: %v", nestingLimitValidatorName, limit) + } + return nil, fmt.Errorf("invalid validator: %s missing limit", nestingLimitValidatorName) + }, + durationValidatorName: func(*env.Validator) (ASTValidator, error) { + return ValidateDurationLiterals(), nil + }, + regexValidatorName: func(*env.Validator) (ASTValidator, error) { + return ValidateRegexLiterals(), nil + }, + timestampValidatorName: func(*env.Validator) (ASTValidator, error) { + return ValidateTimestampLiterals(), nil + }, + homogeneousValidatorName: func(*env.Validator) (ASTValidator, error) { + return ValidateHomogeneousAggregateLiterals(), nil + }, + } +) + +// ASTValidatorFactory creates an ASTValidator as configured by the input map +type ASTValidatorFactory func(*env.Validator) (ASTValidator, error) + // ASTValidators configures a set of ASTValidator instances into the target environment. // // Validators are applied in the order in which the are specified and are treated as singletons. @@ -70,6 +104,18 @@ type ASTValidator interface { Validate(*Env, ValidatorConfig, *ast.AST, *Issues) } +// ConfigurableASTValidator supports conversion of an object to an `env.Validator` instance used for +// YAML serialization. +type ConfigurableASTValidator interface { + // ToConfig converts the internal configuration of an ASTValidator into an env.Validator instance + // which minimally must include the validator name, but may also include a map[string]any config + // object to be serialized to YAML. The string keys represent the configuration parameter name, + // and the any value must mirror the internally supported type associated with the config key. + // + // Note: only primitive CEL types are supported by CEL validators at this time. + ToConfig() *env.Validator +} + // ValidatorConfig provides an accessor method for querying validator configuration state. type ValidatorConfig interface { GetOrDefault(name string, value any) any @@ -196,7 +242,12 @@ type formatValidator struct { // Name returns the unique name of this function format validator. func (v formatValidator) Name() string { - return fmt.Sprintf("cel.lib.std.validate.functions.%s", v.funcName) + return fmt.Sprintf("cel.validator.%s", v.funcName) +} + +// ToConfig converts the ASTValidator to an env.Validator specifying the validator name. +func (v formatValidator) ToConfig() *env.Validator { + return env.NewValidator(v.Name()) } // Validate searches the AST for uses of a given function name with a constant argument and performs a check @@ -242,6 +293,11 @@ func (homogeneousAggregateLiteralValidator) Name() string { return homogeneousValidatorName } +// ToConfig converts the ASTValidator to an env.Validator specifying the validator name. +func (v homogeneousAggregateLiteralValidator) ToConfig() *env.Validator { + return env.NewValidator(v.Name()) +} + // Validate validates that all lists and map literals have homogeneous types, i.e. don't contain dyn types. // // This validator makes an exception for list and map literals which occur at any level of nesting within @@ -336,10 +392,18 @@ type nestingLimitValidator struct { limit int } +// Name returns the name of the nesting limit validator. func (v nestingLimitValidator) Name() string { - return "cel.lib.std.validate.comprehension_nesting_limit" + return nestingLimitValidatorName +} + +// ToConfig converts the ASTValidator to an env.Validator specifying the validator name and the nesting limit +// as an integer value: {"limit": int} +func (v nestingLimitValidator) ToConfig() *env.Validator { + return env.NewValidator(v.Name()).SetConfig(map[string]any{"limit": v.limit}) } +// Validate implements the ASTValidator interface method. func (v nestingLimitValidator) Validate(e *Env, _ ValidatorConfig, a *ast.AST, iss *Issues) { root := ast.NavigateAST(a) comprehensions := ast.MatchDescendants(root, ast.KindMatcher(ast.ComprehensionKind)) diff --git a/vendor/github.com/google/cel-go/checker/checker.go b/vendor/github.com/google/cel-go/checker/checker.go index 6824af7a..0057c16c 100644 --- a/vendor/github.com/google/cel-go/checker/checker.go +++ b/vendor/github.com/google/cel-go/checker/checker.go @@ -145,6 +145,17 @@ func (c *checker) checkSelect(e ast.Expr) { func (c *checker) checkOptSelect(e ast.Expr) { // Collect metadata related to the opt select call packaged by the parser. call := e.AsCall() + if len(call.Args()) != 2 || call.IsMemberFunction() { + t := "" + if call.IsMemberFunction() { + t = " member call with" + } + c.errors.notAnOptionalFieldSelectionCall(e.ID(), c.location(e), + fmt.Sprintf( + "incorrect signature.%s argument count: %d", t, len(call.Args()))) + return + } + operand := call.Args()[0] field := call.Args()[1] fieldName, isString := maybeUnwrapString(field) diff --git a/vendor/github.com/google/cel-go/checker/cost.go b/vendor/github.com/google/cel-go/checker/cost.go index 59be751c..5bc6318e 100644 --- a/vendor/github.com/google/cel-go/checker/cost.go +++ b/vendor/github.com/google/cel-go/checker/cost.go @@ -545,16 +545,17 @@ func (c *coster) costCall(e ast.Expr) CostEstimate { if len(overloadIDs) == 0 { return CostEstimate{} } - var targetType AstNode + var targetType *AstNode if call.IsMemberFunction() { sum = sum.Add(c.cost(call.Target())) - targetType = c.newAstNode(call.Target()) + var t AstNode = c.newAstNode(call.Target()) + targetType = &t } // Pick a cost estimate range that covers all the overload cost estimation ranges fnCost := CostEstimate{Min: uint64(math.MaxUint64), Max: 0} var resultSize *SizeEstimate for _, overload := range overloadIDs { - overloadCost := c.functionCost(e, call.FunctionName(), overload, &targetType, argTypes, argCosts) + overloadCost := c.functionCost(e, call.FunctionName(), overload, targetType, argTypes, argCosts) fnCost = fnCost.Union(overloadCost.CostEstimate) if overloadCost.ResultSize != nil { if resultSize == nil { diff --git a/vendor/github.com/google/cel-go/checker/decls/decls.go b/vendor/github.com/google/cel-go/checker/decls/decls.go index c0e5de46..e013d2c2 100644 --- a/vendor/github.com/google/cel-go/checker/decls/decls.go +++ b/vendor/github.com/google/cel-go/checker/decls/decls.go @@ -91,6 +91,17 @@ func NewFunction(name string, Overloads: overloads}}} } +// NewFunctionWithDoc creates a named function declaration with a description and one or more overloads. +func NewFunctionWithDoc(name, doc string, + overloads ...*exprpb.Decl_FunctionDecl_Overload) *exprpb.Decl { + return &exprpb.Decl{ + Name: name, + DeclKind: &exprpb.Decl_Function{ + Function: &exprpb.Decl_FunctionDecl{ + // Doc: desc, + Overloads: overloads}}} +} + // NewIdent creates a named identifier declaration with an optional literal // value. // @@ -98,28 +109,37 @@ func NewFunction(name string, // // Deprecated: Use NewVar or NewConst instead. func NewIdent(name string, t *exprpb.Type, v *exprpb.Constant) *exprpb.Decl { + return newIdent(name, t, v, "") +} + +func newIdent(name string, t *exprpb.Type, v *exprpb.Constant, desc string) *exprpb.Decl { return &exprpb.Decl{ Name: name, DeclKind: &exprpb.Decl_Ident{ Ident: &exprpb.Decl_IdentDecl{ Type: t, - Value: v}}} + Value: v, + Doc: desc}}} } // NewConst creates a constant identifier with a CEL constant literal value. func NewConst(name string, t *exprpb.Type, v *exprpb.Constant) *exprpb.Decl { - return NewIdent(name, t, v) + return newIdent(name, t, v, "") } // NewVar creates a variable identifier. func NewVar(name string, t *exprpb.Type) *exprpb.Decl { - return NewIdent(name, t, nil) + return newIdent(name, t, nil, "") +} + +// NewVarWithDoc creates a variable identifier with a type and a description string. +func NewVarWithDoc(name string, t *exprpb.Type, desc string) *exprpb.Decl { + return newIdent(name, t, nil, desc) } // NewInstanceOverload creates a instance function overload contract. // First element of argTypes is instance. -func NewInstanceOverload(id string, argTypes []*exprpb.Type, - resultType *exprpb.Type) *exprpb.Decl_FunctionDecl_Overload { +func NewInstanceOverload(id string, argTypes []*exprpb.Type, resultType *exprpb.Type) *exprpb.Decl_FunctionDecl_Overload { return &exprpb.Decl_FunctionDecl_Overload{ OverloadId: id, ResultType: resultType, @@ -154,8 +174,7 @@ func NewObjectType(typeName string) *exprpb.Type { // NewOverload creates a function overload declaration which contains a unique // overload id as well as the expected argument and result types. Overloads // must be aggregated within a Function declaration. -func NewOverload(id string, argTypes []*exprpb.Type, - resultType *exprpb.Type) *exprpb.Decl_FunctionDecl_Overload { +func NewOverload(id string, argTypes []*exprpb.Type, resultType *exprpb.Type) *exprpb.Decl_FunctionDecl_Overload { return &exprpb.Decl_FunctionDecl_Overload{ OverloadId: id, ResultType: resultType, @@ -231,7 +250,5 @@ func NewWrapperType(wrapped *exprpb.Type) *exprpb.Type { // TODO: return an error panic("Wrapped type must be a primitive") } - return &exprpb.Type{ - TypeKind: &exprpb.Type_Wrapper{ - Wrapper: primitive}} + return &exprpb.Type{TypeKind: &exprpb.Type_Wrapper{Wrapper: primitive}} } diff --git a/vendor/github.com/google/cel-go/checker/errors.go b/vendor/github.com/google/cel-go/checker/errors.go index 8b3bf0b8..3535440b 100644 --- a/vendor/github.com/google/cel-go/checker/errors.go +++ b/vendor/github.com/google/cel-go/checker/errors.go @@ -45,6 +45,10 @@ func (e *typeErrors) notAComprehensionRange(id int64, l common.Location, t *type FormatCELType(t)) } +func (e *typeErrors) notAnOptionalFieldSelectionCall(id int64, l common.Location, err string) { + e.errs.ReportErrorAtID(id, l, "unsupported optional field selection: %s", err) +} + func (e *typeErrors) notAnOptionalFieldSelection(id int64, l common.Location, field ast.Expr) { e.errs.ReportErrorAtID(id, l, "unsupported optional field selection: %v", field) } diff --git a/vendor/github.com/google/cel-go/common/BUILD.bazel b/vendor/github.com/google/cel-go/common/BUILD.bazel index eef7f281..1b1b7914 100644 --- a/vendor/github.com/google/cel-go/common/BUILD.bazel +++ b/vendor/github.com/google/cel-go/common/BUILD.bazel @@ -9,6 +9,7 @@ go_library( name = "go_default_library", srcs = [ "cost.go", + "doc.go", "error.go", "errors.go", "location.go", @@ -25,6 +26,7 @@ go_test( name = "go_default_test", size = "small", srcs = [ + "doc_test.go", "errors_test.go", "source_test.go", ], diff --git a/vendor/github.com/google/cel-go/common/ast/ast.go b/vendor/github.com/google/cel-go/common/ast/ast.go index b807669d..62c09cfc 100644 --- a/vendor/github.com/google/cel-go/common/ast/ast.go +++ b/vendor/github.com/google/cel-go/common/ast/ast.go @@ -160,6 +160,13 @@ func MaxID(a *AST) int64 { return visitor.maxID + 1 } +// Heights computes the heights of all AST expressions and returns a map from expression id to height. +func Heights(a *AST) map[int64]int { + visitor := make(heightVisitor) + PostOrderVisit(a.Expr(), visitor) + return visitor +} + // NewSourceInfo creates a simple SourceInfo object from an input common.Source value. func NewSourceInfo(src common.Source) *SourceInfo { var lineOffsets []int32 @@ -455,3 +462,74 @@ func (v *maxIDVisitor) VisitEntryExpr(e EntryExpr) { v.maxID = e.ID() } } + +type heightVisitor map[int64]int + +// VisitExpr computes the height of a given node as the max height of its children plus one. +// +// Identifiers and literals are treated as having a height of zero. +func (hv heightVisitor) VisitExpr(e Expr) { + // default includes IdentKind, LiteralKind + hv[e.ID()] = 0 + switch e.Kind() { + case SelectKind: + hv[e.ID()] = 1 + hv[e.AsSelect().Operand().ID()] + case CallKind: + c := e.AsCall() + height := hv.maxHeight(c.Args()...) + if c.IsMemberFunction() { + tHeight := hv[c.Target().ID()] + if tHeight > height { + height = tHeight + } + } + hv[e.ID()] = 1 + height + case ListKind: + l := e.AsList() + hv[e.ID()] = 1 + hv.maxHeight(l.Elements()...) + case MapKind: + m := e.AsMap() + hv[e.ID()] = 1 + hv.maxEntryHeight(m.Entries()...) + case StructKind: + s := e.AsStruct() + hv[e.ID()] = 1 + hv.maxEntryHeight(s.Fields()...) + case ComprehensionKind: + comp := e.AsComprehension() + hv[e.ID()] = 1 + hv.maxHeight(comp.IterRange(), comp.AccuInit(), comp.LoopCondition(), comp.LoopStep(), comp.Result()) + } +} + +// VisitEntryExpr computes the max height of a map or struct entry and associates the height with the entry id. +func (hv heightVisitor) VisitEntryExpr(e EntryExpr) { + hv[e.ID()] = 0 + switch e.Kind() { + case MapEntryKind: + me := e.AsMapEntry() + hv[e.ID()] = hv.maxHeight(me.Value(), me.Key()) + case StructFieldKind: + sf := e.AsStructField() + hv[e.ID()] = hv[sf.Value().ID()] + } +} + +func (hv heightVisitor) maxHeight(exprs ...Expr) int { + max := 0 + for _, e := range exprs { + h := hv[e.ID()] + if h > max { + max = h + } + } + return max +} + +func (hv heightVisitor) maxEntryHeight(entries ...EntryExpr) int { + max := 0 + for _, e := range entries { + h := hv[e.ID()] + if h > max { + max = h + } + } + return max +} diff --git a/vendor/github.com/google/cel-go/common/ast/navigable.go b/vendor/github.com/google/cel-go/common/ast/navigable.go index d7a90fb7..13e5777b 100644 --- a/vendor/github.com/google/cel-go/common/ast/navigable.go +++ b/vendor/github.com/google/cel-go/common/ast/navigable.go @@ -237,8 +237,13 @@ func visit(expr Expr, visitor Visitor, order visitOrder, depth, maxDepth int) { case StructKind: s := expr.AsStruct() for _, f := range s.Fields() { - visitor.VisitEntryExpr(f) + if order == preOrder { + visitor.VisitEntryExpr(f) + } visit(f.AsStructField().Value(), visitor, order, depth+1, maxDepth) + if order == postOrder { + visitor.VisitEntryExpr(f) + } } } if order == postOrder { diff --git a/vendor/github.com/google/cel-go/common/containers/container.go b/vendor/github.com/google/cel-go/common/containers/container.go index 3097a3f7..fc146b6f 100644 --- a/vendor/github.com/google/cel-go/common/containers/container.go +++ b/vendor/github.com/google/cel-go/common/containers/container.go @@ -63,9 +63,9 @@ func (c *Container) Extend(opts ...ContainerOption) (*Container, error) { } // Copy the name and aliases of the existing container. ext := &Container{name: c.Name()} - if len(c.aliasSet()) > 0 { - aliasSet := make(map[string]string, len(c.aliasSet())) - for k, v := range c.aliasSet() { + if len(c.AliasSet()) > 0 { + aliasSet := make(map[string]string, len(c.AliasSet())) + for k, v := range c.AliasSet() { aliasSet[k] = v } ext.aliases = aliasSet @@ -133,8 +133,8 @@ func (c *Container) ResolveCandidateNames(name string) []string { return append(candidates, name) } -// aliasSet returns the alias to fully-qualified name mapping stored in the container. -func (c *Container) aliasSet() map[string]string { +// AliasSet returns the alias to fully-qualified name mapping stored in the container. +func (c *Container) AliasSet() map[string]string { if c == nil || c.aliases == nil { return noAliases } @@ -160,7 +160,7 @@ func (c *Container) findAlias(name string) (string, bool) { simple = name[0:dot] qualifier = name[dot:] } - alias, found := c.aliasSet()[simple] + alias, found := c.AliasSet()[simple] if !found { return "", false } @@ -264,7 +264,7 @@ func aliasAs(kind, qualifiedName, alias string) ContainerOption { return nil, fmt.Errorf("%s must refer to a valid qualified name: %s", kind, qualifiedName) } - aliasRef, found := c.aliasSet()[alias] + aliasRef, found := c.AliasSet()[alias] if found { return nil, fmt.Errorf( "%s collides with existing reference: name=%s, %s=%s, existing=%s", diff --git a/vendor/github.com/google/cel-go/common/decls/BUILD.bazel b/vendor/github.com/google/cel-go/common/decls/BUILD.bazel index 17791dce..bd3f9ae7 100644 --- a/vendor/github.com/google/cel-go/common/decls/BUILD.bazel +++ b/vendor/github.com/google/cel-go/common/decls/BUILD.bazel @@ -13,7 +13,9 @@ go_library( importpath = "github.com/google/cel-go/common/decls", deps = [ "//checker/decls:go_default_library", + "//common:go_default_library", "//common/functions:go_default_library", + "//common/operators:go_default_library", "//common/types:go_default_library", "//common/types/ref:go_default_library", "//common/types/traits:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/decls/decls.go b/vendor/github.com/google/cel-go/common/decls/decls.go index bfeb52c5..a4a51c3f 100644 --- a/vendor/github.com/google/cel-go/common/decls/decls.go +++ b/vendor/github.com/google/cel-go/common/decls/decls.go @@ -20,7 +20,9 @@ import ( "strings" chkdecls "github.com/google/cel-go/checker/decls" + "github.com/google/cel-go/common" "github.com/google/cel-go/common/functions" + "github.com/google/cel-go/common/operators" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" @@ -54,6 +56,7 @@ func NewFunction(name string, opts ...FunctionOpt) (*FunctionDecl, error) { // overload instances. type FunctionDecl struct { name string + doc string // overloads associated with the function name. overloads map[string]*OverloadDecl @@ -84,6 +87,26 @@ const ( declarationEnabled ) +// Documentation generates documentation about the Function and its overloads as a common.Doc object. +func (f *FunctionDecl) Documentation() *common.Doc { + if f == nil { + return nil + } + children := make([]*common.Doc, len(f.OverloadDecls())) + for i, o := range f.OverloadDecls() { + var examples []*common.Doc + for _, ex := range o.Examples() { + examples = append(examples, common.NewExampleDoc(ex)) + } + od := common.NewOverloadDoc(o.ID(), formatSignature(f.Name(), o), examples...) + children[i] = od + } + return common.NewFunctionDoc( + f.Name(), + f.Description(), + children...) +} + // Name returns the function name in human-readable terms, e.g. 'contains' of 'math.least' func (f *FunctionDecl) Name() string { if f == nil { @@ -92,9 +115,22 @@ func (f *FunctionDecl) Name() string { return f.name } +// Description provides an overview of the function's purpose. +// +// Usage examples should be included on specific overloads. +func (f *FunctionDecl) Description() string { + if f == nil { + return "" + } + return f.doc +} + // IsDeclarationDisabled indicates that the function implementation should be added to the dispatcher, but the // declaration should not be exposed for use in expressions. func (f *FunctionDecl) IsDeclarationDisabled() bool { + if f == nil { + return true + } return f.state == declarationDisabled } @@ -107,8 +143,8 @@ func (f *FunctionDecl) Merge(other *FunctionDecl) (*FunctionDecl, error) { if f == other { return f, nil } - if f.Name() != other.Name() { - return nil, fmt.Errorf("cannot merge unrelated functions. %s and %s", f.Name(), other.Name()) + if f == nil || other == nil || f.Name() != other.Name() { + return nil, fmt.Errorf("cannot merge unrelated functions. %q and %q", f.Name(), other.Name()) } merged := &FunctionDecl{ name: f.Name(), @@ -120,12 +156,17 @@ func (f *FunctionDecl) Merge(other *FunctionDecl) (*FunctionDecl, error) { disableTypeGuards: f.disableTypeGuards && other.disableTypeGuards, // default to the current functions declaration state. state: f.state, + doc: f.doc, } // If the other state indicates that the declaration should be explicitly enabled or // disabled, then update the merged state with the most recent value. if other.state != declarationStateUnset { merged.state = other.state } + // Allow for non-empty overrides of documentation + if len(other.doc) != 0 && f.doc != other.doc { + merged.doc = other.doc + } // baseline copy of the overloads and their ordinals copy(merged.overloadOrdinals, f.overloadOrdinals) for oID, o := range f.overloads { @@ -148,6 +189,70 @@ func (f *FunctionDecl) Merge(other *FunctionDecl) (*FunctionDecl, error) { return merged, nil } +// FunctionSubsetter subsets a function declaration or returns nil and false if the function +// subset was empty. +type FunctionSubsetter func(fn *FunctionDecl) (*FunctionDecl, bool) + +// OverloadSelector selects an overload associated with a given function when it returns true. +// +// Used in combination with the Subset method. +type OverloadSelector func(overload *OverloadDecl) bool + +// IncludeOverloads defines an OverloadSelector which allow-lists a set of overloads by their ids. +func IncludeOverloads(overloadIDs ...string) OverloadSelector { + return func(overload *OverloadDecl) bool { + for _, oID := range overloadIDs { + if overload.id == oID { + return true + } + } + return false + } +} + +// ExcludeOverloads defines an OverloadSelector which deny-lists a set of overloads by their ids. +func ExcludeOverloads(overloadIDs ...string) OverloadSelector { + return func(overload *OverloadDecl) bool { + for _, oID := range overloadIDs { + if overload.id == oID { + return false + } + } + return true + } +} + +// Subset returns a new function declaration which contains only the overloads with the specified IDs. +// If the subset function contains no overloads, then nil is returned to indicate the function is not +// functional. +func (f *FunctionDecl) Subset(selector OverloadSelector) *FunctionDecl { + if f == nil { + return nil + } + overloads := make(map[string]*OverloadDecl) + overloadOrdinals := make([]string, 0, len(f.overloadOrdinals)) + for _, oID := range f.overloadOrdinals { + overload := f.overloads[oID] + if selector(overload) { + overloads[oID] = overload + overloadOrdinals = append(overloadOrdinals, oID) + } + } + if len(overloads) == 0 { + return nil + } + subset := &FunctionDecl{ + name: f.Name(), + doc: f.doc, + overloads: overloads, + singleton: f.singleton, + disableTypeGuards: f.disableTypeGuards, + state: f.state, + overloadOrdinals: overloadOrdinals, + } + return subset +} + // AddOverload ensures that the new overload does not collide with an existing overload signature; // however, if the function signatures are identical, the implementation may be rewritten as its // difficult to compare functions by object identity. @@ -155,6 +260,9 @@ func (f *FunctionDecl) AddOverload(overload *OverloadDecl) error { if f == nil { return fmt.Errorf("nil function cannot add overload: %s", overload.ID()) } + if overload == nil { + return fmt.Errorf("cannot add nil overload to funciton: %s", f.Name()) + } for oID, o := range f.overloads { if oID != overload.ID() && o.SignatureOverlaps(overload) { return fmt.Errorf("overload signature collision in function %s: %s collides with %s", f.Name(), oID, overload.ID()) @@ -165,10 +273,17 @@ func (f *FunctionDecl) AddOverload(overload *OverloadDecl) error { if overload.hasBinding() { f.overloads[oID] = overload } + // Allow redefinition of the doc string. + if len(overload.doc) != 0 && o.doc != overload.doc { + o.doc = overload.doc + } return nil } return fmt.Errorf("overload redefinition in function. %s: %s has multiple definitions", f.Name(), oID) } + if overload.HasLateBinding() != o.HasLateBinding() { + return fmt.Errorf("overload with late binding cannot be added to function %s: cannot mix late and non-late bindings", f.Name()) + } } f.overloadOrdinals = append(f.overloadOrdinals, overload.ID()) f.overloads[overload.ID()] = overload @@ -177,8 +292,9 @@ func (f *FunctionDecl) AddOverload(overload *OverloadDecl) error { // OverloadDecls returns the overload declarations in the order in which they were declared. func (f *FunctionDecl) OverloadDecls() []*OverloadDecl { + var emptySet []*OverloadDecl if f == nil { - return []*OverloadDecl{} + return emptySet } overloads := make([]*OverloadDecl, 0, len(f.overloads)) for _, oID := range f.overloadOrdinals { @@ -187,15 +303,31 @@ func (f *FunctionDecl) OverloadDecls() []*OverloadDecl { return overloads } +// HasLateBinding returns true if the function has late bindings. A function cannot mix late bindings with other bindings. +func (f *FunctionDecl) HasLateBinding() bool { + if f == nil { + return false + } + for _, oID := range f.overloadOrdinals { + if f.overloads[oID].HasLateBinding() { + return true + } + } + return false +} + // Bindings produces a set of function bindings, if any are defined. func (f *FunctionDecl) Bindings() ([]*functions.Overload, error) { + var emptySet []*functions.Overload if f == nil { - return []*functions.Overload{}, nil + return emptySet, nil } overloads := []*functions.Overload{} nonStrict := false + hasLateBinding := false for _, oID := range f.overloadOrdinals { o := f.overloads[oID] + hasLateBinding = hasLateBinding || o.HasLateBinding() if o.hasBinding() { overload := &functions.Overload{ Operator: o.ID(), @@ -213,6 +345,9 @@ func (f *FunctionDecl) Bindings() ([]*functions.Overload, error) { if len(overloads) != 0 { return nil, fmt.Errorf("singleton function incompatible with specialized overloads: %s", f.Name()) } + if hasLateBinding { + return nil, fmt.Errorf("singleton function incompatible with late bindings: %s", f.Name()) + } overloads = []*functions.Overload{ { Operator: f.Name(), @@ -298,6 +433,14 @@ func MaybeNoSuchOverload(funcName string, args ...ref.Val) ref.Val { // FunctionOpt defines a functional option for mutating a function declaration. type FunctionOpt func(*FunctionDecl) (*FunctionDecl, error) +// FunctionDocs configures documentation from a list of strings separated by newlines. +func FunctionDocs(docs ...string) FunctionOpt { + return func(fn *FunctionDecl) (*FunctionDecl, error) { + fn.doc = common.MultilineDescription(docs...) + return fn, nil + } +} + // DisableTypeGuards disables automatically generated function invocation guards on direct overload calls. // Type guards remain on during dynamic dispatch for parsed-only expressions. func DisableTypeGuards(value bool) FunctionOpt { @@ -450,9 +593,13 @@ func newOverloadInternal(overloadID string, // implementation. type OverloadDecl struct { id string + doc string argTypes []*types.Type resultType *types.Type isMemberFunction bool + // hasLateBinding indicates that the function has a binding which is not known at compile time. + // This is useful for functions which have side-effects or are not deterministically computable. + hasLateBinding bool // nonStrict indicates that the function will accept error and unknown arguments as inputs. nonStrict bool // operandTrait indicates whether the member argument should have a specific type-trait. @@ -469,6 +616,15 @@ type OverloadDecl struct { functionOp functions.FunctionOp } +// Examples returns a list of string examples for the overload. +func (o *OverloadDecl) Examples() []string { + var emptySet []string + if o == nil || len(o.doc) == 0 { + return emptySet + } + return common.ParseDescriptions(o.doc) +} + // ID mirrors the overload signature and provides a unique id which may be referenced within the type-checker // and interpreter to optimize performance. // @@ -508,6 +664,14 @@ func (o *OverloadDecl) IsNonStrict() bool { return o.nonStrict } +// HasLateBinding returns whether the overload has a binding which is not known at compile time. +func (o *OverloadDecl) HasLateBinding() bool { + if o == nil { + return false + } + return o.hasLateBinding +} + // OperandTrait returns the trait mask of the first operand to the overload call, e.g. // `traits.Indexer` func (o *OverloadDecl) OperandTrait() int { @@ -666,6 +830,14 @@ func matchOperandTrait(trait int, arg ref.Val) bool { // OverloadOpt is a functional option for configuring a function overload. type OverloadOpt func(*OverloadDecl) (*OverloadDecl, error) +// OverloadExamples configures example expressions for the overload. +func OverloadExamples(examples ...string) OverloadOpt { + return func(o *OverloadDecl) (*OverloadDecl, error) { + o.doc = common.MultilineDescription(examples...) + return o, nil + } +} + // UnaryBinding provides the implementation of a unary overload. The provided function is protected by a runtime // type-guard which ensures runtime type agreement between the overload signature and runtime argument types. func UnaryBinding(binding functions.UnaryOp) OverloadOpt { @@ -676,6 +848,9 @@ func UnaryBinding(binding functions.UnaryOp) OverloadOpt { if len(o.ArgTypes()) != 1 { return nil, fmt.Errorf("unary function bound to non-unary overload: %s", o.ID()) } + if o.hasLateBinding { + return nil, fmt.Errorf("overload already has a late binding: %s", o.ID()) + } o.unaryOp = binding return o, nil } @@ -691,6 +866,9 @@ func BinaryBinding(binding functions.BinaryOp) OverloadOpt { if len(o.ArgTypes()) != 2 { return nil, fmt.Errorf("binary function bound to non-binary overload: %s", o.ID()) } + if o.hasLateBinding { + return nil, fmt.Errorf("overload already has a late binding: %s", o.ID()) + } o.binaryOp = binding return o, nil } @@ -703,11 +881,26 @@ func FunctionBinding(binding functions.FunctionOp) OverloadOpt { if o.hasBinding() { return nil, fmt.Errorf("overload already has a binding: %s", o.ID()) } + if o.hasLateBinding { + return nil, fmt.Errorf("overload already has a late binding: %s", o.ID()) + } o.functionOp = binding return o, nil } } +// LateFunctionBinding indicates that the function has a binding which is not known at compile time. +// This is useful for functions which have side-effects or are not deterministically computable. +func LateFunctionBinding() OverloadOpt { + return func(o *OverloadDecl) (*OverloadDecl, error) { + if o.hasBinding() { + return nil, fmt.Errorf("overload already has a binding: %s", o.ID()) + } + o.hasLateBinding = true + return o, nil + } +} + // OverloadIsNonStrict enables the function to be called with error and unknown argument values. // // Note: do not use this option unless absoluately necessary as it should be an uncommon feature. @@ -737,13 +930,27 @@ func NewVariable(name string, t *types.Type) *VariableDecl { return &VariableDecl{name: name, varType: t} } +// NewVariableWithDoc creates a new variable declaration with usage documentation. +func NewVariableWithDoc(name string, t *types.Type, doc string) *VariableDecl { + return &VariableDecl{name: name, varType: t, doc: doc} +} + // VariableDecl defines a variable declaration which may optionally have a constant value. type VariableDecl struct { name string + doc string varType *types.Type value ref.Val } +// Documentation returns name, type, and description for the variable. +func (v *VariableDecl) Documentation() *common.Doc { + if v == nil { + return nil + } + return common.NewVariableDoc(v.Name(), describeCELType(v.Type()), v.Description()) +} + // Name returns the fully-qualified variable name func (v *VariableDecl) Name() string { if v == nil { @@ -752,6 +959,16 @@ func (v *VariableDecl) Name() string { return v.name } +// Description returns the usage documentation for the variable, if set. +// +// Good usage instructions provide information about the valid formats, ranges, sizes for the variable type. +func (v *VariableDecl) Description() string { + if v == nil { + return "" + } + return v.doc +} + // Type returns the types.Type value associated with the variable. func (v *VariableDecl) Type() *types.Type { if v == nil { @@ -793,7 +1010,7 @@ func variableDeclToExprDecl(v *VariableDecl) (*exprpb.Decl, error) { if err != nil { return nil, err } - return chkdecls.NewVar(v.Name(), varType), nil + return chkdecls.NewVarWithDoc(v.Name(), varType, v.doc), nil } // FunctionDeclToExprDecl converts a go-native function declaration into a protobuf-typed function declaration. @@ -838,8 +1055,10 @@ func functionDeclToExprDecl(f *FunctionDecl) (*exprpb.Decl, error) { overloads[i] = chkdecls.NewParameterizedOverload(oID, argTypes, resultType, params) } } + doc := common.MultilineDescription(o.Examples()...) + overloads[i].Doc = doc } - return chkdecls.NewFunction(f.Name(), overloads...), nil + return chkdecls.NewFunctionWithDoc(f.Name(), f.Description(), overloads...), nil } func collectParamNames(paramNames map[string]struct{}, arg *types.Type) { @@ -851,6 +1070,60 @@ func collectParamNames(paramNames map[string]struct{}, arg *types.Type) { } } +func formatSignature(fnName string, o *OverloadDecl) string { + if opName, isOperator := operators.FindReverse(fnName); isOperator { + if opName == "" { + opName = fnName + } + return formatOperator(opName, o) + } + return formatCall(fnName, o) +} + +func formatOperator(opName string, o *OverloadDecl) string { + args := o.ArgTypes() + argTypes := make([]string, len(o.ArgTypes())) + for j, a := range args { + argTypes[j] = describeCELType(a) + } + ret := describeCELType(o.ResultType()) + switch len(args) { + case 1: + return fmt.Sprintf("%s%s -> %s", opName, argTypes[0], ret) + case 2: + if opName == operators.Index { + return fmt.Sprintf("%s[%s] -> %s", argTypes[0], argTypes[1], ret) + } + return fmt.Sprintf("%s %s %s -> %s", argTypes[0], opName, argTypes[1], ret) + default: + if opName == operators.Conditional { + return fmt.Sprint("bool ? : -> ") + } + return formatCall(opName, o) + } +} + +func formatCall(funcName string, o *OverloadDecl) string { + args := make([]string, len(o.ArgTypes())) + ret := describeCELType(o.ResultType()) + for j, a := range o.ArgTypes() { + args[j] = describeCELType(a) + } + if o.IsMemberFunction() { + target := args[0] + args = args[1:] + return fmt.Sprintf("%s.%s(%s) -> %s", target, funcName, strings.Join(args, ", "), ret) + } + return fmt.Sprintf("%s(%s) -> %s", funcName, strings.Join(args, ", "), ret) +} + +func describeCELType(t *types.Type) string { + if t.Kind() == types.TypeKind { + return "type" + } + return t.String() +} + var ( - emptyArgs = []*types.Type{} + emptyArgs []*types.Type ) diff --git a/vendor/github.com/google/cel-go/common/doc.go b/vendor/github.com/google/cel-go/common/doc.go index 5362fdfe..06eae364 100644 --- a/vendor/github.com/google/cel-go/common/doc.go +++ b/vendor/github.com/google/cel-go/common/doc.go @@ -15,3 +15,157 @@ // Package common defines types and utilities common to expression parsing, // checking, and interpretation package common + +import ( + "strings" + "unicode" +) + +// DocKind indicates the type of documentation element. +type DocKind int + +const ( + // DocEnv represents environment variable documentation. + DocEnv DocKind = iota + 1 + // DocFunction represents function documentation. + DocFunction + // DocOverload represents function overload documentation. + DocOverload + // DocVariable represents variable documentation. + DocVariable + // DocMacro represents macro documentation. + DocMacro + // DocExample represents example documentation. + DocExample +) + +// Doc holds the documentation details for a specific program element like +// a variable, function, macro, or example. +type Doc struct { + // Kind specifies the type of documentation element (e.g., Function, Variable). + Kind DocKind + + // Name is the identifier of the documented element (e.g., function name, variable name). + Name string + + // Type is the data type associated with the element, primarily used for variables. + Type string + + // Signature represents the function or overload signature. + Signature string + + // Description holds the textual description of the element, potentially spanning multiple lines. + Description string + + // Children holds nested documentation elements, such as overloads for a function + // or examples for a function/macro. + Children []*Doc +} + +// MultilineDescription combines multiple lines into a newline separated string. +func MultilineDescription(lines ...string) string { + return strings.Join(lines, "\n") +} + +// ParseDescription takes a single string containing newline characters and splits +// it into a multiline description. All empty lines will be skipped. +// +// Returns an empty string if the input string is empty. +func ParseDescription(doc string) string { + var lines []string + if len(doc) != 0 { + // Split the input string by newline characters. + for _, line := range strings.Split(doc, "\n") { + l := strings.TrimRightFunc(line, unicode.IsSpace) + if len(l) == 0 { + continue + } + lines = append(lines, l) + } + } + // Return an empty slice if the input is empty. + return MultilineDescription(lines...) +} + +// ParseDescriptions splits a documentation string into multiple multi-line description +// sections, using blank lines as delimiters. +func ParseDescriptions(doc string) []string { + var examples []string + if len(doc) != 0 { + lines := strings.Split(doc, "\n") + lineStart := 0 + for i, l := range lines { + // Trim trailing whitespace to identify effectively blank lines. + l = strings.TrimRightFunc(l, unicode.IsSpace) + // If a line is blank, it marks the end of the current section. + if len(l) == 0 { + // Start the next section after the blank line. + ex := lines[lineStart:i] + if len(ex) != 0 { + examples = append(examples, MultilineDescription(ex...)) + } + lineStart = i + 1 + } + } + // Append the last section if it wasn't terminated by a blank line. + if lineStart < len(lines) { + examples = append(examples, MultilineDescription(lines[lineStart:]...)) + } + } + return examples +} + +// NewVariableDoc creates a new Doc struct specifically for documenting a variable. +func NewVariableDoc(name, celType, description string) *Doc { + return &Doc{ + Kind: DocVariable, + Name: name, + Type: celType, + Description: ParseDescription(description), + } +} + +// NewFunctionDoc creates a new Doc struct for documenting a function. +func NewFunctionDoc(name, description string, overloads ...*Doc) *Doc { + return &Doc{ + Kind: DocFunction, + Name: name, + Description: ParseDescription(description), + Children: overloads, + } +} + +// NewOverloadDoc creates a new Doc struct for a function example. +func NewOverloadDoc(id, signature string, examples ...*Doc) *Doc { + return &Doc{ + Kind: DocOverload, + Name: id, + Signature: signature, + Children: examples, + } +} + +// NewMacroDoc creates a new Doc struct for documenting a macro. +func NewMacroDoc(name, description string, examples ...*Doc) *Doc { + return &Doc{ + Kind: DocMacro, + Name: name, + Description: ParseDescription(description), + Children: examples, + } +} + +// NewExampleDoc creates a new Doc struct specifically for holding an example. +func NewExampleDoc(ex string) *Doc { + return &Doc{ + Kind: DocExample, + Description: ex, + } +} + +// Documentor is an interface for types that can provide their own documentation. +type Documentor interface { + // Documentation returns the documentation coded by the DocKind to assist + // with text formatting. + Documentation() *Doc +} diff --git a/vendor/github.com/google/cel-go/common/env/BUILD.bazel b/vendor/github.com/google/cel-go/common/env/BUILD.bazel new file mode 100644 index 00000000..aebe1e54 --- /dev/null +++ b/vendor/github.com/google/cel-go/common/env/BUILD.bazel @@ -0,0 +1,50 @@ +# Copyright 2025 Google LLC +# +# 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 +# +# https://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. + +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package( + default_visibility = ["//visibility:public"], + licenses = ["notice"], # Apache 2.0 +) + +go_library( + name = "go_default_library", + srcs = [ + "env.go", + ], + importpath = "github.com/google/cel-go/common/env", + deps = [ + "//common:go_default_library", + "//common/decls:go_default_library", + "//common/types:go_default_library", + ], +) + +go_test( + name = "go_default_test", + size = "small", + srcs = [ + "env_test.go", + ], + data = glob(["testdata/**"]), + embed = [":go_default_library"], + deps = [ + "//common/decls:go_default_library", + "//common/operators:go_default_library", + "//common/overloads:go_default_library", + "//common/types:go_default_library", + "@in_gopkg_yaml_v3//:go_default_library", + ], +) diff --git a/vendor/github.com/google/cel-go/common/env/env.go b/vendor/github.com/google/cel-go/common/env/env.go new file mode 100644 index 00000000..d848860c --- /dev/null +++ b/vendor/github.com/google/cel-go/common/env/env.go @@ -0,0 +1,887 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package env provides a representation of a CEL environment. +package env + +import ( + "errors" + "fmt" + "math" + "strconv" + "strings" + + "github.com/google/cel-go/common/decls" + "github.com/google/cel-go/common/types" +) + +// NewConfig creates an instance of a YAML serializable CEL environment configuration. +func NewConfig(name string) *Config { + return &Config{ + Name: name, + } +} + +// Config represents a serializable form of the CEL environment configuration. +// +// Note: custom validations, feature flags, and performance tuning parameters are not (yet) +// considered part of the core CEL environment configuration and should be managed separately +// until a common convention for such settings is developed. +type Config struct { + Name string `yaml:"name,omitempty"` + Description string `yaml:"description,omitempty"` + Container string `yaml:"container,omitempty"` + Imports []*Import `yaml:"imports,omitempty"` + StdLib *LibrarySubset `yaml:"stdlib,omitempty"` + Extensions []*Extension `yaml:"extensions,omitempty"` + ContextVariable *ContextVariable `yaml:"context_variable,omitempty"` + Variables []*Variable `yaml:"variables,omitempty"` + Functions []*Function `yaml:"functions,omitempty"` + Validators []*Validator `yaml:"validators,omitempty"` + Features []*Feature `yaml:"features,omitempty"` +} + +// Validate validates the whole configuration is well-formed. +func (c *Config) Validate() error { + if c == nil { + return nil + } + var errs []error + for _, imp := range c.Imports { + if err := imp.Validate(); err != nil { + errs = append(errs, err) + } + } + if err := c.StdLib.Validate(); err != nil { + errs = append(errs, err) + } + for _, ext := range c.Extensions { + if err := ext.Validate(); err != nil { + errs = append(errs, err) + } + } + if err := c.ContextVariable.Validate(); err != nil { + errs = append(errs, err) + } + if c.ContextVariable != nil && len(c.Variables) != 0 { + errs = append(errs, errors.New("invalid config: either context variable or variables may be set, but not both")) + } + for _, v := range c.Variables { + if err := v.Validate(); err != nil { + errs = append(errs, err) + } + } + for _, fn := range c.Functions { + if err := fn.Validate(); err != nil { + errs = append(errs, err) + } + } + for _, feat := range c.Features { + if err := feat.Validate(); err != nil { + errs = append(errs, err) + } + } + for _, val := range c.Validators { + if err := val.Validate(); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// SetContainer configures the container name for this configuration. +func (c *Config) SetContainer(container string) *Config { + c.Container = container + return c +} + +// AddVariableDecls adds one or more variables to the config, converting them to serializable values first. +// +// VariableDecl inputs are expected to be well-formed. +func (c *Config) AddVariableDecls(vars ...*decls.VariableDecl) *Config { + convVars := make([]*Variable, len(vars)) + for i, v := range vars { + if v == nil { + continue + } + cv := NewVariable(v.Name(), SerializeTypeDesc(v.Type())) + cv.Description = v.Description() + convVars[i] = cv + } + return c.AddVariables(convVars...) +} + +// AddVariables adds one or more vairables to the config. +func (c *Config) AddVariables(vars ...*Variable) *Config { + c.Variables = append(c.Variables, vars...) + return c +} + +// SetContextVariable configures the ContextVariable for this configuration. +func (c *Config) SetContextVariable(ctx *ContextVariable) *Config { + c.ContextVariable = ctx + return c +} + +// AddFunctionDecls adds one or more functions to the config, converting them to serializable values first. +// +// FunctionDecl inputs are expected to be well-formed. +func (c *Config) AddFunctionDecls(funcs ...*decls.FunctionDecl) *Config { + convFuncs := make([]*Function, len(funcs)) + for i, fn := range funcs { + if fn == nil { + continue + } + overloads := make([]*Overload, 0, len(fn.OverloadDecls())) + for _, o := range fn.OverloadDecls() { + overloadID := o.ID() + args := make([]*TypeDesc, 0, len(o.ArgTypes())) + for _, a := range o.ArgTypes() { + args = append(args, SerializeTypeDesc(a)) + } + ret := SerializeTypeDesc(o.ResultType()) + var overload *Overload + if o.IsMemberFunction() { + overload = NewMemberOverload(overloadID, args[0], args[1:], ret) + } else { + overload = NewOverload(overloadID, args, ret) + } + exampleCount := len(o.Examples()) + if exampleCount > 0 { + overload.Examples = o.Examples() + } + overloads = append(overloads, overload) + } + cf := NewFunction(fn.Name(), overloads...) + cf.Description = fn.Description() + convFuncs[i] = cf + } + return c.AddFunctions(convFuncs...) +} + +// AddFunctions adds one or more functions to the config. +func (c *Config) AddFunctions(funcs ...*Function) *Config { + c.Functions = append(c.Functions, funcs...) + return c +} + +// SetStdLib configures the LibrarySubset for the standard library. +func (c *Config) SetStdLib(subset *LibrarySubset) *Config { + c.StdLib = subset + return c +} + +// AddImports appends a set of imports to the config. +func (c *Config) AddImports(imps ...*Import) *Config { + c.Imports = append(c.Imports, imps...) + return c +} + +// AddExtensions appends a set of extensions to the config. +func (c *Config) AddExtensions(exts ...*Extension) *Config { + c.Extensions = append(c.Extensions, exts...) + return c +} + +// AddValidators appends one or more validators to the config. +func (c *Config) AddValidators(vals ...*Validator) *Config { + c.Validators = append(c.Validators, vals...) + return c +} + +// AddFeatures appends one or more features to the config. +func (c *Config) AddFeatures(feats ...*Feature) *Config { + c.Features = append(c.Features, feats...) + return c +} + +// NewImport returns a serializable import value from the qualified type name. +func NewImport(name string) *Import { + return &Import{Name: name} +} + +// Import represents a type name that will be appreviated by its simple name using +// the cel.Abbrevs() option. +type Import struct { + Name string `yaml:"name"` +} + +// Validate validates the import configuration is well-formed. +func (imp *Import) Validate() error { + if imp == nil { + return errors.New("invalid import: nil") + } + if imp.Name == "" { + return errors.New("invalid import: missing type name") + } + return nil +} + +// NewVariable returns a serializable variable from a name and type definition +func NewVariable(name string, t *TypeDesc) *Variable { + return NewVariableWithDoc(name, t, "") +} + +// NewVariableWithDoc returns a serializable variable from a name, type definition, and doc string. +func NewVariableWithDoc(name string, t *TypeDesc, doc string) *Variable { + return &Variable{Name: name, TypeDesc: t, Description: doc} +} + +// Variable represents a typed variable declaration which will be published via the +// cel.VariableDecls() option. +type Variable struct { + Name string `yaml:"name"` + Description string `yaml:"description,omitempty"` + + // Type represents the type declaration for the variable. + // + // Deprecated: use the embedded *TypeDesc fields directly. + Type *TypeDesc `yaml:"type,omitempty"` + + // TypeDesc is an embedded set of fields allowing for the specification of the Variable type. + *TypeDesc `yaml:",inline"` +} + +// Validate validates the variable configuration is well-formed. +func (v *Variable) Validate() error { + if v == nil { + return errors.New("invalid variable: nil") + } + if v.Name == "" { + return errors.New("invalid variable: missing variable name") + } + if err := v.GetType().Validate(); err != nil { + return fmt.Errorf("invalid variable %q: %w", v.Name, err) + } + return nil +} + +// GetType returns the variable type description. +// +// Note, if both the embedded TypeDesc and the field Type are non-nil, the embedded TypeDesc will +// take precedence. +func (v *Variable) GetType() *TypeDesc { + if v == nil { + return nil + } + if v.TypeDesc != nil { + return v.TypeDesc + } + if v.Type != nil { + return v.Type + } + return nil +} + +// AsCELVariable converts the serializable form of the Variable into a CEL environment declaration. +func (v *Variable) AsCELVariable(tp types.Provider) (*decls.VariableDecl, error) { + if err := v.Validate(); err != nil { + return nil, err + } + t, err := v.GetType().AsCELType(tp) + if err != nil { + return nil, fmt.Errorf("invalid variable %q: %w", v.Name, err) + } + return decls.NewVariableWithDoc(v.Name, t, v.Description), nil +} + +// NewContextVariable returns a serializable context variable with a specific type name. +func NewContextVariable(typeName string) *ContextVariable { + return &ContextVariable{TypeName: typeName} +} + +// ContextVariable represents a structured message whose fields are to be treated as the top-level +// variable identifiers within CEL expressions. +type ContextVariable struct { + // TypeName represents the fully qualified typename of the context variable. + // Currently, only protobuf types are supported. + TypeName string `yaml:"type_name"` +} + +// Validate validates the context-variable configuration is well-formed. +func (ctx *ContextVariable) Validate() error { + if ctx == nil { + return nil + } + if ctx.TypeName == "" { + return errors.New("invalid context variable: missing type name") + } + return nil +} + +// NewFunction creates a serializable function and overload set. +func NewFunction(name string, overloads ...*Overload) *Function { + return &Function{Name: name, Overloads: overloads} +} + +// NewFunctionWithDoc creates a serializable function and overload set. +func NewFunctionWithDoc(name, doc string, overloads ...*Overload) *Function { + return &Function{Name: name, Description: doc, Overloads: overloads} +} + +// Function represents the serializable format of a function and its overloads. +type Function struct { + Name string `yaml:"name"` + Description string `yaml:"description,omitempty"` + Overloads []*Overload `yaml:"overloads,omitempty"` +} + +// Validate validates the function configuration is well-formed. +func (fn *Function) Validate() error { + if fn == nil { + return errors.New("invalid function: nil") + } + if fn.Name == "" { + return errors.New("invalid function: missing function name") + } + if len(fn.Overloads) == 0 { + return fmt.Errorf("invalid function %q: missing overloads", fn.Name) + } + var errs []error + for _, o := range fn.Overloads { + if err := o.Validate(); err != nil { + errs = append(errs, fmt.Errorf("invalid function %q: %w", fn.Name, err)) + } + } + return errors.Join(errs...) +} + +// AsCELFunction converts the serializable form of the Function into CEL environment declaration. +func (fn *Function) AsCELFunction(tp types.Provider) (*decls.FunctionDecl, error) { + if err := fn.Validate(); err != nil { + return nil, err + } + opts := make([]decls.FunctionOpt, 0, len(fn.Overloads)+1) + for _, o := range fn.Overloads { + opt, err := o.AsFunctionOption(tp) + opts = append(opts, opt) + if err != nil { + return nil, fmt.Errorf("invalid function %q: %w", fn.Name, err) + } + } + if len(fn.Description) != 0 { + opts = append(opts, decls.FunctionDocs(fn.Description)) + } + return decls.NewFunction(fn.Name, opts...) +} + +// NewOverload returns a new serializable representation of a global overload. +func NewOverload(id string, args []*TypeDesc, ret *TypeDesc, examples ...string) *Overload { + return &Overload{ID: id, Args: args, Return: ret, Examples: examples} +} + +// NewMemberOverload returns a new serializable representation of a member (receiver) overload. +func NewMemberOverload(id string, target *TypeDesc, args []*TypeDesc, ret *TypeDesc, examples ...string) *Overload { + return &Overload{ID: id, Target: target, Args: args, Return: ret, Examples: examples} +} + +// Overload represents the serializable format of a function overload. +type Overload struct { + ID string `yaml:"id"` + Examples []string `yaml:"examples,omitempty"` + Target *TypeDesc `yaml:"target,omitempty"` + Args []*TypeDesc `yaml:"args,omitempty"` + Return *TypeDesc `yaml:"return,omitempty"` +} + +// Validate validates the overload configuration is well-formed. +func (od *Overload) Validate() error { + if od == nil { + return errors.New("invalid overload: nil") + } + if od.ID == "" { + return errors.New("invalid overload: missing overload id") + } + var errs []error + if od.Target != nil { + if err := od.Target.Validate(); err != nil { + errs = append(errs, fmt.Errorf("invalid overload %q target: %w", od.ID, err)) + } + } + for i, arg := range od.Args { + if err := arg.Validate(); err != nil { + errs = append(errs, fmt.Errorf("invalid overload %q arg[%d]: %w", od.ID, i, err)) + } + } + if err := od.Return.Validate(); err != nil { + errs = append(errs, fmt.Errorf("invalid overload %q return: %w", od.ID, err)) + } + return errors.Join(errs...) +} + +// AsFunctionOption converts the serializable form of the Overload into a function declaration option. +func (od *Overload) AsFunctionOption(tp types.Provider) (decls.FunctionOpt, error) { + if err := od.Validate(); err != nil { + return nil, err + } + args := make([]*types.Type, len(od.Args)) + var err error + var errs []error + for i, a := range od.Args { + args[i], err = a.AsCELType(tp) + if err != nil { + errs = append(errs, err) + } + } + result, err := od.Return.AsCELType(tp) + if err != nil { + errs = append(errs, err) + } + if od.Target != nil { + t, err := od.Target.AsCELType(tp) + if err != nil { + return nil, errors.Join(append(errs, err)...) + } + args = append([]*types.Type{t}, args...) + return decls.MemberOverload(od.ID, args, result), nil + } + if len(errs) != 0 { + return nil, errors.Join(errs...) + } + return decls.Overload(od.ID, args, result, decls.OverloadExamples(od.Examples...)), nil +} + +// NewExtension creates a serializable Extension from a name and version string. +func NewExtension(name string, version uint32) *Extension { + versionString := "latest" + if version < math.MaxUint32 { + versionString = strconv.FormatUint(uint64(version), 10) + } + return &Extension{ + Name: name, + Version: versionString, + } +} + +// Extension represents a named and optionally versioned extension library configured in the environment. +type Extension struct { + // Name is either the LibraryName() or some short-hand simple identifier which is understood by the config-handler. + Name string `yaml:"name"` + + // Version may either be an unsigned long value or the string 'latest'. If empty, the value is treated as '0'. + Version string `yaml:"version,omitempty"` +} + +// Validate validates the extension configuration is well-formed. +func (e *Extension) Validate() error { + _, err := e.VersionNumber() + return err +} + +// VersionNumber returns the parsed version string, or an error if the version cannot be parsed. +func (e *Extension) VersionNumber() (uint32, error) { + if e == nil { + return 0, fmt.Errorf("invalid extension: nil") + } + if e.Name == "" { + return 0, fmt.Errorf("invalid extension: missing name") + } + if e.Version == "latest" { + return math.MaxUint32, nil + } + if e.Version == "" { + return 0, nil + } + ver, err := strconv.ParseUint(e.Version, 10, 32) + if err != nil { + return 0, fmt.Errorf("invalid extension %q version: %w", e.Name, err) + } + return uint32(ver), nil +} + +// NewLibrarySubset returns an empty library subsetting config which permits all library features. +func NewLibrarySubset() *LibrarySubset { + return &LibrarySubset{} +} + +// LibrarySubset indicates a subset of the macros and function supported by a subsettable library. +type LibrarySubset struct { + // Disabled indicates whether the library has been disabled, typically only used for + // default-enabled libraries like stdlib. + Disabled bool `yaml:"disabled,omitempty"` + + // DisableMacros disables macros for the given library. + DisableMacros bool `yaml:"disable_macros,omitempty"` + + // IncludeMacros specifies a set of macro function names to include in the subset. + IncludeMacros []string `yaml:"include_macros,omitempty"` + + // ExcludeMacros specifies a set of macro function names to exclude from the subset. + // Note: if IncludeMacros is non-empty, then ExcludeFunctions is ignored. + ExcludeMacros []string `yaml:"exclude_macros,omitempty"` + + // IncludeFunctions specifies a set of functions to include in the subset. + // + // Note: the overloads specified in the subset need only specify their ID. + // Note: if IncludeFunctions is non-empty, then ExcludeFunctions is ignored. + IncludeFunctions []*Function `yaml:"include_functions,omitempty"` + + // ExcludeFunctions specifies the set of functions to exclude from the subset. + // + // Note: the overloads specified in the subset need only specify their ID. + ExcludeFunctions []*Function `yaml:"exclude_functions,omitempty"` +} + +// Validate validates the library configuration is well-formed. +// +// For example, setting both the IncludeMacros and ExcludeMacros together could be confusing +// and create a broken expectation, likewise for IncludeFunctions and ExcludeFunctions. +func (lib *LibrarySubset) Validate() error { + if lib == nil { + return nil + } + var errs []error + if len(lib.IncludeMacros) != 0 && len(lib.ExcludeMacros) != 0 { + errs = append(errs, errors.New("invalid subset: cannot both include and exclude macros")) + } + if len(lib.IncludeFunctions) != 0 && len(lib.ExcludeFunctions) != 0 { + errs = append(errs, errors.New("invalid subset: cannot both include and exclude functions")) + } + return errors.Join(errs...) +} + +// SubsetFunction produces a function declaration which matches the supported subset, or nil +// if the function is not supported by the LibrarySubset. +// +// For IncludeFunctions, if the function does not specify a set of overloads to include, the +// whole function definition is included. If overloads are set, then a new function which +// includes only the specified overloads is produced. +// +// For ExcludeFunctions, if the function does not specify a set of overloads to exclude, the +// whole function definition is excluded. If overloads are set, then a new function which +// includes only the permitted overloads is produced. +func (lib *LibrarySubset) SubsetFunction(fn *decls.FunctionDecl) (*decls.FunctionDecl, bool) { + // When lib is null, it should indicate that all values are included in the subset. + if lib == nil { + return fn, true + } + if lib.Disabled { + return nil, false + } + if len(lib.IncludeFunctions) != 0 { + for _, include := range lib.IncludeFunctions { + if include.Name != fn.Name() { + continue + } + if len(include.Overloads) == 0 { + return fn, true + } + overloadIDs := make([]string, len(include.Overloads)) + for i, o := range include.Overloads { + overloadIDs[i] = o.ID + } + return fn.Subset(decls.IncludeOverloads(overloadIDs...)), true + } + return nil, false + } + if len(lib.ExcludeFunctions) != 0 { + for _, exclude := range lib.ExcludeFunctions { + if exclude.Name != fn.Name() { + continue + } + if len(exclude.Overloads) == 0 { + return nil, false + } + overloadIDs := make([]string, len(exclude.Overloads)) + for i, o := range exclude.Overloads { + overloadIDs[i] = o.ID + } + return fn.Subset(decls.ExcludeOverloads(overloadIDs...)), true + } + return fn, true + } + return fn, true +} + +// SubsetMacro indicates whether the macro function should be included in the library subset. +func (lib *LibrarySubset) SubsetMacro(macroFunction string) bool { + // When lib is null, it should indicate that all values are included in the subset. + if lib == nil { + return true + } + if lib.Disabled || lib.DisableMacros { + return false + } + if len(lib.IncludeMacros) != 0 { + for _, name := range lib.IncludeMacros { + if name == macroFunction { + return true + } + } + return false + } + if len(lib.ExcludeMacros) != 0 { + for _, name := range lib.ExcludeMacros { + if name == macroFunction { + return false + } + } + return true + } + return true +} + +// SetDisabled disables or enables the library. +func (lib *LibrarySubset) SetDisabled(value bool) *LibrarySubset { + lib.Disabled = value + return lib +} + +// SetDisableMacros disables the macros for the library. +func (lib *LibrarySubset) SetDisableMacros(value bool) *LibrarySubset { + lib.DisableMacros = value + return lib +} + +// AddIncludedMacros allow-lists one or more macros by function name. +// +// Note, this option will override any excluded macros. +func (lib *LibrarySubset) AddIncludedMacros(macros ...string) *LibrarySubset { + lib.IncludeMacros = append(lib.IncludeMacros, macros...) + return lib +} + +// AddExcludedMacros deny-lists one or more macros by function name. +func (lib *LibrarySubset) AddExcludedMacros(macros ...string) *LibrarySubset { + lib.ExcludeMacros = append(lib.ExcludeMacros, macros...) + return lib +} + +// AddIncludedFunctions allow-lists one or more functions from the subset. +// +// Note, this option will override any excluded functions. +func (lib *LibrarySubset) AddIncludedFunctions(funcs ...*Function) *LibrarySubset { + lib.IncludeFunctions = append(lib.IncludeFunctions, funcs...) + return lib +} + +// AddExcludedFunctions deny-lists one or more functions from the subset. +func (lib *LibrarySubset) AddExcludedFunctions(funcs ...*Function) *LibrarySubset { + lib.ExcludeFunctions = append(lib.ExcludeFunctions, funcs...) + return lib +} + +// NewValidator returns a named Validator instance. +func NewValidator(name string) *Validator { + return &Validator{Name: name} +} + +// Validator represents a named validator with an optional map-based configuration object. +// +// Note: the map-keys must directly correspond to the internal representation of the original +// validator, and should only use primitive scalar types as values at this time. +type Validator struct { + Name string `yaml:"name"` + Config map[string]any `yaml:"config,omitempty"` +} + +// Validate validates the configuration of the validator object. +func (v *Validator) Validate() error { + if v == nil { + return errors.New("invalid validator: nil") + } + if v.Name == "" { + return errors.New("invalid validator: missing name") + } + return nil +} + +// SetConfig sets the set of map key-value pairs associated with this validator's configuration. +func (v *Validator) SetConfig(config map[string]any) *Validator { + v.Config = config + return v +} + +// ConfigValue retrieves the value associated with the config key name, if one exists. +func (v *Validator) ConfigValue(name string) (any, bool) { + if v == nil { + return nil, false + } + value, found := v.Config[name] + return value, found +} + +// NewFeature creates a new feature flag with a boolean enablement flag. +func NewFeature(name string, enabled bool) *Feature { + return &Feature{Name: name, Enabled: enabled} +} + +// Feature represents a named boolean feature flag supported by CEL. +type Feature struct { + Name string `yaml:"name"` + Enabled bool `yaml:"enabled"` +} + +// Validate validates whether the feature is well-configured. +func (feat *Feature) Validate() error { + if feat == nil { + return errors.New("invalid feature: nil") + } + if feat.Name == "" { + return errors.New("invalid feature: missing name") + } + return nil +} + +// NewTypeDesc describes a simple or complex type with parameters. +func NewTypeDesc(typeName string, params ...*TypeDesc) *TypeDesc { + return &TypeDesc{TypeName: typeName, Params: params} +} + +// NewTypeParam describe a type-param type. +func NewTypeParam(paramName string) *TypeDesc { + return &TypeDesc{TypeName: paramName, IsTypeParam: true} +} + +// TypeDesc represents the serializable format of a CEL *types.Type value. +type TypeDesc struct { + TypeName string `yaml:"type_name"` + Params []*TypeDesc `yaml:"params,omitempty"` + IsTypeParam bool `yaml:"is_type_param,omitempty"` +} + +// String implements the strings.Stringer interface method. +func (td *TypeDesc) String() string { + ps := make([]string, len(td.Params)) + for i, p := range td.Params { + ps[i] = p.String() + } + typeName := td.TypeName + if len(ps) != 0 { + typeName = fmt.Sprintf("%s(%s)", typeName, strings.Join(ps, ",")) + } + return typeName +} + +// Validate validates the type configuration is well-formed. +func (td *TypeDesc) Validate() error { + if td == nil { + return errors.New("invalid type: nil") + } + if td.TypeName == "" { + return errors.New("invalid type: missing type name") + } + if td.IsTypeParam && len(td.Params) != 0 { + return errors.New("invalid type: param type cannot have parameters") + } + switch td.TypeName { + case "list": + if len(td.Params) != 1 { + return fmt.Errorf("invalid type: list expects 1 parameter, got %d", len(td.Params)) + } + return td.Params[0].Validate() + case "map": + if len(td.Params) != 2 { + return fmt.Errorf("invalid type: map expects 2 parameters, got %d", len(td.Params)) + } + if err := td.Params[0].Validate(); err != nil { + return err + } + if err := td.Params[1].Validate(); err != nil { + return err + } + case "optional_type": + if len(td.Params) != 1 { + return fmt.Errorf("invalid type: optional_type expects 1 parameter, got %d", len(td.Params)) + } + return td.Params[0].Validate() + default: + } + return nil +} + +// AsCELType converts the serializable object to a *types.Type value. +func (td *TypeDesc) AsCELType(tp types.Provider) (*types.Type, error) { + err := td.Validate() + if err != nil { + return nil, err + } + switch td.TypeName { + case "dyn": + return types.DynType, nil + case "map": + kt, err := td.Params[0].AsCELType(tp) + if err != nil { + return nil, err + } + vt, err := td.Params[1].AsCELType(tp) + if err != nil { + return nil, err + } + return types.NewMapType(kt, vt), nil + case "list": + et, err := td.Params[0].AsCELType(tp) + if err != nil { + return nil, err + } + return types.NewListType(et), nil + case "optional_type": + et, err := td.Params[0].AsCELType(tp) + if err != nil { + return nil, err + } + return types.NewOptionalType(et), nil + default: + if td.IsTypeParam { + return types.NewTypeParamType(td.TypeName), nil + } + if msgType, found := tp.FindStructType(td.TypeName); found { + // First parameter is the type name. + return msgType.Parameters()[0], nil + } + t, found := tp.FindIdent(td.TypeName) + if !found { + return nil, fmt.Errorf("undefined type name: %q", td.TypeName) + } + _, ok := t.(*types.Type) + if ok && len(td.Params) == 0 { + return t.(*types.Type), nil + } + params := make([]*types.Type, len(td.Params)) + for i, p := range td.Params { + params[i], err = p.AsCELType(tp) + if err != nil { + return nil, err + } + } + return types.NewOpaqueType(td.TypeName, params...), nil + } +} + +// SerializeTypeDesc converts a CEL native *types.Type to a serializable TypeDesc. +func SerializeTypeDesc(t *types.Type) *TypeDesc { + typeName := t.TypeName() + if t.Kind() == types.TypeParamKind { + return NewTypeParam(typeName) + } + if t != types.NullType && t.IsAssignableType(types.NullType) { + if wrapperTypeName, found := wrapperTypes[t.Kind()]; found { + return NewTypeDesc(wrapperTypeName) + } + } + var params []*TypeDesc + for _, p := range t.Parameters() { + params = append(params, SerializeTypeDesc(p)) + } + return NewTypeDesc(typeName, params...) +} + +var wrapperTypes = map[types.Kind]string{ + types.BoolKind: "google.protobuf.BoolValue", + types.BytesKind: "google.protobuf.BytesValue", + types.DoubleKind: "google.protobuf.DoubleValue", + types.IntKind: "google.protobuf.Int64Value", + types.StringKind: "google.protobuf.StringValue", + types.UintKind: "google.protobuf.UInt64Value", +} diff --git a/vendor/github.com/google/cel-go/common/stdlib/BUILD.bazel b/vendor/github.com/google/cel-go/common/stdlib/BUILD.bazel index b55f4521..124dbea8 100644 --- a/vendor/github.com/google/cel-go/common/stdlib/BUILD.bazel +++ b/vendor/github.com/google/cel-go/common/stdlib/BUILD.bazel @@ -12,6 +12,7 @@ go_library( ], importpath = "github.com/google/cel-go/common/stdlib", deps = [ + "//common:go_default_library", "//common/decls:go_default_library", "//common/functions:go_default_library", "//common/operators:go_default_library", diff --git a/vendor/github.com/google/cel-go/common/stdlib/standard.go b/vendor/github.com/google/cel-go/common/stdlib/standard.go index 1550c178..4040a4f5 100644 --- a/vendor/github.com/google/cel-go/common/stdlib/standard.go +++ b/vendor/github.com/google/cel-go/common/stdlib/standard.go @@ -16,6 +16,11 @@ package stdlib import ( + "strconv" + "strings" + "time" + + "github.com/google/cel-go/common" "github.com/google/cel-go/common/decls" "github.com/google/cel-go/common/functions" "github.com/google/cel-go/common/operators" @@ -28,6 +33,7 @@ import ( var ( stdFunctions []*decls.FunctionDecl stdTypes []*decls.VariableDecl + utcTZ = types.String("UTC") ) func init() { @@ -55,19 +61,49 @@ func init() { // Logical operators. Special-cased within the interpreter. // Note, the singleton binding prevents extensions from overriding the operator behavior. function(operators.Conditional, + decls.FunctionDocs( + `The ternary operator tests a boolean predicate and returns the left-hand side `+ + `(truthy) expression if true, or the right-hand side (falsy) expression if false`), decls.Overload(overloads.Conditional, argTypes(types.BoolType, paramA, paramA), paramA, - decls.OverloadIsNonStrict()), + decls.OverloadIsNonStrict(), + decls.OverloadExamples( + `'hello'.contains('lo') ? 'hi' : 'bye' // 'hi'`, + `32 % 3 == 0 ? 'divisible' : 'not divisible' // 'not divisible'`)), decls.SingletonFunctionBinding(noFunctionOverrides)), + function(operators.LogicalAnd, + decls.FunctionDocs( + `logically AND two boolean values. Errors and unknown values`, + `are valid inputs and will not halt evaluation.`), decls.Overload(overloads.LogicalAnd, argTypes(types.BoolType, types.BoolType), types.BoolType, - decls.OverloadIsNonStrict()), + decls.OverloadIsNonStrict(), + decls.OverloadExamples( + `true && true // true`, + `true && false // false`, + `error && true // error`, + `error && false // false`)), decls.SingletonBinaryBinding(noBinaryOverrides)), + function(operators.LogicalOr, + decls.FunctionDocs( + `logically OR two boolean values. Errors and unknown values`, + `are valid inputs and will not halt evaluation.`), decls.Overload(overloads.LogicalOr, argTypes(types.BoolType, types.BoolType), types.BoolType, - decls.OverloadIsNonStrict()), + decls.OverloadIsNonStrict(), + decls.OverloadExamples( + `true || false // true`, + `false || false // false`, + `error || true // true`, + `error || error // true`)), decls.SingletonBinaryBinding(noBinaryOverrides)), + function(operators.LogicalNot, - decls.Overload(overloads.LogicalNot, argTypes(types.BoolType), types.BoolType), + decls.FunctionDocs(`logically negate a boolean value.`), + decls.Overload(overloads.LogicalNot, argTypes(types.BoolType), types.BoolType, + decls.OverloadExamples( + `!true // false`, + `!false // true`, + `!error // error`)), decls.SingletonUnaryBinding(func(val ref.Val) ref.Val { b, ok := val.(types.Bool) if !ok { @@ -90,66 +126,104 @@ func init() { // Equality / inequality. Special-cased in the interpreter function(operators.Equals, - decls.Overload(overloads.Equals, argTypes(paramA, paramA), types.BoolType), + decls.FunctionDocs(`compare two values of the same type for equality`), + decls.Overload(overloads.Equals, argTypes(paramA, paramA), types.BoolType, + decls.OverloadExamples( + `1 == 1 // true`, + `'hello' == 'world' // false`, + `bytes('hello') == b'hello' // true`, + `duration('1h') == duration('60m') // true`, + `dyn(3.0) == 3 // true`)), decls.SingletonBinaryBinding(noBinaryOverrides)), function(operators.NotEquals, - decls.Overload(overloads.NotEquals, argTypes(paramA, paramA), types.BoolType), + decls.FunctionDocs(`compare two values of the same type for inequality`), + decls.Overload(overloads.NotEquals, argTypes(paramA, paramA), types.BoolType, + decls.OverloadExamples( + `1 != 2 // true`, + `"a" != "a" // false`, + `3.0 != 3.1 // true`)), decls.SingletonBinaryBinding(noBinaryOverrides)), // Mathematical operators function(operators.Add, + decls.FunctionDocs( + `adds two numeric values or concatenates two strings, bytes,`, + `or lists.`), decls.Overload(overloads.AddBytes, - argTypes(types.BytesType, types.BytesType), types.BytesType), + argTypes(types.BytesType, types.BytesType), types.BytesType, + decls.OverloadExamples(`b'hi' + bytes('ya') // b'hiya'`)), decls.Overload(overloads.AddDouble, - argTypes(types.DoubleType, types.DoubleType), types.DoubleType), + argTypes(types.DoubleType, types.DoubleType), types.DoubleType, + decls.OverloadExamples(`3.14 + 1.59 // 4.73`)), decls.Overload(overloads.AddDurationDuration, - argTypes(types.DurationType, types.DurationType), types.DurationType), + argTypes(types.DurationType, types.DurationType), types.DurationType, + decls.OverloadExamples(`duration('1m') + duration('1s') // duration('1m1s')`)), decls.Overload(overloads.AddDurationTimestamp, - argTypes(types.DurationType, types.TimestampType), types.TimestampType), + argTypes(types.DurationType, types.TimestampType), types.TimestampType, + decls.OverloadExamples(`duration('24h') + timestamp('2023-01-01T00:00:00Z') // timestamp('2023-01-02T00:00:00Z')`)), decls.Overload(overloads.AddTimestampDuration, - argTypes(types.TimestampType, types.DurationType), types.TimestampType), + argTypes(types.TimestampType, types.DurationType), types.TimestampType, + decls.OverloadExamples(`timestamp('2023-01-01T00:00:00Z') + duration('24h1m2s') // timestamp('2023-01-02T00:01:02Z')`)), decls.Overload(overloads.AddInt64, - argTypes(types.IntType, types.IntType), types.IntType), + argTypes(types.IntType, types.IntType), types.IntType, + decls.OverloadExamples(`1 + 2 // 3`)), decls.Overload(overloads.AddList, - argTypes(listOfA, listOfA), listOfA), + argTypes(listOfA, listOfA), listOfA, + decls.OverloadExamples(`[1] + [2, 3] // [1, 2, 3]`)), decls.Overload(overloads.AddString, - argTypes(types.StringType, types.StringType), types.StringType), + argTypes(types.StringType, types.StringType), types.StringType, + decls.OverloadExamples(`"Hello, " + "world!" // "Hello, world!"`)), decls.Overload(overloads.AddUint64, - argTypes(types.UintType, types.UintType), types.UintType), + argTypes(types.UintType, types.UintType), types.UintType, + decls.OverloadExamples(`22u + 33u // 55u`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { return lhs.(traits.Adder).Add(rhs) }, traits.AdderType)), function(operators.Divide, + decls.FunctionDocs(`divide two numbers`), decls.Overload(overloads.DivideDouble, - argTypes(types.DoubleType, types.DoubleType), types.DoubleType), + argTypes(types.DoubleType, types.DoubleType), types.DoubleType, + decls.OverloadExamples(`7.0 / 2.0 // 3.5`)), decls.Overload(overloads.DivideInt64, - argTypes(types.IntType, types.IntType), types.IntType), + argTypes(types.IntType, types.IntType), types.IntType, + decls.OverloadExamples(`10 / 2 // 5`)), decls.Overload(overloads.DivideUint64, - argTypes(types.UintType, types.UintType), types.UintType), + argTypes(types.UintType, types.UintType), types.UintType, + decls.OverloadExamples(`42u / 2u // 21u`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { return lhs.(traits.Divider).Divide(rhs) }, traits.DividerType)), function(operators.Modulo, + decls.FunctionDocs(`compute the modulus of one integer into another`), decls.Overload(overloads.ModuloInt64, - argTypes(types.IntType, types.IntType), types.IntType), + argTypes(types.IntType, types.IntType), types.IntType, + decls.OverloadExamples(`3 % 2 // 1`)), decls.Overload(overloads.ModuloUint64, - argTypes(types.UintType, types.UintType), types.UintType), + argTypes(types.UintType, types.UintType), types.UintType, + decls.OverloadExamples(`6u % 3u // 0u`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { return lhs.(traits.Modder).Modulo(rhs) }, traits.ModderType)), function(operators.Multiply, + decls.FunctionDocs(`multiply two numbers`), decls.Overload(overloads.MultiplyDouble, - argTypes(types.DoubleType, types.DoubleType), types.DoubleType), + argTypes(types.DoubleType, types.DoubleType), types.DoubleType, + decls.OverloadExamples(`3.5 * 40.0 // 140.0`)), decls.Overload(overloads.MultiplyInt64, - argTypes(types.IntType, types.IntType), types.IntType), + argTypes(types.IntType, types.IntType), types.IntType, + decls.OverloadExamples(`-2 * 6 // -12`)), decls.Overload(overloads.MultiplyUint64, - argTypes(types.UintType, types.UintType), types.UintType), + argTypes(types.UintType, types.UintType), types.UintType, + decls.OverloadExamples(`13u * 3u // 39u`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { return lhs.(traits.Multiplier).Multiply(rhs) }, traits.MultiplierType)), function(operators.Negate, - decls.Overload(overloads.NegateDouble, argTypes(types.DoubleType), types.DoubleType), - decls.Overload(overloads.NegateInt64, argTypes(types.IntType), types.IntType), + decls.FunctionDocs(`negate a numeric value`), + decls.Overload(overloads.NegateDouble, argTypes(types.DoubleType), types.DoubleType, + decls.OverloadExamples(`-(3.14) // -3.14`)), + decls.Overload(overloads.NegateInt64, argTypes(types.IntType), types.IntType, + decls.OverloadExamples(`-(5) // -5`)), decls.SingletonUnaryBinding(func(val ref.Val) ref.Val { if types.IsBool(val) { return types.MaybeNoSuchOverloadErr(val) @@ -157,18 +231,32 @@ func init() { return val.(traits.Negater).Negate() }, traits.NegatorType)), function(operators.Subtract, + decls.FunctionDocs(`subtract two numbers, or two time-related values`), decls.Overload(overloads.SubtractDouble, - argTypes(types.DoubleType, types.DoubleType), types.DoubleType), + argTypes(types.DoubleType, types.DoubleType), types.DoubleType, + decls.OverloadExamples(`10.5 - 2.0 // 8.5`)), decls.Overload(overloads.SubtractDurationDuration, - argTypes(types.DurationType, types.DurationType), types.DurationType), + argTypes(types.DurationType, types.DurationType), types.DurationType, + decls.OverloadExamples(`duration('1m') - duration('1s') // duration('59s')`)), decls.Overload(overloads.SubtractInt64, - argTypes(types.IntType, types.IntType), types.IntType), + argTypes(types.IntType, types.IntType), types.IntType, + decls.OverloadExamples(`5 - 3 // 2`)), decls.Overload(overloads.SubtractTimestampDuration, - argTypes(types.TimestampType, types.DurationType), types.TimestampType), + argTypes(types.TimestampType, types.DurationType), types.TimestampType, + decls.OverloadExamples(common.MultilineDescription( + `timestamp('2023-01-10T12:00:00Z')`, + ` - duration('12h') // timestamp('2023-01-10T00:00:00Z')`))), decls.Overload(overloads.SubtractTimestampTimestamp, - argTypes(types.TimestampType, types.TimestampType), types.DurationType), + argTypes(types.TimestampType, types.TimestampType), types.DurationType, + decls.OverloadExamples(common.MultilineDescription( + `timestamp('2023-01-10T12:00:00Z')`, + ` - timestamp('2023-01-10T00:00:00Z') // duration('12h')`))), decls.Overload(overloads.SubtractUint64, - argTypes(types.UintType, types.UintType), types.UintType), + argTypes(types.UintType, types.UintType), types.UintType, + decls.OverloadExamples(common.MultilineDescription( + `// the subtraction result must be positive, otherwise an overflow`, + `// error is generated.`, + `42u - 3u // 39u`))), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { return lhs.(traits.Subtractor).Subtract(rhs) }, traits.SubtractorType)), @@ -176,34 +264,51 @@ func init() { // Relations operators function(operators.Less, + decls.FunctionDocs( + `compare two values and return true if the first value is`, + `less than the second`), decls.Overload(overloads.LessBool, - argTypes(types.BoolType, types.BoolType), types.BoolType), + argTypes(types.BoolType, types.BoolType), types.BoolType, + decls.OverloadExamples(`false < true // true`)), decls.Overload(overloads.LessInt64, - argTypes(types.IntType, types.IntType), types.BoolType), + argTypes(types.IntType, types.IntType), types.BoolType, + decls.OverloadExamples(`-2 < 3 // true`, `1 < 0 // false`)), decls.Overload(overloads.LessInt64Double, - argTypes(types.IntType, types.DoubleType), types.BoolType), + argTypes(types.IntType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`1 < 1.1 // true`)), decls.Overload(overloads.LessInt64Uint64, - argTypes(types.IntType, types.UintType), types.BoolType), + argTypes(types.IntType, types.UintType), types.BoolType, + decls.OverloadExamples(`1 < 2u // true`)), decls.Overload(overloads.LessUint64, - argTypes(types.UintType, types.UintType), types.BoolType), + argTypes(types.UintType, types.UintType), types.BoolType, + decls.OverloadExamples(`1u < 2u // true`)), decls.Overload(overloads.LessUint64Double, - argTypes(types.UintType, types.DoubleType), types.BoolType), + argTypes(types.UintType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`1u < 0.9 // false`)), decls.Overload(overloads.LessUint64Int64, - argTypes(types.UintType, types.IntType), types.BoolType), + argTypes(types.UintType, types.IntType), types.BoolType, + decls.OverloadExamples(`1u < 23 // true`, `1u < -1 // false`)), decls.Overload(overloads.LessDouble, - argTypes(types.DoubleType, types.DoubleType), types.BoolType), + argTypes(types.DoubleType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2.0 < 2.4 // true`)), decls.Overload(overloads.LessDoubleInt64, - argTypes(types.DoubleType, types.IntType), types.BoolType), + argTypes(types.DoubleType, types.IntType), types.BoolType, + decls.OverloadExamples(`2.1 < 3 // true`)), decls.Overload(overloads.LessDoubleUint64, - argTypes(types.DoubleType, types.UintType), types.BoolType), + argTypes(types.DoubleType, types.UintType), types.BoolType, + decls.OverloadExamples(`2.3 < 2u // false`, `-1.0 < 1u // true`)), decls.Overload(overloads.LessString, - argTypes(types.StringType, types.StringType), types.BoolType), + argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples(`'a' < 'b' // true`, `'cat' < 'cab' // false`)), decls.Overload(overloads.LessBytes, - argTypes(types.BytesType, types.BytesType), types.BoolType), + argTypes(types.BytesType, types.BytesType), types.BoolType, + decls.OverloadExamples(`b'hello' < b'world' // true`)), decls.Overload(overloads.LessTimestamp, - argTypes(types.TimestampType, types.TimestampType), types.BoolType), + argTypes(types.TimestampType, types.TimestampType), types.BoolType, + decls.OverloadExamples(`timestamp('2001-01-01T02:03:04Z') < timestamp('2002-02-02T02:03:04Z') // true`)), decls.Overload(overloads.LessDuration, - argTypes(types.DurationType, types.DurationType), types.BoolType), + argTypes(types.DurationType, types.DurationType), types.BoolType, + decls.OverloadExamples(`duration('1ms') < duration('1s') // true`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { cmp := lhs.(traits.Comparer).Compare(rhs) if cmp == types.IntNegOne { @@ -216,34 +321,51 @@ func init() { }, traits.ComparerType)), function(operators.LessEquals, + decls.FunctionDocs( + `compare two values and return true if the first value is`, + `less than or equal to the second`), decls.Overload(overloads.LessEqualsBool, - argTypes(types.BoolType, types.BoolType), types.BoolType), + argTypes(types.BoolType, types.BoolType), types.BoolType, + decls.OverloadExamples(`false <= true // true`)), decls.Overload(overloads.LessEqualsInt64, - argTypes(types.IntType, types.IntType), types.BoolType), + argTypes(types.IntType, types.IntType), types.BoolType, + decls.OverloadExamples(`-2 <= 3 // true`)), decls.Overload(overloads.LessEqualsInt64Double, - argTypes(types.IntType, types.DoubleType), types.BoolType), + argTypes(types.IntType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`1 <= 1.1 // true`)), decls.Overload(overloads.LessEqualsInt64Uint64, - argTypes(types.IntType, types.UintType), types.BoolType), + argTypes(types.IntType, types.UintType), types.BoolType, + decls.OverloadExamples(`1 <= 2u // true`, `-1 <= 0u // true`)), decls.Overload(overloads.LessEqualsUint64, - argTypes(types.UintType, types.UintType), types.BoolType), + argTypes(types.UintType, types.UintType), types.BoolType, + decls.OverloadExamples(`1u <= 2u // true`)), decls.Overload(overloads.LessEqualsUint64Double, - argTypes(types.UintType, types.DoubleType), types.BoolType), + argTypes(types.UintType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`1u <= 1.0 // true`, `1u <= 1.1 // true`)), decls.Overload(overloads.LessEqualsUint64Int64, - argTypes(types.UintType, types.IntType), types.BoolType), + argTypes(types.UintType, types.IntType), types.BoolType, + decls.OverloadExamples(`1u <= 23 // true`)), decls.Overload(overloads.LessEqualsDouble, - argTypes(types.DoubleType, types.DoubleType), types.BoolType), + argTypes(types.DoubleType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2.0 <= 2.4 // true`)), decls.Overload(overloads.LessEqualsDoubleInt64, - argTypes(types.DoubleType, types.IntType), types.BoolType), + argTypes(types.DoubleType, types.IntType), types.BoolType, + decls.OverloadExamples(`2.1 <= 3 // true`)), decls.Overload(overloads.LessEqualsDoubleUint64, - argTypes(types.DoubleType, types.UintType), types.BoolType), + argTypes(types.DoubleType, types.UintType), types.BoolType, + decls.OverloadExamples(`2.0 <= 2u // true`, `-1.0 <= 1u // true`)), decls.Overload(overloads.LessEqualsString, - argTypes(types.StringType, types.StringType), types.BoolType), + argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples(`'a' <= 'b' // true`, `'a' <= 'a' // true`, `'cat' <= 'cab' // false`)), decls.Overload(overloads.LessEqualsBytes, - argTypes(types.BytesType, types.BytesType), types.BoolType), + argTypes(types.BytesType, types.BytesType), types.BoolType, + decls.OverloadExamples(`b'hello' <= b'world' // true`)), decls.Overload(overloads.LessEqualsTimestamp, - argTypes(types.TimestampType, types.TimestampType), types.BoolType), + argTypes(types.TimestampType, types.TimestampType), types.BoolType, + decls.OverloadExamples(`timestamp('2001-01-01T02:03:04Z') <= timestamp('2002-02-02T02:03:04Z') // true`)), decls.Overload(overloads.LessEqualsDuration, - argTypes(types.DurationType, types.DurationType), types.BoolType), + argTypes(types.DurationType, types.DurationType), types.BoolType, + decls.OverloadExamples(`duration('1ms') <= duration('1s') // true`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { cmp := lhs.(traits.Comparer).Compare(rhs) if cmp == types.IntNegOne || cmp == types.IntZero { @@ -256,34 +378,51 @@ func init() { }, traits.ComparerType)), function(operators.Greater, + decls.FunctionDocs( + `compare two values and return true if the first value is`, + `greater than the second`), decls.Overload(overloads.GreaterBool, - argTypes(types.BoolType, types.BoolType), types.BoolType), + argTypes(types.BoolType, types.BoolType), types.BoolType, + decls.OverloadExamples(`true > false // true`)), decls.Overload(overloads.GreaterInt64, - argTypes(types.IntType, types.IntType), types.BoolType), + argTypes(types.IntType, types.IntType), types.BoolType, + decls.OverloadExamples(`3 > -2 // true`)), decls.Overload(overloads.GreaterInt64Double, - argTypes(types.IntType, types.DoubleType), types.BoolType), + argTypes(types.IntType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2 > 1.1 // true`)), decls.Overload(overloads.GreaterInt64Uint64, - argTypes(types.IntType, types.UintType), types.BoolType), + argTypes(types.IntType, types.UintType), types.BoolType, + decls.OverloadExamples(`3 > 2u // true`)), decls.Overload(overloads.GreaterUint64, - argTypes(types.UintType, types.UintType), types.BoolType), + argTypes(types.UintType, types.UintType), types.BoolType, + decls.OverloadExamples(`2u > 1u // true`)), decls.Overload(overloads.GreaterUint64Double, - argTypes(types.UintType, types.DoubleType), types.BoolType), + argTypes(types.UintType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2u > 1.9 // true`)), decls.Overload(overloads.GreaterUint64Int64, - argTypes(types.UintType, types.IntType), types.BoolType), + argTypes(types.UintType, types.IntType), types.BoolType, + decls.OverloadExamples(`23u > 1 // true`, `0u > -1 // true`)), decls.Overload(overloads.GreaterDouble, - argTypes(types.DoubleType, types.DoubleType), types.BoolType), + argTypes(types.DoubleType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2.4 > 2.0 // true`)), decls.Overload(overloads.GreaterDoubleInt64, - argTypes(types.DoubleType, types.IntType), types.BoolType), + argTypes(types.DoubleType, types.IntType), types.BoolType, + decls.OverloadExamples(`3.1 > 3 // true`, `3.0 > 3 // false`)), decls.Overload(overloads.GreaterDoubleUint64, - argTypes(types.DoubleType, types.UintType), types.BoolType), + argTypes(types.DoubleType, types.UintType), types.BoolType, + decls.OverloadExamples(`2.3 > 2u // true`)), decls.Overload(overloads.GreaterString, - argTypes(types.StringType, types.StringType), types.BoolType), + argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples(`'b' > 'a' // true`)), decls.Overload(overloads.GreaterBytes, - argTypes(types.BytesType, types.BytesType), types.BoolType), + argTypes(types.BytesType, types.BytesType), types.BoolType, + decls.OverloadExamples(`b'world' > b'hello' // true`)), decls.Overload(overloads.GreaterTimestamp, - argTypes(types.TimestampType, types.TimestampType), types.BoolType), + argTypes(types.TimestampType, types.TimestampType), types.BoolType, + decls.OverloadExamples(`timestamp('2002-02-02T02:03:04Z') > timestamp('2001-01-01T02:03:04Z') // true`)), decls.Overload(overloads.GreaterDuration, - argTypes(types.DurationType, types.DurationType), types.BoolType), + argTypes(types.DurationType, types.DurationType), types.BoolType, + decls.OverloadExamples(`duration('1ms') > duration('1us') // true`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { cmp := lhs.(traits.Comparer).Compare(rhs) if cmp == types.IntOne { @@ -296,34 +435,51 @@ func init() { }, traits.ComparerType)), function(operators.GreaterEquals, + decls.FunctionDocs( + `compare two values and return true if the first value is`, + `greater than or equal to the second`), decls.Overload(overloads.GreaterEqualsBool, - argTypes(types.BoolType, types.BoolType), types.BoolType), + argTypes(types.BoolType, types.BoolType), types.BoolType, + decls.OverloadExamples(`true >= false // true`)), decls.Overload(overloads.GreaterEqualsInt64, - argTypes(types.IntType, types.IntType), types.BoolType), + argTypes(types.IntType, types.IntType), types.BoolType, + decls.OverloadExamples(`3 >= -2 // true`)), decls.Overload(overloads.GreaterEqualsInt64Double, - argTypes(types.IntType, types.DoubleType), types.BoolType), + argTypes(types.IntType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2 >= 1.1 // true`, `1 >= 1.0 // true`)), decls.Overload(overloads.GreaterEqualsInt64Uint64, - argTypes(types.IntType, types.UintType), types.BoolType), + argTypes(types.IntType, types.UintType), types.BoolType, + decls.OverloadExamples(`3 >= 2u // true`)), decls.Overload(overloads.GreaterEqualsUint64, - argTypes(types.UintType, types.UintType), types.BoolType), + argTypes(types.UintType, types.UintType), types.BoolType, + decls.OverloadExamples(`2u >= 1u // true`)), decls.Overload(overloads.GreaterEqualsUint64Double, - argTypes(types.UintType, types.DoubleType), types.BoolType), + argTypes(types.UintType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2u >= 1.9 // true`)), decls.Overload(overloads.GreaterEqualsUint64Int64, - argTypes(types.UintType, types.IntType), types.BoolType), + argTypes(types.UintType, types.IntType), types.BoolType, + decls.OverloadExamples(`23u >= 1 // true`, `1u >= 1 // true`)), decls.Overload(overloads.GreaterEqualsDouble, - argTypes(types.DoubleType, types.DoubleType), types.BoolType), + argTypes(types.DoubleType, types.DoubleType), types.BoolType, + decls.OverloadExamples(`2.4 >= 2.0 // true`)), decls.Overload(overloads.GreaterEqualsDoubleInt64, - argTypes(types.DoubleType, types.IntType), types.BoolType), + argTypes(types.DoubleType, types.IntType), types.BoolType, + decls.OverloadExamples(`3.1 >= 3 // true`)), decls.Overload(overloads.GreaterEqualsDoubleUint64, - argTypes(types.DoubleType, types.UintType), types.BoolType), + argTypes(types.DoubleType, types.UintType), types.BoolType, + decls.OverloadExamples(`2.3 >= 2u // true`)), decls.Overload(overloads.GreaterEqualsString, - argTypes(types.StringType, types.StringType), types.BoolType), + argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples(`'b' >= 'a' // true`)), decls.Overload(overloads.GreaterEqualsBytes, - argTypes(types.BytesType, types.BytesType), types.BoolType), + argTypes(types.BytesType, types.BytesType), types.BoolType, + decls.OverloadExamples(`b'world' >= b'hello' // true`)), decls.Overload(overloads.GreaterEqualsTimestamp, - argTypes(types.TimestampType, types.TimestampType), types.BoolType), + argTypes(types.TimestampType, types.TimestampType), types.BoolType, + decls.OverloadExamples(`timestamp('2001-01-01T02:03:04Z') >= timestamp('2001-01-01T02:03:04Z') // true`)), decls.Overload(overloads.GreaterEqualsDuration, - argTypes(types.DurationType, types.DurationType), types.BoolType), + argTypes(types.DurationType, types.DurationType), types.BoolType, + decls.OverloadExamples(`duration('60s') >= duration('1m') // true`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { cmp := lhs.(traits.Comparer).Compare(rhs) if cmp == types.IntOne || cmp == types.IntZero { @@ -337,16 +493,28 @@ func init() { // Indexing function(operators.Index, - decls.Overload(overloads.IndexList, argTypes(listOfA, types.IntType), paramA), - decls.Overload(overloads.IndexMap, argTypes(mapOfAB, paramA), paramB), + decls.FunctionDocs(`select a value from a list by index, or value from a map by key`), + decls.Overload(overloads.IndexList, argTypes(listOfA, types.IntType), paramA, + decls.OverloadExamples(`[1, 2, 3][1] // 2`)), + decls.Overload(overloads.IndexMap, argTypes(mapOfAB, paramA), paramB, + decls.OverloadExamples( + `{'key': 'value'}['key'] // 'value'`, + `{'key': 'value'}['missing'] // error`)), decls.SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { return lhs.(traits.Indexer).Get(rhs) }, traits.IndexerType)), // Collections operators function(operators.In, - decls.Overload(overloads.InList, argTypes(paramA, listOfA), types.BoolType), - decls.Overload(overloads.InMap, argTypes(paramA, mapOfAB), types.BoolType), + decls.FunctionDocs(`test whether a value exists in a list, or a key exists in a map`), + decls.Overload(overloads.InList, argTypes(paramA, listOfA), types.BoolType, + decls.OverloadExamples( + `2 in [1, 2, 3] // true`, + `"a" in ["b", "c"] // false`)), + decls.Overload(overloads.InMap, argTypes(paramA, mapOfAB), types.BoolType, + decls.OverloadExamples( + `'key1' in {'key1': 'value1', 'key2': 'value2'} // true`, + `3 in {1: "one", 2: "two"} // false`)), decls.SingletonBinaryBinding(inAggregate)), function(operators.OldIn, decls.DisableDeclaration(true), // safe deprecation @@ -359,209 +527,364 @@ func init() { decls.Overload(overloads.InMap, argTypes(paramA, mapOfAB), types.BoolType), decls.SingletonBinaryBinding(inAggregate)), function(overloads.Size, - decls.Overload(overloads.SizeBytes, argTypes(types.BytesType), types.IntType), - decls.MemberOverload(overloads.SizeBytesInst, argTypes(types.BytesType), types.IntType), - decls.Overload(overloads.SizeList, argTypes(listOfA), types.IntType), - decls.MemberOverload(overloads.SizeListInst, argTypes(listOfA), types.IntType), - decls.Overload(overloads.SizeMap, argTypes(mapOfAB), types.IntType), - decls.MemberOverload(overloads.SizeMapInst, argTypes(mapOfAB), types.IntType), - decls.Overload(overloads.SizeString, argTypes(types.StringType), types.IntType), - decls.MemberOverload(overloads.SizeStringInst, argTypes(types.StringType), types.IntType), + decls.FunctionDocs( + `compute the size of a list or map, the number of characters in a string,`, + `or the number of bytes in a sequence`), + decls.Overload(overloads.SizeBytes, argTypes(types.BytesType), types.IntType, + decls.OverloadExamples(`size(b'123') // 3`)), + decls.MemberOverload(overloads.SizeBytesInst, argTypes(types.BytesType), types.IntType, + decls.OverloadExamples(`b'123'.size() // 3`)), + decls.Overload(overloads.SizeList, argTypes(listOfA), types.IntType, + decls.OverloadExamples(`size([1, 2, 3]) // 3`)), + decls.MemberOverload(overloads.SizeListInst, argTypes(listOfA), types.IntType, + decls.OverloadExamples(`[1, 2, 3].size() // 3`)), + decls.Overload(overloads.SizeMap, argTypes(mapOfAB), types.IntType, + decls.OverloadExamples(`size({'a': 1, 'b': 2}) // 2`)), + decls.MemberOverload(overloads.SizeMapInst, argTypes(mapOfAB), types.IntType, + decls.OverloadExamples(`{'a': 1, 'b': 2}.size() // 2`)), + decls.Overload(overloads.SizeString, argTypes(types.StringType), types.IntType, + decls.OverloadExamples(`size('hello') // 5`)), + decls.MemberOverload(overloads.SizeStringInst, argTypes(types.StringType), types.IntType, + decls.OverloadExamples(`'hello'.size() // 5`)), decls.SingletonUnaryBinding(func(val ref.Val) ref.Val { return val.(traits.Sizer).Size() }, traits.SizerType)), // Type conversions function(overloads.TypeConvertType, - decls.Overload(overloads.TypeConvertType, argTypes(paramA), types.NewTypeTypeWithParam(paramA)), + decls.FunctionDocs(`convert a value to its type identifier`), + decls.Overload(overloads.TypeConvertType, argTypes(paramA), types.NewTypeTypeWithParam(paramA), + decls.OverloadExamples( + `type(1) // int`, + `type('hello') // string`, + `type(int) // type`, + `type(type) // type`)), decls.SingletonUnaryBinding(convertToType(types.TypeType))), // Bool conversions function(overloads.TypeConvertBool, + decls.FunctionDocs(`convert a value to a boolean`), decls.Overload(overloads.BoolToBool, argTypes(types.BoolType), types.BoolType, + + decls.OverloadExamples(`bool(true) // true`), decls.UnaryBinding(identity)), decls.Overload(overloads.StringToBool, argTypes(types.StringType), types.BoolType, + + decls.OverloadExamples(`bool('true') // true`, `bool('false') // false`), decls.UnaryBinding(convertToType(types.BoolType)))), // Bytes conversions function(overloads.TypeConvertBytes, + decls.FunctionDocs(`convert a value to bytes`), decls.Overload(overloads.BytesToBytes, argTypes(types.BytesType), types.BytesType, + decls.OverloadExamples(`bytes(b'abc') // b'abc'`), decls.UnaryBinding(identity)), decls.Overload(overloads.StringToBytes, argTypes(types.StringType), types.BytesType, + decls.OverloadExamples(`bytes('hello') // b'hello'`), decls.UnaryBinding(convertToType(types.BytesType)))), // Double conversions function(overloads.TypeConvertDouble, + decls.FunctionDocs(`convert a value to a double`), decls.Overload(overloads.DoubleToDouble, argTypes(types.DoubleType), types.DoubleType, + decls.OverloadExamples(`double(1.23) // 1.23`), decls.UnaryBinding(identity)), decls.Overload(overloads.IntToDouble, argTypes(types.IntType), types.DoubleType, + decls.OverloadExamples(`double(123) // 123.0`), decls.UnaryBinding(convertToType(types.DoubleType))), decls.Overload(overloads.StringToDouble, argTypes(types.StringType), types.DoubleType, + decls.OverloadExamples(`double('1.23') // 1.23`), decls.UnaryBinding(convertToType(types.DoubleType))), decls.Overload(overloads.UintToDouble, argTypes(types.UintType), types.DoubleType, + decls.OverloadExamples(`double(123u) // 123.0`), decls.UnaryBinding(convertToType(types.DoubleType)))), // Duration conversions function(overloads.TypeConvertDuration, + decls.FunctionDocs(`convert a value to a google.protobuf.Duration`), decls.Overload(overloads.DurationToDuration, argTypes(types.DurationType), types.DurationType, + decls.OverloadExamples(`duration(duration('1s')) // duration('1s')`), decls.UnaryBinding(identity)), decls.Overload(overloads.IntToDuration, argTypes(types.IntType), types.DurationType, decls.UnaryBinding(convertToType(types.DurationType))), decls.Overload(overloads.StringToDuration, argTypes(types.StringType), types.DurationType, + decls.OverloadExamples(`duration('1h2m3s') // duration('3723s')`), decls.UnaryBinding(convertToType(types.DurationType)))), // Dyn conversions function(overloads.TypeConvertDyn, - decls.Overload(overloads.ToDyn, argTypes(paramA), types.DynType), + decls.FunctionDocs(`indicate that the type is dynamic for type-checking purposes`), + decls.Overload(overloads.ToDyn, argTypes(paramA), types.DynType, + decls.OverloadExamples(`dyn(1) // 1`)), decls.SingletonUnaryBinding(identity)), // Int conversions function(overloads.TypeConvertInt, + decls.FunctionDocs(`convert a value to an int`), decls.Overload(overloads.IntToInt, argTypes(types.IntType), types.IntType, + decls.OverloadExamples(`int(123) // 123`), decls.UnaryBinding(identity)), decls.Overload(overloads.DoubleToInt, argTypes(types.DoubleType), types.IntType, + decls.OverloadExamples(`int(123.45) // 123`), decls.UnaryBinding(convertToType(types.IntType))), decls.Overload(overloads.DurationToInt, argTypes(types.DurationType), types.IntType, - decls.UnaryBinding(convertToType(types.IntType))), + decls.OverloadExamples(`int(duration('1s')) // 1000000000`), + decls.UnaryBinding(convertToType(types.IntType))), // Duration to nanoseconds decls.Overload(overloads.StringToInt, argTypes(types.StringType), types.IntType, + decls.OverloadExamples(`int('123') // 123`, `int('-456') // -456`), decls.UnaryBinding(convertToType(types.IntType))), decls.Overload(overloads.TimestampToInt, argTypes(types.TimestampType), types.IntType, - decls.UnaryBinding(convertToType(types.IntType))), + decls.OverloadExamples(`int(timestamp('1970-01-01T00:00:01Z')) // 1`), + decls.UnaryBinding(convertToType(types.IntType))), // Timestamp to epoch seconds decls.Overload(overloads.UintToInt, argTypes(types.UintType), types.IntType, - decls.UnaryBinding(convertToType(types.IntType))), - ), + decls.OverloadExamples(`int(123u) // 123`), + decls.UnaryBinding(convertToType(types.IntType)))), // String conversions function(overloads.TypeConvertString, + decls.FunctionDocs(`convert a value to a string`), decls.Overload(overloads.StringToString, argTypes(types.StringType), types.StringType, + decls.OverloadExamples(`string('hello') // 'hello'`), decls.UnaryBinding(identity)), decls.Overload(overloads.BoolToString, argTypes(types.BoolType), types.StringType, + decls.OverloadExamples(`string(true) // 'true'`), decls.UnaryBinding(convertToType(types.StringType))), decls.Overload(overloads.BytesToString, argTypes(types.BytesType), types.StringType, + decls.OverloadExamples(`string(b'hello') // 'hello'`), decls.UnaryBinding(convertToType(types.StringType))), decls.Overload(overloads.DoubleToString, argTypes(types.DoubleType), types.StringType, - decls.UnaryBinding(convertToType(types.StringType))), + decls.UnaryBinding(convertToType(types.StringType)), + decls.OverloadExamples(`string(-1.23e4) // '-12300'`)), decls.Overload(overloads.DurationToString, argTypes(types.DurationType), types.StringType, + decls.OverloadExamples(`string(duration('1h30m')) // '5400s'`), decls.UnaryBinding(convertToType(types.StringType))), decls.Overload(overloads.IntToString, argTypes(types.IntType), types.StringType, + decls.OverloadExamples(`string(-123) // '-123'`), decls.UnaryBinding(convertToType(types.StringType))), decls.Overload(overloads.TimestampToString, argTypes(types.TimestampType), types.StringType, + decls.OverloadExamples(`string(timestamp('1970-01-01T00:00:00Z')) // '1970-01-01T00:00:00Z'`), decls.UnaryBinding(convertToType(types.StringType))), decls.Overload(overloads.UintToString, argTypes(types.UintType), types.StringType, + decls.OverloadExamples(`string(123u) // '123'`), decls.UnaryBinding(convertToType(types.StringType)))), // Timestamp conversions function(overloads.TypeConvertTimestamp, + decls.FunctionDocs(`convert a value to a google.protobuf.Timestamp`), decls.Overload(overloads.TimestampToTimestamp, argTypes(types.TimestampType), types.TimestampType, + decls.OverloadExamples(`timestamp(timestamp('2023-01-01T00:00:00Z')) // timestamp('2023-01-01T00:00:00Z')`), decls.UnaryBinding(identity)), decls.Overload(overloads.IntToTimestamp, argTypes(types.IntType), types.TimestampType, + decls.OverloadExamples(`timestamp(1) // timestamp('1970-01-01T00:00:01Z')`), // Epoch seconds to Timestamp decls.UnaryBinding(convertToType(types.TimestampType))), decls.Overload(overloads.StringToTimestamp, argTypes(types.StringType), types.TimestampType, + decls.OverloadExamples(`timestamp('2025-01-01T12:34:56Z') // timestamp('2025-01-01T12:34:56Z')`), decls.UnaryBinding(convertToType(types.TimestampType)))), // Uint conversions function(overloads.TypeConvertUint, + decls.FunctionDocs(`convert a value to a uint`), decls.Overload(overloads.UintToUint, argTypes(types.UintType), types.UintType, + decls.OverloadExamples(`uint(123u) // 123u`), decls.UnaryBinding(identity)), decls.Overload(overloads.DoubleToUint, argTypes(types.DoubleType), types.UintType, + decls.OverloadExamples(`uint(123.45) // 123u`), decls.UnaryBinding(convertToType(types.UintType))), decls.Overload(overloads.IntToUint, argTypes(types.IntType), types.UintType, + decls.OverloadExamples(`uint(123) // 123u`), decls.UnaryBinding(convertToType(types.UintType))), decls.Overload(overloads.StringToUint, argTypes(types.StringType), types.UintType, + decls.OverloadExamples(`uint('123') // 123u`), decls.UnaryBinding(convertToType(types.UintType)))), // String functions function(overloads.Contains, + decls.FunctionDocs(`test whether a string contains a substring`), decls.MemberOverload(overloads.ContainsString, argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples( + `'hello world'.contains('o w') // true`, + `'hello world'.contains('goodbye') // false`), decls.BinaryBinding(types.StringContains)), decls.DisableTypeGuards(true)), function(overloads.EndsWith, + decls.FunctionDocs(`test whether a string ends with a substring suffix`), decls.MemberOverload(overloads.EndsWithString, argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples( + `'hello world'.endsWith('world') // true`, + `'hello world'.endsWith('hello') // false`), decls.BinaryBinding(types.StringEndsWith)), decls.DisableTypeGuards(true)), function(overloads.StartsWith, + decls.FunctionDocs(`test whether a string starts with a substring prefix`), decls.MemberOverload(overloads.StartsWithString, argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples( + `'hello world'.startsWith('hello') // true`, + `'hello world'.startsWith('world') // false`), decls.BinaryBinding(types.StringStartsWith)), decls.DisableTypeGuards(true)), function(overloads.Matches, - decls.Overload(overloads.Matches, argTypes(types.StringType, types.StringType), types.BoolType), + decls.FunctionDocs(`test whether a string matches an RE2 regular expression`), + decls.Overload(overloads.Matches, argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples( + `matches('123-456', '^[0-9]+(-[0-9]+)?$') // true`, + `matches('hello', '^h.*o$') // true`)), decls.MemberOverload(overloads.MatchesString, - argTypes(types.StringType, types.StringType), types.BoolType), + argTypes(types.StringType, types.StringType), types.BoolType, + decls.OverloadExamples( + `'123-456'.matches('^[0-9]+(-[0-9]+)?$') // true`, + `'hello'.matches('^h.*o$') // true`)), decls.SingletonBinaryBinding(func(str, pat ref.Val) ref.Val { return str.(traits.Matcher).Match(pat) }, traits.MatcherType)), // Timestamp / duration functions function(overloads.TimeGetFullYear, + decls.FunctionDocs(`get the 0-based full year from a timestamp, UTC unless an IANA timezone is specified.`), decls.MemberOverload(overloads.TimestampToYear, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getFullYear() // 2023`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetFullYear(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToYearWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType)), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-01-01T05:30:00Z').getFullYear('-08:00') // 2022`), + decls.BinaryBinding(timestampGetFullYear))), function(overloads.TimeGetMonth, + decls.FunctionDocs(`get the 0-based month from a timestamp, UTC unless an IANA timezone is specified.`), decls.MemberOverload(overloads.TimestampToMonth, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getMonth() // 6`), // July is month 6 + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetMonth(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToMonthWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType)), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-01-01T05:30:00Z').getMonth('America/Los_Angeles') // 11`), // December is month 11 + decls.BinaryBinding(timestampGetMonth))), function(overloads.TimeGetDayOfYear, + decls.FunctionDocs(`get the 0-based day of the year from a timestamp, UTC unless an IANA timezone is specified.`), decls.MemberOverload(overloads.TimestampToDayOfYear, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-01-02T00:00:00Z').getDayOfYear() // 1`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetDayOfYear(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToDayOfYearWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType)), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-01-01T05:00:00Z').getDayOfYear('America/Los_Angeles') // 364`), + decls.BinaryBinding(timestampGetDayOfYear))), function(overloads.TimeGetDayOfMonth, + decls.FunctionDocs(`get the 0-based day of the month from a timestamp, UTC unless an IANA timezone is specified.`), decls.MemberOverload(overloads.TimestampToDayOfMonthZeroBased, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getDayOfMonth() // 13`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetDayOfMonthZeroBased(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToDayOfMonthZeroBasedWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType)), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-01T05:00:00Z').getDayOfMonth('America/Los_Angeles') // 29`), + decls.BinaryBinding(timestampGetDayOfMonthZeroBased))), function(overloads.TimeGetDate, + decls.FunctionDocs(`get the 1-based day of the month from a timestamp, UTC unless an IANA timezone is specified.`), decls.MemberOverload(overloads.TimestampToDayOfMonthOneBased, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getDate() // 14`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetDayOfMonthOneBased(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToDayOfMonthOneBasedWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType)), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-01T05:00:00Z').getDate('America/Los_Angeles') // 30`), + decls.BinaryBinding(timestampGetDayOfMonthOneBased))), function(overloads.TimeGetDayOfWeek, + decls.FunctionDocs(`get the 0-based day of the week from a timestamp, UTC unless an IANA timezone is specified.`), decls.MemberOverload(overloads.TimestampToDayOfWeek, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getDayOfWeek() // 5`), // Friday is day 5 + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetDayOfWeek(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToDayOfWeekWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType)), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-16T05:00:00Z').getDayOfWeek('America/Los_Angeles') // 6`), // Saturday is day 6 + decls.BinaryBinding(timestampGetDayOfWeek))), function(overloads.TimeGetHours, + decls.FunctionDocs(`get the hours portion from a timestamp, or convert a duration to hours`), decls.MemberOverload(overloads.TimestampToHours, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getHours() // 10`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetHours(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToHoursWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getHours('America/Los_Angeles') // 2`), + decls.BinaryBinding(timestampGetHours)), decls.MemberOverload(overloads.DurationToHours, - argTypes(types.DurationType), types.IntType)), + argTypes(types.DurationType), types.IntType, + decls.OverloadExamples(`duration('3723s').getHours() // 1`), + decls.UnaryBinding(types.DurationGetHours))), function(overloads.TimeGetMinutes, + decls.FunctionDocs(`get the minutes portion from a timestamp, or convert a duration to minutes`), decls.MemberOverload(overloads.TimestampToMinutes, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getMinutes() // 30`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetMinutes(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToMinutesWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getMinutes('America/Los_Angeles') // 30`), + decls.BinaryBinding(timestampGetMinutes)), decls.MemberOverload(overloads.DurationToMinutes, - argTypes(types.DurationType), types.IntType)), + argTypes(types.DurationType), types.IntType, + decls.OverloadExamples(`duration('3723s').getMinutes() // 62`), + decls.UnaryBinding(types.DurationGetMinutes))), function(overloads.TimeGetSeconds, + decls.FunctionDocs(`get the seconds portion from a timestamp, or convert a duration to seconds`), decls.MemberOverload(overloads.TimestampToSeconds, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getSeconds() // 45`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetSeconds(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToSecondsWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getSeconds('America/Los_Angeles') // 45`), + decls.BinaryBinding(timestampGetSeconds)), decls.MemberOverload(overloads.DurationToSeconds, - argTypes(types.DurationType), types.IntType)), + argTypes(types.DurationType), types.IntType, + decls.OverloadExamples(`duration('3723.456s').getSeconds() // 3723`), + decls.UnaryBinding(types.DurationGetSeconds))), function(overloads.TimeGetMilliseconds, + decls.FunctionDocs(`get the milliseconds portion from a timestamp`), decls.MemberOverload(overloads.TimestampToMilliseconds, - argTypes(types.TimestampType), types.IntType), + argTypes(types.TimestampType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getMilliseconds() // 123`), + decls.UnaryBinding(func(ts ref.Val) ref.Val { + return timestampGetMilliseconds(ts, utcTZ) + })), decls.MemberOverload(overloads.TimestampToMillisecondsWithTz, - argTypes(types.TimestampType, types.StringType), types.IntType), + argTypes(types.TimestampType, types.StringType), types.IntType, + decls.OverloadExamples(`timestamp('2023-07-14T10:30:45.123Z').getMilliseconds('America/Los_Angeles') // 123`), + decls.BinaryBinding(timestampGetMilliseconds)), decls.MemberOverload(overloads.DurationToMilliseconds, - argTypes(types.DurationType), types.IntType)), + argTypes(types.DurationType), types.IntType, + decls.UnaryBinding(types.DurationGetMilliseconds))), } } @@ -618,3 +941,118 @@ func convertToType(t ref.Type) functions.UnaryOp { return val.ConvertToType(t) } } + +func timestampGetFullYear(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Year()) +} + +func timestampGetMonth(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + // CEL spec indicates that the month should be 0-based, but the Time value + // for Month() is 1-based. + return types.Int(t.Month() - 1) +} + +func timestampGetDayOfYear(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.YearDay() - 1) +} + +func timestampGetDayOfMonthZeroBased(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Day() - 1) +} + +func timestampGetDayOfMonthOneBased(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Day()) +} + +func timestampGetDayOfWeek(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Weekday()) +} + +func timestampGetHours(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Hour()) +} + +func timestampGetMinutes(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Minute()) +} + +func timestampGetSeconds(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Second()) +} + +func timestampGetMilliseconds(ts, tz ref.Val) ref.Val { + t, err := inTimeZone(ts, tz) + if err != nil { + return types.NewErrFromString(err.Error()) + } + return types.Int(t.Nanosecond() / 1000000) +} + +func inTimeZone(ts, tz ref.Val) (time.Time, error) { + t := ts.(types.Timestamp) + val := string(tz.(types.String)) + ind := strings.Index(val, ":") + if ind == -1 { + loc, err := time.LoadLocation(val) + if err != nil { + return time.Time{}, err + } + return t.In(loc), nil + } + + // If the input is not the name of a timezone (for example, 'US/Central'), it should be a numerical offset from UTC + // in the format ^(+|-)(0[0-9]|1[0-4]):[0-5][0-9]$. The numerical input is parsed in terms of hours and minutes. + hr, err := strconv.Atoi(string(val[0:ind])) + if err != nil { + return time.Time{}, err + } + min, err := strconv.Atoi(string(val[ind+1:])) + if err != nil { + return time.Time{}, err + } + var offset int + if string(val[0]) == "-" { + offset = hr*60 - min + } else { + offset = hr*60 + min + } + secondsEastOfUTC := int((time.Duration(offset) * time.Minute).Seconds()) + timezone := time.FixedZone("", secondsEastOfUTC) + return t.In(timezone), nil +} diff --git a/vendor/github.com/google/cel-go/common/types/BUILD.bazel b/vendor/github.com/google/cel-go/common/types/BUILD.bazel index 8f010fae..7082bc75 100644 --- a/vendor/github.com/google/cel-go/common/types/BUILD.bazel +++ b/vendor/github.com/google/cel-go/common/types/BUILD.bazel @@ -18,6 +18,7 @@ go_library( "int.go", "iterator.go", "json_value.go", + "format.go", "list.go", "map.go", "null.go", diff --git a/vendor/github.com/google/cel-go/common/types/bool.go b/vendor/github.com/google/cel-go/common/types/bool.go index 565734f3..1f9e1073 100644 --- a/vendor/github.com/google/cel-go/common/types/bool.go +++ b/vendor/github.com/google/cel-go/common/types/bool.go @@ -18,6 +18,7 @@ import ( "fmt" "reflect" "strconv" + "strings" "github.com/google/cel-go/common/types/ref" @@ -128,6 +129,14 @@ func (b Bool) Value() any { return bool(b) } +func (b Bool) format(sb *strings.Builder) { + if b { + sb.WriteString("true") + } else { + sb.WriteString("false") + } +} + // IsBool returns whether the input ref.Val or ref.Type is equal to BoolType. func IsBool(elem ref.Val) bool { switch v := elem.(type) { diff --git a/vendor/github.com/google/cel-go/common/types/bytes.go b/vendor/github.com/google/cel-go/common/types/bytes.go index 7e813e29..b59e1fc2 100644 --- a/vendor/github.com/google/cel-go/common/types/bytes.go +++ b/vendor/github.com/google/cel-go/common/types/bytes.go @@ -19,6 +19,7 @@ import ( "encoding/base64" "fmt" "reflect" + "strings" "unicode/utf8" "github.com/google/cel-go/common/types/ref" @@ -138,3 +139,17 @@ func (b Bytes) Type() ref.Type { func (b Bytes) Value() any { return []byte(b) } + +func (b Bytes) format(sb *strings.Builder) { + fmt.Fprintf(sb, "b\"%s\"", bytesToOctets([]byte(b))) +} + +// bytesToOctets converts byte sequences to a string using a three digit octal encoded value +// per byte. +func bytesToOctets(byteVal []byte) string { + var b strings.Builder + for _, c := range byteVal { + fmt.Fprintf(&b, "\\%03o", c) + } + return b.String() +} diff --git a/vendor/github.com/google/cel-go/common/types/double.go b/vendor/github.com/google/cel-go/common/types/double.go index 027e7897..1e7de9d6 100644 --- a/vendor/github.com/google/cel-go/common/types/double.go +++ b/vendor/github.com/google/cel-go/common/types/double.go @@ -18,6 +18,8 @@ import ( "fmt" "math" "reflect" + "strconv" + "strings" "github.com/google/cel-go/common/types/ref" @@ -209,3 +211,23 @@ func (d Double) Type() ref.Type { func (d Double) Value() any { return float64(d) } + +func (d Double) format(sb *strings.Builder) { + if math.IsNaN(float64(d)) { + sb.WriteString(`double("NaN")`) + return + } + if math.IsInf(float64(d), -1) { + sb.WriteString(`double("-Infinity")`) + return + } + if math.IsInf(float64(d), 1) { + sb.WriteString(`double("Infinity")`) + return + } + s := strconv.FormatFloat(float64(d), 'f', -1, 64) + sb.WriteString(s) + if !strings.ContainsRune(s, '.') { + sb.WriteString(".0") + } +} diff --git a/vendor/github.com/google/cel-go/common/types/duration.go b/vendor/github.com/google/cel-go/common/types/duration.go index 596e56d6..be58d567 100644 --- a/vendor/github.com/google/cel-go/common/types/duration.go +++ b/vendor/github.com/google/cel-go/common/types/duration.go @@ -18,6 +18,7 @@ import ( "fmt" "reflect" "strconv" + "strings" "time" "github.com/google/cel-go/common/overloads" @@ -185,6 +186,10 @@ func (d Duration) Value() any { return d.Duration } +func (d Duration) format(sb *strings.Builder) { + fmt.Fprintf(sb, `duration("%ss")`, strconv.FormatFloat(d.Seconds(), 'f', -1, 64)) +} + // DurationGetHours returns the duration in hours. func DurationGetHours(val ref.Val) ref.Val { dur, ok := val.(Duration) diff --git a/vendor/github.com/google/cel-go/common/types/format.go b/vendor/github.com/google/cel-go/common/types/format.go new file mode 100644 index 00000000..174a2bd0 --- /dev/null +++ b/vendor/github.com/google/cel-go/common/types/format.go @@ -0,0 +1,42 @@ +package types + +import ( + "fmt" + "strings" + + "github.com/google/cel-go/common/types/ref" + "github.com/google/cel-go/common/types/traits" +) + +type formattable interface { + format(*strings.Builder) +} + +// Format formats the value as a string. The result is only intended for human consumption and ignores errors. +// Do not depend on the output being stable. It may change at any time. +func Format(val ref.Val) string { + var sb strings.Builder + formatTo(&sb, val) + return sb.String() +} + +func formatTo(sb *strings.Builder, val ref.Val) { + if fmtable, ok := val.(formattable); ok { + fmtable.format(sb) + return + } + // All of the builtins implement formattable. Try to deal with traits. + if l, ok := val.(traits.Lister); ok { + formatList(l, sb) + return + } + if m, ok := val.(traits.Mapper); ok { + formatMap(m, sb) + return + } + // This could be an error, unknown, opaque or object. + // Unfortunately we have no consistent way of inspecting + // opaque and object. So we just fallback to fmt.Stringer + // and hope it is relavent. + fmt.Fprintf(sb, "%s", val) +} diff --git a/vendor/github.com/google/cel-go/common/types/int.go b/vendor/github.com/google/cel-go/common/types/int.go index 0ae9507c..0ac1997b 100644 --- a/vendor/github.com/google/cel-go/common/types/int.go +++ b/vendor/github.com/google/cel-go/common/types/int.go @@ -19,6 +19,7 @@ import ( "math" "reflect" "strconv" + "strings" "time" "github.com/google/cel-go/common/types/ref" @@ -290,6 +291,10 @@ func (i Int) Value() any { return int64(i) } +func (i Int) format(sb *strings.Builder) { + sb.WriteString(strconv.FormatInt(int64(i), 10)) +} + // isJSONSafe indicates whether the int is safely representable as a floating point value in JSON. func (i Int) isJSONSafe() bool { return i >= minIntJSON && i <= maxIntJSON diff --git a/vendor/github.com/google/cel-go/common/types/list.go b/vendor/github.com/google/cel-go/common/types/list.go index 7e68a5da..8c023f89 100644 --- a/vendor/github.com/google/cel-go/common/types/list.go +++ b/vendor/github.com/google/cel-go/common/types/list.go @@ -299,6 +299,22 @@ func (l *baseList) String() string { return sb.String() } +func formatList(l traits.Lister, sb *strings.Builder) { + sb.WriteString("[") + n, _ := l.Size().(Int) + for i := 0; i < int(n); i++ { + formatTo(sb, l.Get(Int(i))) + if i != int(n)-1 { + sb.WriteString(", ") + } + } + sb.WriteString("]") +} + +func (l *baseList) format(sb *strings.Builder) { + formatList(l, sb) +} + // mutableList aggregates values into its internal storage. For use with internal CEL variables only. type mutableList struct { *baseList diff --git a/vendor/github.com/google/cel-go/common/types/map.go b/vendor/github.com/google/cel-go/common/types/map.go index cb6cce78..b3309619 100644 --- a/vendor/github.com/google/cel-go/common/types/map.go +++ b/vendor/github.com/google/cel-go/common/types/map.go @@ -17,6 +17,7 @@ package types import ( "fmt" "reflect" + "sort" "strings" "github.com/stoewer/go-strcase" @@ -318,6 +319,41 @@ func (m *baseMap) String() string { return sb.String() } +type baseMapEntry struct { + key string + val string +} + +func formatMap(m traits.Mapper, sb *strings.Builder) { + it := m.Iterator() + var ents []baseMapEntry + if s, ok := m.Size().(Int); ok { + ents = make([]baseMapEntry, 0, int(s)) + } + for it.HasNext() == True { + k := it.Next() + v, _ := m.Find(k) + ents = append(ents, baseMapEntry{Format(k), Format(v)}) + } + sort.SliceStable(ents, func(i, j int) bool { + return ents[i].key < ents[j].key + }) + sb.WriteString("{") + for i, ent := range ents { + if i > 0 { + sb.WriteString(", ") + } + sb.WriteString(ent.key) + sb.WriteString(": ") + sb.WriteString(ent.val) + } + sb.WriteString("}") +} + +func (m *baseMap) format(sb *strings.Builder) { + formatMap(m, sb) +} + // Type implements the ref.Val interface method. func (m *baseMap) Type() ref.Type { return MapType diff --git a/vendor/github.com/google/cel-go/common/types/null.go b/vendor/github.com/google/cel-go/common/types/null.go index 36514ff2..2c0297fe 100644 --- a/vendor/github.com/google/cel-go/common/types/null.go +++ b/vendor/github.com/google/cel-go/common/types/null.go @@ -17,6 +17,7 @@ package types import ( "fmt" "reflect" + "strings" "google.golang.org/protobuf/proto" @@ -117,3 +118,7 @@ func (n Null) Type() ref.Type { func (n Null) Value() any { return structpb.NullValue_NULL_VALUE } + +func (n Null) format(sb *strings.Builder) { + sb.WriteString("null") +} diff --git a/vendor/github.com/google/cel-go/common/types/object.go b/vendor/github.com/google/cel-go/common/types/object.go index 5377bff8..776f6954 100644 --- a/vendor/github.com/google/cel-go/common/types/object.go +++ b/vendor/github.com/google/cel-go/common/types/object.go @@ -17,9 +17,12 @@ package types import ( "fmt" "reflect" + "sort" + "strings" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" "github.com/google/cel-go/common/types/pb" "github.com/google/cel-go/common/types/ref" @@ -163,3 +166,29 @@ func (o *protoObj) Type() ref.Type { func (o *protoObj) Value() any { return o.value } + +type protoObjField struct { + fd protoreflect.FieldDescriptor + v protoreflect.Value +} + +func (o *protoObj) format(sb *strings.Builder) { + var fields []protoreflect.FieldDescriptor + o.value.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + fields = append(fields, fd) + return true + }) + sort.SliceStable(fields, func(i, j int) bool { + return fields[i].Number() < fields[j].Number() + }) + sb.WriteString(o.Type().TypeName()) + sb.WriteString("{") + for i, field := range fields { + if i > 0 { + sb.WriteString(", ") + } + sb.WriteString(fmt.Sprintf("%s: ", field.Name())) + formatTo(sb, o.Get(String(field.Name()))) + } + sb.WriteString("}") +} diff --git a/vendor/github.com/google/cel-go/common/types/optional.go b/vendor/github.com/google/cel-go/common/types/optional.go index 97845a74..b8685ebf 100644 --- a/vendor/github.com/google/cel-go/common/types/optional.go +++ b/vendor/github.com/google/cel-go/common/types/optional.go @@ -18,6 +18,7 @@ import ( "errors" "fmt" "reflect" + "strings" "github.com/google/cel-go/common/types/ref" ) @@ -94,6 +95,16 @@ func (o *Optional) String() string { return "optional.none()" } +func (o *Optional) format(sb *strings.Builder) { + if o.HasValue() { + sb.WriteString(`optional.of(`) + formatTo(sb, o.GetValue()) + sb.WriteString(`)`) + } else { + sb.WriteString("optional.none()") + } +} + // Type implements the ref.Val interface method. func (o *Optional) Type() ref.Type { return OptionalType diff --git a/vendor/github.com/google/cel-go/common/types/string.go b/vendor/github.com/google/cel-go/common/types/string.go index 3a93743f..8aad4701 100644 --- a/vendor/github.com/google/cel-go/common/types/string.go +++ b/vendor/github.com/google/cel-go/common/types/string.go @@ -186,6 +186,10 @@ func (s String) Value() any { return string(s) } +func (s String) format(sb *strings.Builder) { + sb.WriteString(strconv.Quote(string(s))) +} + // StringContains returns whether the string contains a substring. func StringContains(s, sub ref.Val) ref.Val { str, ok := s.(String) diff --git a/vendor/github.com/google/cel-go/common/types/timestamp.go b/vendor/github.com/google/cel-go/common/types/timestamp.go index 33acdea8..f7be5859 100644 --- a/vendor/github.com/google/cel-go/common/types/timestamp.go +++ b/vendor/github.com/google/cel-go/common/types/timestamp.go @@ -179,6 +179,10 @@ func (t Timestamp) Value() any { return t.Time } +func (t Timestamp) format(sb *strings.Builder) { + fmt.Fprintf(sb, `timestamp("%s")`, t.Time.UTC().Format(time.RFC3339Nano)) +} + var ( timestampValueType = reflect.TypeOf(&tpb.Timestamp{}) diff --git a/vendor/github.com/google/cel-go/common/types/types.go b/vendor/github.com/google/cel-go/common/types/types.go index f419beab..78c77a9b 100644 --- a/vendor/github.com/google/cel-go/common/types/types.go +++ b/vendor/github.com/google/cel-go/common/types/types.go @@ -164,9 +164,9 @@ var ( traits.SubtractorType, } // ListType represents the runtime list type. - ListType = NewListType(nil) + ListType = NewListType(DynType) // MapType represents the runtime map type. - MapType = NewMapType(nil, nil) + MapType = NewMapType(DynType, DynType) // NullType represents the type of a null value. NullType = &Type{ kind: NullTypeKind, @@ -376,6 +376,10 @@ func (t *Type) TypeName() string { return t.runtimeTypeName } +func (t *Type) format(sb *strings.Builder) { + sb.WriteString(t.TypeName()) +} + // WithTraits creates a copy of the current Type and sets the trait mask to the traits parameter. // // This method should be used with Opaque types where the type acts like a container, e.g. vector. @@ -395,6 +399,9 @@ func (t *Type) WithTraits(traits int) *Type { // String returns a human-readable definition of the type name. func (t *Type) String() string { + if t.Kind() == TypeParamKind { + return fmt.Sprintf("<%s>", t.DeclaredTypeName()) + } if len(t.Parameters()) == 0 { return t.DeclaredTypeName() } diff --git a/vendor/github.com/google/cel-go/common/types/uint.go b/vendor/github.com/google/cel-go/common/types/uint.go index 6d74f30d..a93405a1 100644 --- a/vendor/github.com/google/cel-go/common/types/uint.go +++ b/vendor/github.com/google/cel-go/common/types/uint.go @@ -19,6 +19,7 @@ import ( "math" "reflect" "strconv" + "strings" "github.com/google/cel-go/common/types/ref" @@ -250,6 +251,11 @@ func (i Uint) Value() any { return uint64(i) } +func (i Uint) format(sb *strings.Builder) { + sb.WriteString(strconv.FormatUint(uint64(i), 10)) + sb.WriteString("u") +} + // isJSONSafe indicates whether the uint is safely representable as a floating point value in JSON. func (i Uint) isJSONSafe() bool { return i <= maxIntJSON diff --git a/vendor/github.com/google/cel-go/interpreter/activation.go b/vendor/github.com/google/cel-go/interpreter/activation.go index c20d19de..dd40619e 100644 --- a/vendor/github.com/google/cel-go/interpreter/activation.go +++ b/vendor/github.com/google/cel-go/interpreter/activation.go @@ -158,7 +158,8 @@ type PartialActivation interface { // partialActivationConverter indicates whether an Activation implementation supports conversion to a PartialActivation type partialActivationConverter interface { - asPartialActivation() (PartialActivation, bool) + // AsPartialActivation converts the current activation to a PartialActivation + AsPartialActivation() (PartialActivation, bool) } // partActivation is the default implementations of the PartialActivation interface. @@ -172,19 +173,20 @@ func (a *partActivation) UnknownAttributePatterns() []*AttributePattern { return a.unknowns } -// asPartialActivation returns the partActivation as a PartialActivation interface. -func (a *partActivation) asPartialActivation() (PartialActivation, bool) { +// AsPartialActivation returns the partActivation as a PartialActivation interface. +func (a *partActivation) AsPartialActivation() (PartialActivation, bool) { return a, true } -func asPartialActivation(vars Activation) (PartialActivation, bool) { +// AsPartialActivation walks the activation hierarchy and returns the first PartialActivation, if found. +func AsPartialActivation(vars Activation) (PartialActivation, bool) { // Only internal activation instances may implement this interface if pv, ok := vars.(partialActivationConverter); ok { - return pv.asPartialActivation() + return pv.AsPartialActivation() } // Since Activations may be hierarchical, test whether a parent converts to a PartialActivation if vars.Parent() != nil { - return asPartialActivation(vars.Parent()) + return AsPartialActivation(vars.Parent()) } return nil, false } diff --git a/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go b/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go index 7e5c2db0..7d0759e3 100644 --- a/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go +++ b/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go @@ -358,7 +358,7 @@ func (m *attributeMatcher) AddQualifier(qual Qualifier) (Attribute, error) { func (m *attributeMatcher) Resolve(vars Activation) (any, error) { id := m.NamespacedAttribute.ID() // Bug in how partial activation is resolved, should search parents as well. - partial, isPartial := asPartialActivation(vars) + partial, isPartial := AsPartialActivation(vars) if isPartial { unk, err := m.fac.matchesUnknownPatterns( partial, diff --git a/vendor/github.com/google/cel-go/interpreter/interpretable.go b/vendor/github.com/google/cel-go/interpreter/interpretable.go index 591b7688..96b5a8ff 100644 --- a/vendor/github.com/google/cel-go/interpreter/interpretable.go +++ b/vendor/github.com/google/cel-go/interpreter/interpretable.go @@ -109,6 +109,47 @@ type InterpretableConstructor interface { Type() ref.Type } +// ObservableInterpretable is an Interpretable which supports stateful observation, such as tracing +// or cost-tracking. +type ObservableInterpretable struct { + Interpretable + observers []StatefulObserver +} + +// ID implements the Interpretable method to get the expression id associated with the step. +func (oi *ObservableInterpretable) ID() int64 { + return oi.Interpretable.ID() +} + +// Eval proxies to the ObserveEval method while invoking a no-op callback to report the observations. +func (oi *ObservableInterpretable) Eval(vars Activation) ref.Val { + return oi.ObserveEval(vars, func(any) {}) +} + +// ObserveEval evaluates an interpretable and performs per-evaluation state-tracking. +// +// This method is concurrency safe and the expectation is that the observer function will use +// a switch statement to determine the type of the state which has been reported back from the call. +func (oi *ObservableInterpretable) ObserveEval(vars Activation, observer func(any)) ref.Val { + var err error + // Initialize the state needed for the observers to function. + for _, obs := range oi.observers { + vars, err = obs.InitState(vars) + if err != nil { + return types.WrapErr(err) + } + // Provide an initial reference to the state to ensure state is available + // even in cases of interrupting errors generated during evaluation. + observer(obs.GetState(vars)) + } + result := oi.Interpretable.Eval(vars) + // Get the state which needs to be reported back as having been observed. + for _, obs := range oi.observers { + observer(obs.GetState(vars)) + } + return result +} + // Core Interpretable implementations used during the program planning phase. type evalTestOnly struct { @@ -156,9 +197,6 @@ func (q *testOnlyQualifier) Qualify(vars Activation, obj any) (any, error) { if unk, isUnk := out.(types.Unknown); isUnk { return unk, nil } - if opt, isOpt := out.(types.Optional); isOpt { - return opt.HasValue(), nil - } return present, nil } @@ -822,9 +860,9 @@ type evalWatch struct { } // Eval implements the Interpretable interface method. -func (e *evalWatch) Eval(ctx Activation) ref.Val { - val := e.Interpretable.Eval(ctx) - e.observer(e.ID(), e.Interpretable, val) +func (e *evalWatch) Eval(vars Activation) ref.Val { + val := e.Interpretable.Eval(vars) + e.observer(vars, e.ID(), e.Interpretable, val) return val } @@ -883,7 +921,7 @@ func (e *evalWatchAttr) AddQualifier(q Qualifier) (Attribute, error) { // Eval implements the Interpretable interface method. func (e *evalWatchAttr) Eval(vars Activation) ref.Val { val := e.InterpretableAttribute.Eval(vars) - e.observer(e.ID(), e.InterpretableAttribute, val) + e.observer(vars, e.ID(), e.InterpretableAttribute, val) return val } @@ -904,7 +942,7 @@ func (e *evalWatchConstQual) Qualify(vars Activation, obj any) (any, error) { } else { val = e.adapter.NativeToValue(out) } - e.observer(e.ID(), e.ConstantQualifier, val) + e.observer(vars, e.ID(), e.ConstantQualifier, val) return out, err } @@ -920,7 +958,7 @@ func (e *evalWatchConstQual) QualifyIfPresent(vars Activation, obj any, presence val = types.Bool(present) } if present || presenceOnly { - e.observer(e.ID(), e.ConstantQualifier, val) + e.observer(vars, e.ID(), e.ConstantQualifier, val) } return out, present, err } @@ -947,7 +985,7 @@ func (e *evalWatchAttrQual) Qualify(vars Activation, obj any) (any, error) { } else { val = e.adapter.NativeToValue(out) } - e.observer(e.ID(), e.Attribute, val) + e.observer(vars, e.ID(), e.Attribute, val) return out, err } @@ -963,7 +1001,7 @@ func (e *evalWatchAttrQual) QualifyIfPresent(vars Activation, obj any, presenceO val = types.Bool(present) } if present || presenceOnly { - e.observer(e.ID(), e.Attribute, val) + e.observer(vars, e.ID(), e.Attribute, val) } return out, present, err } @@ -984,7 +1022,7 @@ func (e *evalWatchQual) Qualify(vars Activation, obj any) (any, error) { } else { val = e.adapter.NativeToValue(out) } - e.observer(e.ID(), e.Qualifier, val) + e.observer(vars, e.ID(), e.Qualifier, val) return out, err } @@ -1000,7 +1038,7 @@ func (e *evalWatchQual) QualifyIfPresent(vars Activation, obj any, presenceOnly val = types.Bool(present) } if present || presenceOnly { - e.observer(e.ID(), e.Qualifier, val) + e.observer(vars, e.ID(), e.Qualifier, val) } return out, present, err } @@ -1014,7 +1052,7 @@ type evalWatchConst struct { // Eval implements the Interpretable interface method. func (e *evalWatchConst) Eval(vars Activation) ref.Val { val := e.Value() - e.observer(e.ID(), e.InterpretableConst, val) + e.observer(vars, e.ID(), e.InterpretableConst, val) return val } @@ -1187,13 +1225,13 @@ func (a *evalAttr) Eval(ctx Activation) ref.Val { } // Qualify proxies to the Attribute's Qualify method. -func (a *evalAttr) Qualify(ctx Activation, obj any) (any, error) { - return a.attr.Qualify(ctx, obj) +func (a *evalAttr) Qualify(vars Activation, obj any) (any, error) { + return a.attr.Qualify(vars, obj) } // QualifyIfPresent proxies to the Attribute's QualifyIfPresent method. -func (a *evalAttr) QualifyIfPresent(ctx Activation, obj any, presenceOnly bool) (any, bool, error) { - return a.attr.QualifyIfPresent(ctx, obj, presenceOnly) +func (a *evalAttr) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { + return a.attr.QualifyIfPresent(vars, obj, presenceOnly) } func (a *evalAttr) IsOptional() bool { @@ -1226,9 +1264,9 @@ func (c *evalWatchConstructor) ID() int64 { } // Eval implements the Interpretable Eval function. -func (c *evalWatchConstructor) Eval(ctx Activation) ref.Val { - val := c.constructor.Eval(ctx) - c.observer(c.ID(), c.constructor, val) +func (c *evalWatchConstructor) Eval(vars Activation) ref.Val { + val := c.constructor.Eval(vars) + c.observer(vars, c.ID(), c.constructor, val) return val } @@ -1370,16 +1408,16 @@ func (f *folder) Parent() Activation { // if they were provided to the input activation, or an empty set if the proxied activation is not partial. func (f *folder) UnknownAttributePatterns() []*AttributePattern { if pv, ok := f.activation.(partialActivationConverter); ok { - if partial, isPartial := pv.asPartialActivation(); isPartial { + if partial, isPartial := pv.AsPartialActivation(); isPartial { return partial.UnknownAttributePatterns() } } return []*AttributePattern{} } -func (f *folder) asPartialActivation() (PartialActivation, bool) { +func (f *folder) AsPartialActivation() (PartialActivation, bool) { if pv, ok := f.activation.(partialActivationConverter); ok { - if _, isPartial := pv.asPartialActivation(); isPartial { + if _, isPartial := pv.AsPartialActivation(); isPartial { return f, true } } diff --git a/vendor/github.com/google/cel-go/interpreter/interpreter.go b/vendor/github.com/google/cel-go/interpreter/interpreter.go index 0aca74d8..be57e743 100644 --- a/vendor/github.com/google/cel-go/interpreter/interpreter.go +++ b/vendor/github.com/google/cel-go/interpreter/interpreter.go @@ -18,36 +18,41 @@ package interpreter import ( + "errors" + "github.com/google/cel-go/common/ast" "github.com/google/cel-go/common/containers" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" ) +// PlannerOption configures the program plan options during interpretable setup. +type PlannerOption func(*planner) (*planner, error) + // Interpreter generates a new Interpretable from a checked or unchecked expression. type Interpreter interface { // NewInterpretable creates an Interpretable from a checked expression and an - // optional list of InterpretableDecorator values. - NewInterpretable(exprAST *ast.AST, decorators ...InterpretableDecorator) (Interpretable, error) + // optional list of PlannerOption values. + NewInterpretable(exprAST *ast.AST, opts ...PlannerOption) (Interpretable, error) } // EvalObserver is a functional interface that accepts an expression id and an observed value. // The id identifies the expression that was evaluated, the programStep is the Interpretable or Qualifier that // was evaluated and value is the result of the evaluation. -type EvalObserver func(id int64, programStep any, value ref.Val) +type EvalObserver func(vars Activation, id int64, programStep any, value ref.Val) -// Observe constructs a decorator that calls all the provided observers in order after evaluating each Interpretable -// or Qualifier during program evaluation. -func Observe(observers ...EvalObserver) InterpretableDecorator { - if len(observers) == 1 { - return decObserveEval(observers[0]) - } - observeFn := func(id int64, programStep any, val ref.Val) { - for _, observer := range observers { - observer(id, programStep, val) - } - } - return decObserveEval(observeFn) +// StatefulObserver observes evaluation while tracking or utilizing stateful behavior. +type StatefulObserver interface { + // InitState configures stateful metadata on the activation. + InitState(Activation) (Activation, error) + + // GetState retrieves the stateful metadata from the activation. + GetState(Activation) any + + // Observe passes the activation and relevant evaluation metadata to the observer. + // The observe method is expected to do the equivalent of GetState(vars) in order + // to find the metadata that needs to be updated upon invocation. + Observe(vars Activation, id int64, programStep any, value ref.Val) } // EvalCancelledError represents a cancelled program evaluation operation. @@ -73,24 +78,110 @@ const ( CostLimitExceeded ) -// TODO: Replace all usages of TrackState with EvalStateObserver +// evalStateOption configures the evalStateFactory behavior. +type evalStateOption func(*evalStateFactory) *evalStateFactory + +// EvalStateFactory configures the EvalState generator to be used by the EvalStateObserver. +func EvalStateFactory(factory func() EvalState) evalStateOption { + return func(fac *evalStateFactory) *evalStateFactory { + fac.factory = factory + return fac + } +} + +// EvalStateObserver provides an observer which records the value associated with the given expression id. +// EvalState must be provided to the observer. +func EvalStateObserver(opts ...evalStateOption) PlannerOption { + et := &evalStateFactory{factory: NewEvalState} + for _, o := range opts { + et = o(et) + } + return func(p *planner) (*planner, error) { + if et.factory == nil { + return nil, errors.New("eval state factory not configured") + } + p.observers = append(p.observers, et) + p.decorators = append(p.decorators, decObserveEval(et.Observe)) + return p, nil + } +} + +// evalStateConverter identifies an object which is convertible to an EvalState instance. +type evalStateConverter interface { + asEvalState() EvalState +} + +// evalStateActivation hides state in the Activation in a manner not accessible to expressions. +type evalStateActivation struct { + vars Activation + state EvalState +} + +// ResolveName proxies variable lookups to the backing activation. +func (esa evalStateActivation) ResolveName(name string) (any, bool) { + return esa.vars.ResolveName(name) +} + +// Parent proxies parent lookups to the backing activation. +func (esa evalStateActivation) Parent() Activation { + return esa.vars +} + +// AsPartialActivation supports conversion to a partial activation in order to detect unknown attributes. +func (esa evalStateActivation) AsPartialActivation() (PartialActivation, bool) { + return AsPartialActivation(esa.vars) +} -// TrackState decorates each expression node with an observer which records the value -// associated with the given expression id. EvalState must be provided to the decorator. -// This decorator is not thread-safe, and the EvalState must be reset between Eval() -// calls. -// DEPRECATED: Please use EvalStateObserver instead. It composes gracefully with additional observers. -func TrackState(state EvalState) InterpretableDecorator { - return Observe(EvalStateObserver(state)) +// asEvalState implements the evalStateConverter method. +func (esa evalStateActivation) asEvalState() EvalState { + return esa.state } -// EvalStateObserver provides an observer which records the value -// associated with the given expression id. EvalState must be provided to the observer. -// This decorator is not thread-safe, and the EvalState must be reset between Eval() -// calls. -func EvalStateObserver(state EvalState) EvalObserver { - return func(id int64, programStep any, val ref.Val) { - state.SetValue(id, val) +// asEvalState walks the Activation hierarchy and returns the first EvalState found, if present. +func asEvalState(vars Activation) (EvalState, bool) { + if conv, ok := vars.(evalStateConverter); ok { + return conv.asEvalState(), true + } + if vars.Parent() != nil { + return asEvalState(vars.Parent()) + } + return nil, false +} + +// evalStateFactory holds a reference to a factory function that produces an EvalState instance. +type evalStateFactory struct { + factory func() EvalState +} + +// InitState produces an EvalState instance and bundles it into the Activation in a way which is +// not visible to expression evaluation. +func (et *evalStateFactory) InitState(vars Activation) (Activation, error) { + state := et.factory() + return evalStateActivation{vars: vars, state: state}, nil +} + +// GetState extracts the EvalState from the Activation. +func (et *evalStateFactory) GetState(vars Activation) any { + if state, found := asEvalState(vars); found { + return state + } + return nil +} + +// Observe records the evaluation state for a given expression node and program step. +func (et *evalStateFactory) Observe(vars Activation, id int64, programStep any, val ref.Val) { + state, found := asEvalState(vars) + if !found { + return + } + state.SetValue(id, val) +} + +// CustomDecorator configures a custom interpretable decorator for the program. +func CustomDecorator(dec InterpretableDecorator) PlannerOption { + return func(p *planner) (*planner, error) { + p.decorators = append(p.decorators, dec) + return p, nil } } @@ -99,11 +190,8 @@ func EvalStateObserver(state EvalState) EvalObserver { // insight into the evaluation state of the entire expression. EvalState must be // provided to the decorator. This decorator is not thread-safe, and the EvalState // must be reset between Eval() calls. -func ExhaustiveEval() InterpretableDecorator { - ex := decDisableShortcircuits() - return func(i Interpretable) (Interpretable, error) { - return ex(i) - } +func ExhaustiveEval() PlannerOption { + return CustomDecorator(decDisableShortcircuits()) } // InterruptableEval annotates comprehension loops with information that indicates they @@ -111,14 +199,14 @@ func ExhaustiveEval() InterpretableDecorator { // // The custom activation is currently managed higher up in the stack within the 'cel' package // and should not require any custom support on behalf of callers. -func InterruptableEval() InterpretableDecorator { - return decInterruptFolds() +func InterruptableEval() PlannerOption { + return CustomDecorator(decInterruptFolds()) } // Optimize will pre-compute operations such as list and map construction and optimize // call arguments to set membership tests. The set of optimizations will increase over time. -func Optimize() InterpretableDecorator { - return decOptimize() +func Optimize() PlannerOption { + return CustomDecorator(decOptimize()) } // RegexOptimization provides a way to replace an InterpretableCall for a regex function when the @@ -142,8 +230,8 @@ type RegexOptimization struct { // CompileRegexConstants compiles regex pattern string constants at program creation time and reports any regex pattern // compile errors. -func CompileRegexConstants(regexOptimizations ...*RegexOptimization) InterpretableDecorator { - return decRegexOptimizer(regexOptimizations...) +func CompileRegexConstants(regexOptimizations ...*RegexOptimization) PlannerOption { + return CustomDecorator(decRegexOptimizer(regexOptimizations...)) } type exprInterpreter struct { @@ -172,14 +260,14 @@ func NewInterpreter(dispatcher Dispatcher, // NewIntepretable implements the Interpreter interface method. func (i *exprInterpreter) NewInterpretable( checked *ast.AST, - decorators ...InterpretableDecorator) (Interpretable, error) { - p := newPlanner( - i.dispatcher, - i.provider, - i.adapter, - i.attrFactory, - i.container, - checked, - decorators...) + opts ...PlannerOption) (Interpretable, error) { + p := newPlanner(i.dispatcher, i.provider, i.adapter, i.attrFactory, i.container, checked) + var err error + for _, o := range opts { + p, err = o(p) + if err != nil { + return nil, err + } + } return p.Plan(checked.Expr()) } diff --git a/vendor/github.com/google/cel-go/interpreter/planner.go b/vendor/github.com/google/cel-go/interpreter/planner.go index f0fd4eaf..f0e0d430 100644 --- a/vendor/github.com/google/cel-go/interpreter/planner.go +++ b/vendor/github.com/google/cel-go/interpreter/planner.go @@ -25,12 +25,6 @@ import ( "github.com/google/cel-go/common/types" ) -// interpretablePlanner creates an Interpretable evaluation plan from a proto Expr value. -type interpretablePlanner interface { - // Plan generates an Interpretable value (or error) from the input proto Expr. - Plan(expr ast.Expr) (Interpretable, error) -} - // newPlanner creates an interpretablePlanner which references a Dispatcher, TypeProvider, // TypeAdapter, Container, and CheckedExpr value. These pieces of data are used to resolve // functions, types, and namespaced identifiers at plan time rather than at runtime since @@ -40,8 +34,7 @@ func newPlanner(disp Dispatcher, adapter types.Adapter, attrFactory AttributeFactory, cont *containers.Container, - exprAST *ast.AST, - decorators ...InterpretableDecorator) interpretablePlanner { + exprAST *ast.AST) *planner { return &planner{ disp: disp, provider: provider, @@ -50,7 +43,8 @@ func newPlanner(disp Dispatcher, container: cont, refMap: exprAST.ReferenceMap(), typeMap: exprAST.TypeMap(), - decorators: decorators, + decorators: make([]InterpretableDecorator, 0), + observers: make([]StatefulObserver, 0), } } @@ -64,6 +58,7 @@ type planner struct { refMap map[int64]*ast.ReferenceInfo typeMap map[int64]*types.Type decorators []InterpretableDecorator + observers []StatefulObserver } // Plan implements the interpretablePlanner interface. This implementation of the Plan method also @@ -72,6 +67,17 @@ type planner struct { // such as state-tracking, expression re-write, and possibly efficient thread-safe memoization of // repeated expressions. func (p *planner) Plan(expr ast.Expr) (Interpretable, error) { + i, err := p.plan(expr) + if err != nil { + return nil, err + } + if len(p.observers) == 0 { + return i, nil + } + return &ObservableInterpretable{Interpretable: i, observers: p.observers}, nil +} + +func (p *planner) plan(expr ast.Expr) (Interpretable, error) { switch expr.Kind() { case ast.CallKind: return p.decorate(p.planCall(expr)) @@ -161,7 +167,7 @@ func (p *planner) planSelect(expr ast.Expr) (Interpretable, error) { sel := expr.AsSelect() // Plan the operand evaluation. - op, err := p.Plan(sel.Operand()) + op, err := p.plan(sel.Operand()) if err != nil { return nil, err } @@ -220,14 +226,14 @@ func (p *planner) planCall(expr ast.Expr) (Interpretable, error) { args := make([]Interpretable, argCount) if target != nil { - arg, err := p.Plan(target) + arg, err := p.plan(target) if err != nil { return nil, err } args[0] = arg } for i, argExpr := range call.Args() { - arg, err := p.Plan(argExpr) + arg, err := p.plan(argExpr) if err != nil { return nil, err } @@ -496,7 +502,7 @@ func (p *planner) planCreateList(expr ast.Expr) (Interpretable, error) { } elems := make([]Interpretable, len(elements)) for i, elem := range elements { - elemVal, err := p.Plan(elem) + elemVal, err := p.plan(elem) if err != nil { return nil, err } @@ -521,13 +527,13 @@ func (p *planner) planCreateMap(expr ast.Expr) (Interpretable, error) { hasOptionals := false for i, e := range entries { entry := e.AsMapEntry() - keyVal, err := p.Plan(entry.Key()) + keyVal, err := p.plan(entry.Key()) if err != nil { return nil, err } keys[i] = keyVal - valVal, err := p.Plan(entry.Value()) + valVal, err := p.plan(entry.Value()) if err != nil { return nil, err } @@ -560,7 +566,7 @@ func (p *planner) planCreateStruct(expr ast.Expr) (Interpretable, error) { for i, f := range objFields { field := f.AsStructField() fields[i] = field.Name() - val, err := p.Plan(field.Value()) + val, err := p.plan(field.Value()) if err != nil { return nil, err } @@ -582,23 +588,23 @@ func (p *planner) planCreateStruct(expr ast.Expr) (Interpretable, error) { // planComprehension generates an Interpretable fold operation. func (p *planner) planComprehension(expr ast.Expr) (Interpretable, error) { fold := expr.AsComprehension() - accu, err := p.Plan(fold.AccuInit()) + accu, err := p.plan(fold.AccuInit()) if err != nil { return nil, err } - iterRange, err := p.Plan(fold.IterRange()) + iterRange, err := p.plan(fold.IterRange()) if err != nil { return nil, err } - cond, err := p.Plan(fold.LoopCondition()) + cond, err := p.plan(fold.LoopCondition()) if err != nil { return nil, err } - step, err := p.Plan(fold.LoopStep()) + step, err := p.plan(fold.LoopStep()) if err != nil { return nil, err } - result, err := p.Plan(fold.Result()) + result, err := p.plan(fold.Result()) if err != nil { return nil, err } diff --git a/vendor/github.com/google/cel-go/interpreter/runtimecost.go b/vendor/github.com/google/cel-go/interpreter/runtimecost.go index 8f47c53d..6c44cd79 100644 --- a/vendor/github.com/google/cel-go/interpreter/runtimecost.go +++ b/vendor/github.com/google/cel-go/interpreter/runtimecost.go @@ -15,6 +15,7 @@ package interpreter import ( + "errors" "math" "github.com/google/cel-go/common" @@ -34,78 +35,172 @@ type ActualCostEstimator interface { CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64 } +// costTrackPlanOption modifies the cost tracking factory associatied with the CostObserver +type costTrackPlanOption func(*costTrackerFactory) *costTrackerFactory + +// CostTrackerFactory configures the factory method to generate a new cost-tracker per-evaluation. +func CostTrackerFactory(factory func() (*CostTracker, error)) costTrackPlanOption { + return func(fac *costTrackerFactory) *costTrackerFactory { + fac.factory = factory + return fac + } +} + // CostObserver provides an observer that tracks runtime cost. -func CostObserver(tracker *CostTracker) EvalObserver { - observer := func(id int64, programStep any, val ref.Val) { - switch t := programStep.(type) { - case ConstantQualifier: - // TODO: Push identifiers on to the stack before observing constant qualifiers that apply to them - // and enable the below pop. Once enabled this can case can be collapsed into the Qualifier case. - tracker.cost++ - case InterpretableConst: - // zero cost - case InterpretableAttribute: - switch a := t.Attr().(type) { - case *conditionalAttribute: - // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions. - tracker.stack.drop(a.falsy.ID(), a.truthy.ID(), a.expr.ID()) - default: - tracker.stack.drop(t.Attr().ID()) - tracker.cost += common.SelectAndIdentCost - } - if !tracker.presenceTestHasCost { - if _, isTestOnly := programStep.(*evalTestOnly); isTestOnly { - tracker.cost -= common.SelectAndIdentCost - } - } - case *evalExhaustiveConditional: - // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions. - tracker.stack.drop(t.attr.falsy.ID(), t.attr.truthy.ID(), t.attr.expr.ID()) +func CostObserver(opts ...costTrackPlanOption) PlannerOption { + ct := &costTrackerFactory{} + for _, o := range opts { + ct = o(ct) + } + return func(p *planner) (*planner, error) { + if ct.factory == nil { + return nil, errors.New("cost tracker factory not configured") + } + p.observers = append(p.observers, ct) + p.decorators = append(p.decorators, decObserveEval(ct.Observe)) + return p, nil + } +} - // While the field names are identical, the boolean operation eval structs do not share an interface and so - // must be handled individually. - case *evalOr: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalAnd: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalExhaustiveOr: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalExhaustiveAnd: - for _, term := range t.terms { - tracker.stack.drop(term.ID()) - } - case *evalFold: - tracker.stack.drop(t.iterRange.ID()) - case Qualifier: - tracker.cost++ - case InterpretableCall: - if argVals, ok := tracker.stack.dropArgs(t.Args()); ok { - tracker.cost += tracker.costCall(t, argVals, val) - } - case InterpretableConstructor: - tracker.stack.dropArgs(t.InitVals()) - switch t.Type() { - case types.ListType: - tracker.cost += common.ListCreateBaseCost - case types.MapType: - tracker.cost += common.MapCreateBaseCost - default: - tracker.cost += common.StructCreateBaseCost +// costTrackerConverter identifies an object which is convertible to a CostTracker instance. +type costTrackerConverter interface { + asCostTracker() *CostTracker +} + +// costTrackActivation hides state in the Activation in a manner not accessible to expressions. +type costTrackActivation struct { + vars Activation + costTracker *CostTracker +} + +// ResolveName proxies variable lookups to the backing activation. +func (cta costTrackActivation) ResolveName(name string) (any, bool) { + return cta.vars.ResolveName(name) +} + +// Parent proxies parent lookups to the backing activation. +func (cta costTrackActivation) Parent() Activation { + return cta.vars +} + +// AsPartialActivation supports conversion to a partial activation in order to detect unknown attributes. +func (cta costTrackActivation) AsPartialActivation() (PartialActivation, bool) { + return AsPartialActivation(cta.vars) +} + +// asCostTracker implements the costTrackerConverter method. +func (cta costTrackActivation) asCostTracker() *CostTracker { + return cta.costTracker +} + +// asCostTracker walks the Activation hierarchy and returns the first cost tracker found, if present. +func asCostTracker(vars Activation) (*CostTracker, bool) { + if conv, ok := vars.(costTrackerConverter); ok { + return conv.asCostTracker(), true + } + if vars.Parent() != nil { + return asCostTracker(vars.Parent()) + } + return nil, false +} + +// costTrackerFactory holds a factory for producing new CostTracker instances on each Eval call. +type costTrackerFactory struct { + factory func() (*CostTracker, error) +} + +// InitState produces a CostTracker and bundles it into an Activation in a way which is not visible +// to expression evaluation. +func (ct *costTrackerFactory) InitState(vars Activation) (Activation, error) { + tracker, err := ct.factory() + if err != nil { + return nil, err + } + return costTrackActivation{vars: vars, costTracker: tracker}, nil +} + +// GetState extracts the CostTracker from the Activation. +func (ct *costTrackerFactory) GetState(vars Activation) any { + if tracker, found := asCostTracker(vars); found { + return tracker + } + return nil +} + +// Observe computes the incremental cost of each step and records it into the CostTracker associated +// with the evaluation. +func (ct *costTrackerFactory) Observe(vars Activation, id int64, programStep any, val ref.Val) { + tracker, found := asCostTracker(vars) + if !found { + return + } + switch t := programStep.(type) { + case ConstantQualifier: + // TODO: Push identifiers on to the stack before observing constant qualifiers that apply to them + // and enable the below pop. Once enabled this can case can be collapsed into the Qualifier case. + tracker.cost++ + case InterpretableConst: + // zero cost + case InterpretableAttribute: + switch a := t.Attr().(type) { + case *conditionalAttribute: + // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions. + tracker.stack.drop(a.falsy.ID(), a.truthy.ID(), a.expr.ID()) + default: + tracker.stack.drop(t.Attr().ID()) + tracker.cost += common.SelectAndIdentCost + } + if !tracker.presenceTestHasCost { + if _, isTestOnly := programStep.(*evalTestOnly); isTestOnly { + tracker.cost -= common.SelectAndIdentCost } } - tracker.stack.push(val, id) + case *evalExhaustiveConditional: + // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions. + tracker.stack.drop(t.attr.falsy.ID(), t.attr.truthy.ID(), t.attr.expr.ID()) - if tracker.Limit != nil && tracker.cost > *tracker.Limit { - panic(EvalCancelledError{Cause: CostLimitExceeded, Message: "operation cancelled: actual cost limit exceeded"}) + // While the field names are identical, the boolean operation eval structs do not share an interface and so + // must be handled individually. + case *evalOr: + for _, term := range t.terms { + tracker.stack.drop(term.ID()) + } + case *evalAnd: + for _, term := range t.terms { + tracker.stack.drop(term.ID()) } + case *evalExhaustiveOr: + for _, term := range t.terms { + tracker.stack.drop(term.ID()) + } + case *evalExhaustiveAnd: + for _, term := range t.terms { + tracker.stack.drop(term.ID()) + } + case *evalFold: + tracker.stack.drop(t.iterRange.ID()) + case Qualifier: + tracker.cost++ + case InterpretableCall: + if argVals, ok := tracker.stack.dropArgs(t.Args()); ok { + tracker.cost += tracker.costCall(t, argVals, val) + } + case InterpretableConstructor: + tracker.stack.dropArgs(t.InitVals()) + switch t.Type() { + case types.ListType: + tracker.cost += common.ListCreateBaseCost + case types.MapType: + tracker.cost += common.MapCreateBaseCost + default: + tracker.cost += common.StructCreateBaseCost + } + } + tracker.stack.push(val, id) + + if tracker.Limit != nil && tracker.cost > *tracker.Limit { + panic(EvalCancelledError{Cause: CostLimitExceeded, Message: "operation cancelled: actual cost limit exceeded"}) } - return observer } // CostTrackerOption configures the behavior of CostTracker objects. diff --git a/vendor/github.com/google/cel-go/parser/macro.go b/vendor/github.com/google/cel-go/parser/macro.go index 6b3b648d..1ef43c4b 100644 --- a/vendor/github.com/google/cel-go/parser/macro.go +++ b/vendor/github.com/google/cel-go/parser/macro.go @@ -24,38 +24,74 @@ import ( "github.com/google/cel-go/common/types/ref" ) +// MacroOpt defines a functional option for configuring macro behavior. +type MacroOpt func(*macro) *macro + +// MacroDocs configures a list of strings into a multiline description for the macro. +func MacroDocs(docs ...string) MacroOpt { + return func(m *macro) *macro { + m.doc = common.MultilineDescription(docs...) + return m + } +} + +// MacroExamples configures a list of examples, either as a string or common.MultilineString, +// into an example set to be provided with the macro Documentation() call. +func MacroExamples(examples ...string) MacroOpt { + return func(m *macro) *macro { + m.examples = examples + return m + } +} + // NewGlobalMacro creates a Macro for a global function with the specified arg count. -func NewGlobalMacro(function string, argCount int, expander MacroExpander) Macro { - return ¯o{ +func NewGlobalMacro(function string, argCount int, expander MacroExpander, opts ...MacroOpt) Macro { + m := ¯o{ function: function, argCount: argCount, expander: expander} + for _, opt := range opts { + m = opt(m) + } + return m } // NewReceiverMacro creates a Macro for a receiver function matching the specified arg count. -func NewReceiverMacro(function string, argCount int, expander MacroExpander) Macro { - return ¯o{ +func NewReceiverMacro(function string, argCount int, expander MacroExpander, opts ...MacroOpt) Macro { + m := ¯o{ function: function, argCount: argCount, expander: expander, receiverStyle: true} + for _, opt := range opts { + m = opt(m) + } + return m } // NewGlobalVarArgMacro creates a Macro for a global function with a variable arg count. -func NewGlobalVarArgMacro(function string, expander MacroExpander) Macro { - return ¯o{ +func NewGlobalVarArgMacro(function string, expander MacroExpander, opts ...MacroOpt) Macro { + m := ¯o{ function: function, expander: expander, varArgStyle: true} + for _, opt := range opts { + m = opt(m) + } + return m } // NewReceiverVarArgMacro creates a Macro for a receiver function matching a variable arg count. -func NewReceiverVarArgMacro(function string, expander MacroExpander) Macro { - return ¯o{ +func NewReceiverVarArgMacro(function string, expander MacroExpander, opts ...MacroOpt) Macro { + m := ¯o{ function: function, expander: expander, receiverStyle: true, varArgStyle: true} + for _, opt := range opts { + m = opt(m) + } + return m } // Macro interface for describing the function signature to match and the MacroExpander to apply. @@ -95,6 +131,8 @@ type macro struct { varArgStyle bool argCount int expander MacroExpander + doc string + examples []string } // Function returns the macro's function name (i.e. the function whose syntax it mimics). @@ -125,6 +163,15 @@ func (m *macro) MacroKey() string { return makeMacroKey(m.function, m.argCount, m.receiverStyle) } +// Documentation generates documentation and examples for the macro. +func (m *macro) Documentation() *common.Doc { + examples := make([]*common.Doc, len(m.examples)) + for i, ex := range m.examples { + examples[i] = common.NewExampleDoc(ex) + } + return common.NewMacroDoc(m.Function(), m.doc, examples...) +} + func makeMacroKey(name string, args int, receiverStyle bool) string { return fmt.Sprintf("%s:%d:%v", name, args, receiverStyle) } @@ -250,37 +297,139 @@ type ExprHelper interface { var ( // HasMacro expands "has(m.f)" which tests the presence of a field, avoiding the need to // specify the field as a string. - HasMacro = NewGlobalMacro(operators.Has, 1, MakeHas) + HasMacro = NewGlobalMacro(operators.Has, 1, MakeHas, + MacroDocs( + `check a protocol buffer message for the presence of a field, or check a map`, + `for the presence of a string key.`, + `Only map accesses using the select notation are supported.`), + MacroExamples( + common.MultilineDescription( + `// true if the 'address' field exists in the 'user' message`, + `has(user.address)`), + common.MultilineDescription( + `// test whether the 'key_name' is set on the map which defines it`, + `has({'key_name': 'value'}.key_name) // true`), + common.MultilineDescription( + `// test whether the 'id' field is set to a non-default value on the Expr{} message literal`, + `has(Expr{}.id) // false`), + )) // AllMacro expands "range.all(var, predicate)" into a comprehension which ensures that all // elements in the range satisfy the predicate. - AllMacro = NewReceiverMacro(operators.All, 2, MakeAll) + AllMacro = NewReceiverMacro(operators.All, 2, MakeAll, + MacroDocs(`tests whether all elements in the input list or all keys in a map`, + `satisfy the given predicate. The all macro behaves in a manner consistent with`, + `the Logical AND operator including in how it absorbs errors and short-circuits.`), + MacroExamples( + `[1, 2, 3].all(x, x > 0) // true`, + `[1, 2, 0].all(x, x > 0) // false`, + `['apple', 'banana', 'cherry'].all(fruit, fruit.size() > 3) // true`, + `[3.14, 2.71, 1.61].all(num, num < 3.0) // false`, + `{'a': 1, 'b': 2, 'c': 3}.all(key, key != 'b') // false`, + common.MultilineDescription( + `// an empty list or map as the range will result in a trivially true result`, + `[].all(x, x > 0) // true`), + )) // ExistsMacro expands "range.exists(var, predicate)" into a comprehension which ensures that // some element in the range satisfies the predicate. - ExistsMacro = NewReceiverMacro(operators.Exists, 2, MakeExists) + ExistsMacro = NewReceiverMacro(operators.Exists, 2, MakeExists, + MacroDocs(`tests whether any value in the list or any key in the map`, + `satisfies the predicate expression. The exists macro behaves in a manner`, + `consistent with the Logical OR operator including in how it absorbs errors and`, + `short-circuits.`), + MacroExamples( + `[1, 2, 3].exists(i, i % 2 != 0) // true`, + `[0, -1, 5].exists(num, num < 0) // true`, + `{'x': 'foo', 'y': 'bar'}.exists(key, key.startsWith('z')) // false`, + common.MultilineDescription( + `// an empty list or map as the range will result in a trivially false result`, + `[].exists(i, i > 0) // false`), + common.MultilineDescription( + `// test whether a key name equalling 'iss' exists in the map and the`, + `// value contains the substring 'cel.dev'`, + `// tokens = {'sub': 'me', 'iss': 'https://issuer.cel.dev'}`, + `tokens.exists(k, k == 'iss' && tokens[k].contains('cel.dev'))`), + )) // ExistsOneMacro expands "range.exists_one(var, predicate)", which is true if for exactly one // element in range the predicate holds. // Deprecated: Use ExistsOneMacroNew - ExistsOneMacro = NewReceiverMacro(operators.ExistsOne, 2, MakeExistsOne) + ExistsOneMacro = NewReceiverMacro(operators.ExistsOne, 2, MakeExistsOne, + MacroDocs(`tests whether exactly one list element or map key satisfies`, + `the predicate expression. This macro does not short-circuit in order to remain`, + `consistent with logical operators being the only operators which can absorb`, + `errors within CEL.`), + MacroExamples( + `[1, 2, 2].exists_one(i, i < 2) // true`, + `{'a': 'hello', 'aa': 'hellohello'}.exists_one(k, k.startsWith('a')) // false`, + `[1, 2, 3, 4].exists_one(num, num % 2 == 0) // false`, + common.MultilineDescription( + `// ensure exactly one key in the map ends in @acme.co`, + `{'wiley@acme.co': 'coyote', 'aa@milne.co': 'bear'}.exists_one(k, k.endsWith('@acme.co')) // true`), + )) // ExistsOneMacroNew expands "range.existsOne(var, predicate)", which is true if for exactly one // element in range the predicate holds. - ExistsOneMacroNew = NewReceiverMacro("existsOne", 2, MakeExistsOne) + ExistsOneMacroNew = NewReceiverMacro("existsOne", 2, MakeExistsOne, + MacroDocs( + `tests whether exactly one list element or map key satisfies the predicate`, + `expression. This macro does not short-circuit in order to remain consistent`, + `with logical operators being the only operators which can absorb errors`, + `within CEL.`), + MacroExamples( + `[1, 2, 2].existsOne(i, i < 2) // true`, + `{'a': 'hello', 'aa': 'hellohello'}.existsOne(k, k.startsWith('a')) // false`, + `[1, 2, 3, 4].existsOne(num, num % 2 == 0) // false`, + common.MultilineDescription( + `// ensure exactly one key in the map ends in @acme.co`, + `{'wiley@acme.co': 'coyote', 'aa@milne.co': 'bear'}.existsOne(k, k.endsWith('@acme.co')) // true`), + )) // MapMacro expands "range.map(var, function)" into a comprehension which applies the function // to each element in the range to produce a new list. - MapMacro = NewReceiverMacro(operators.Map, 2, MakeMap) + MapMacro = NewReceiverMacro(operators.Map, 2, MakeMap, + MacroDocs("the three-argument form of map transforms all elements in the input range."), + MacroExamples( + `[1, 2, 3].map(x, x * 2) // [2, 4, 6]`, + `[5, 10, 15].map(x, x / 5) // [1, 2, 3]`, + `['apple', 'banana'].map(fruit, fruit.upperAscii()) // ['APPLE', 'BANANA']`, + common.MultilineDescription( + `// Combine all map key-value pairs into a list`, + `{'hi': 'you', 'howzit': 'bruv'}.map(k,`, + ` k + ":" + {'hi': 'you', 'howzit': 'bruv'}[k]) // ['hi:you', 'howzit:bruv']`), + )) // MapFilterMacro expands "range.map(var, predicate, function)" into a comprehension which // first filters the elements in the range by the predicate, then applies the transform function // to produce a new list. - MapFilterMacro = NewReceiverMacro(operators.Map, 3, MakeMap) + MapFilterMacro = NewReceiverMacro(operators.Map, 3, MakeMap, + MacroDocs(`the four-argument form of the map transforms only elements which satisfy`, + `the predicate which is equivalent to chaining the filter and three-argument`, + `map macros together.`), + MacroExamples( + common.MultilineDescription( + `// multiply only numbers divisible two, by 2`, + `[1, 2, 3, 4].map(num, num % 2 == 0, num * 2) // [4, 8]`), + )) // FilterMacro expands "range.filter(var, predicate)" into a comprehension which filters // elements in the range, producing a new list from the elements that satisfy the predicate. - FilterMacro = NewReceiverMacro(operators.Filter, 2, MakeFilter) + FilterMacro = NewReceiverMacro(operators.Filter, 2, MakeFilter, + MacroDocs(`returns a list containing only the elements from the input list`, + `that satisfy the given predicate`), + MacroExamples( + `[1, 2, 3].filter(x, x > 1) // [2, 3]`, + `['cat', 'dog', 'bird', 'fish'].filter(pet, pet.size() == 3) // ['cat', 'dog']`, + `[{'a': 10, 'b': 5, 'c': 20}].map(m, m.filter(key, m[key] > 10)) // [['c']]`, + common.MultilineDescription( + `// filter a list to select only emails with the @cel.dev suffix`, + `['alice@buf.io', 'tristan@cel.dev'].filter(v, v.endsWith('@cel.dev')) // ['tristan@cel.dev']`), + common.MultilineDescription( + `// filter a map into a list, selecting only the values for keys that start with 'http-auth'`, + `{'http-auth-agent': 'secret', 'user-agent': 'mozilla'}.filter(k,`, + ` k.startsWith('http-auth')) // ['secret']`), + )) // AllMacros includes the list of all spec-supported macros. AllMacros = []Macro{ diff --git a/vendor/github.com/hashicorp/errwrap/LICENSE b/vendor/github.com/hashicorp/errwrap/LICENSE deleted file mode 100644 index c33dcc7c..00000000 --- a/vendor/github.com/hashicorp/errwrap/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/errwrap/README.md b/vendor/github.com/hashicorp/errwrap/README.md deleted file mode 100644 index 444df08f..00000000 --- a/vendor/github.com/hashicorp/errwrap/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# errwrap - -`errwrap` is a package for Go that formalizes the pattern of wrapping errors -and checking if an error contains another error. - -There is a common pattern in Go of taking a returned `error` value and -then wrapping it (such as with `fmt.Errorf`) before returning it. The problem -with this pattern is that you completely lose the original `error` structure. - -Arguably the _correct_ approach is that you should make a custom structure -implementing the `error` interface, and have the original error as a field -on that structure, such [as this example](http://golang.org/pkg/os/#PathError). -This is a good approach, but you have to know the entire chain of possible -rewrapping that happens, when you might just care about one. - -`errwrap` formalizes this pattern (it doesn't matter what approach you use -above) by giving a single interface for wrapping errors, checking if a specific -error is wrapped, and extracting that error. - -## Installation and Docs - -Install using `go get github.com/hashicorp/errwrap`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/errwrap - -## Usage - -#### Basic Usage - -Below is a very basic example of its usage: - -```go -// A function that always returns an error, but wraps it, like a real -// function might. -func tryOpen() error { - _, err := os.Open("/i/dont/exist") - if err != nil { - return errwrap.Wrapf("Doesn't exist: {{err}}", err) - } - - return nil -} - -func main() { - err := tryOpen() - - // We can use the Contains helpers to check if an error contains - // another error. It is safe to do this with a nil error, or with - // an error that doesn't even use the errwrap package. - if errwrap.Contains(err, "does not exist") { - // Do something - } - if errwrap.ContainsType(err, new(os.PathError)) { - // Do something - } - - // Or we can use the associated `Get` functions to just extract - // a specific error. This would return nil if that specific error doesn't - // exist. - perr := errwrap.GetType(err, new(os.PathError)) -} -``` - -#### Custom Types - -If you're already making custom types that properly wrap errors, then -you can get all the functionality of `errwraps.Contains` and such by -implementing the `Wrapper` interface with just one function. Example: - -```go -type AppError { - Code ErrorCode - Err error -} - -func (e *AppError) WrappedErrors() []error { - return []error{e.Err} -} -``` - -Now this works: - -```go -err := &AppError{Err: fmt.Errorf("an error")} -if errwrap.ContainsType(err, fmt.Errorf("")) { - // This will work! -} -``` diff --git a/vendor/github.com/hashicorp/errwrap/errwrap.go b/vendor/github.com/hashicorp/errwrap/errwrap.go deleted file mode 100644 index 44e368e5..00000000 --- a/vendor/github.com/hashicorp/errwrap/errwrap.go +++ /dev/null @@ -1,178 +0,0 @@ -// Package errwrap implements methods to formalize error wrapping in Go. -// -// All of the top-level functions that take an `error` are built to be able -// to take any error, not just wrapped errors. This allows you to use errwrap -// without having to type-check and type-cast everywhere. -package errwrap - -import ( - "errors" - "reflect" - "strings" -) - -// WalkFunc is the callback called for Walk. -type WalkFunc func(error) - -// Wrapper is an interface that can be implemented by custom types to -// have all the Contains, Get, etc. functions in errwrap work. -// -// When Walk reaches a Wrapper, it will call the callback for every -// wrapped error in addition to the wrapper itself. Since all the top-level -// functions in errwrap use Walk, this means that all those functions work -// with your custom type. -type Wrapper interface { - WrappedErrors() []error -} - -// Wrap defines that outer wraps inner, returning an error type that -// can be cleanly used with the other methods in this package, such as -// Contains, GetAll, etc. -// -// This function won't modify the error message at all (the outer message -// will be used). -func Wrap(outer, inner error) error { - return &wrappedError{ - Outer: outer, - Inner: inner, - } -} - -// Wrapf wraps an error with a formatting message. This is similar to using -// `fmt.Errorf` to wrap an error. If you're using `fmt.Errorf` to wrap -// errors, you should replace it with this. -// -// format is the format of the error message. The string '{{err}}' will -// be replaced with the original error message. -// -// Deprecated: Use fmt.Errorf() -func Wrapf(format string, err error) error { - outerMsg := "" - if err != nil { - outerMsg = err.Error() - } - - outer := errors.New(strings.Replace( - format, "{{err}}", outerMsg, -1)) - - return Wrap(outer, err) -} - -// Contains checks if the given error contains an error with the -// message msg. If err is not a wrapped error, this will always return -// false unless the error itself happens to match this msg. -func Contains(err error, msg string) bool { - return len(GetAll(err, msg)) > 0 -} - -// ContainsType checks if the given error contains an error with -// the same concrete type as v. If err is not a wrapped error, this will -// check the err itself. -func ContainsType(err error, v interface{}) bool { - return len(GetAllType(err, v)) > 0 -} - -// Get is the same as GetAll but returns the deepest matching error. -func Get(err error, msg string) error { - es := GetAll(err, msg) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetType is the same as GetAllType but returns the deepest matching error. -func GetType(err error, v interface{}) error { - es := GetAllType(err, v) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetAll gets all the errors that might be wrapped in err with the -// given message. The order of the errors is such that the outermost -// matching error (the most recent wrap) is index zero, and so on. -func GetAll(err error, msg string) []error { - var result []error - - Walk(err, func(err error) { - if err.Error() == msg { - result = append(result, err) - } - }) - - return result -} - -// GetAllType gets all the errors that are the same type as v. -// -// The order of the return value is the same as described in GetAll. -func GetAllType(err error, v interface{}) []error { - var result []error - - var search string - if v != nil { - search = reflect.TypeOf(v).String() - } - Walk(err, func(err error) { - var needle string - if err != nil { - needle = reflect.TypeOf(err).String() - } - - if needle == search { - result = append(result, err) - } - }) - - return result -} - -// Walk walks all the wrapped errors in err and calls the callback. If -// err isn't a wrapped error, this will be called once for err. If err -// is a wrapped error, the callback will be called for both the wrapper -// that implements error as well as the wrapped error itself. -func Walk(err error, cb WalkFunc) { - if err == nil { - return - } - - switch e := err.(type) { - case *wrappedError: - cb(e.Outer) - Walk(e.Inner, cb) - case Wrapper: - cb(err) - - for _, err := range e.WrappedErrors() { - Walk(err, cb) - } - case interface{ Unwrap() error }: - cb(err) - Walk(e.Unwrap(), cb) - default: - cb(err) - } -} - -// wrappedError is an implementation of error that has both the -// outer and inner errors. -type wrappedError struct { - Outer error - Inner error -} - -func (w *wrappedError) Error() string { - return w.Outer.Error() -} - -func (w *wrappedError) WrappedErrors() []error { - return []error{w.Outer, w.Inner} -} - -func (w *wrappedError) Unwrap() error { - return w.Inner -} diff --git a/vendor/github.com/hashicorp/go-multierror/LICENSE b/vendor/github.com/hashicorp/go-multierror/LICENSE deleted file mode 100644 index 82b4de97..00000000 --- a/vendor/github.com/hashicorp/go-multierror/LICENSE +++ /dev/null @@ -1,353 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/go-multierror/Makefile b/vendor/github.com/hashicorp/go-multierror/Makefile deleted file mode 100644 index b97cd6ed..00000000 --- a/vendor/github.com/hashicorp/go-multierror/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TEST?=./... - -default: test - -# test runs the test suite and vets the code. -test: generate - @echo "==> Running tests..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} - -# testrace runs the race checker -testrace: generate - @echo "==> Running tests (race)..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -race ${TESTARGS} - -# updatedeps installs all the dependencies needed to run and build. -updatedeps: - @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" - -# generate runs `go generate` to build the dynamically generated source files. -generate: - @echo "==> Generating..." - @find . -type f -name '.DS_Store' -delete - @go list ./... \ - | grep -v "/vendor/" \ - | xargs -n1 go generate - -.PHONY: default test testrace updatedeps generate diff --git a/vendor/github.com/hashicorp/go-multierror/README.md b/vendor/github.com/hashicorp/go-multierror/README.md deleted file mode 100644 index 71dd308e..00000000 --- a/vendor/github.com/hashicorp/go-multierror/README.md +++ /dev/null @@ -1,150 +0,0 @@ -# go-multierror - -[![CircleCI](https://img.shields.io/circleci/build/github/hashicorp/go-multierror/master)](https://circleci.com/gh/hashicorp/go-multierror) -[![Go Reference](https://pkg.go.dev/badge/github.com/hashicorp/go-multierror.svg)](https://pkg.go.dev/github.com/hashicorp/go-multierror) -![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/hashicorp/go-multierror) - -[circleci]: https://app.circleci.com/pipelines/github/hashicorp/go-multierror -[godocs]: https://pkg.go.dev/github.com/hashicorp/go-multierror - -`go-multierror` is a package for Go that provides a mechanism for -representing a list of `error` values as a single `error`. - -This allows a function in Go to return an `error` that might actually -be a list of errors. If the caller knows this, they can unwrap the -list and access the errors. If the caller doesn't know, the error -formats to a nice human-readable format. - -`go-multierror` is fully compatible with the Go standard library -[errors](https://golang.org/pkg/errors/) package, including the -functions `As`, `Is`, and `Unwrap`. This provides a standardized approach -for introspecting on error values. - -## Installation and Docs - -Install using `go get github.com/hashicorp/go-multierror`. - -Full documentation is available at -https://pkg.go.dev/github.com/hashicorp/go-multierror - -### Requires go version 1.13 or newer - -`go-multierror` requires go version 1.13 or newer. Go 1.13 introduced -[error wrapping](https://golang.org/doc/go1.13#error_wrapping), which -this library takes advantage of. - -If you need to use an earlier version of go, you can use the -[v1.0.0](https://github.com/hashicorp/go-multierror/tree/v1.0.0) -tag, which doesn't rely on features in go 1.13. - -If you see compile errors that look like the below, it's likely that -you're on an older version of go: - -``` -/go/src/github.com/hashicorp/go-multierror/multierror.go:112:9: undefined: errors.As -/go/src/github.com/hashicorp/go-multierror/multierror.go:117:9: undefined: errors.Is -``` - -## Usage - -go-multierror is easy to use and purposely built to be unobtrusive in -existing Go applications/libraries that may not be aware of it. - -**Building a list of errors** - -The `Append` function is used to create a list of errors. This function -behaves a lot like the Go built-in `append` function: it doesn't matter -if the first argument is nil, a `multierror.Error`, or any other `error`, -the function behaves as you would expect. - -```go -var result error - -if err := step1(); err != nil { - result = multierror.Append(result, err) -} -if err := step2(); err != nil { - result = multierror.Append(result, err) -} - -return result -``` - -**Customizing the formatting of the errors** - -By specifying a custom `ErrorFormat`, you can customize the format -of the `Error() string` function: - -```go -var result *multierror.Error - -// ... accumulate errors here, maybe using Append - -if result != nil { - result.ErrorFormat = func([]error) string { - return "errors!" - } -} -``` - -**Accessing the list of errors** - -`multierror.Error` implements `error` so if the caller doesn't know about -multierror, it will work just fine. But if you're aware a multierror might -be returned, you can use type switches to access the list of errors: - -```go -if err := something(); err != nil { - if merr, ok := err.(*multierror.Error); ok { - // Use merr.Errors - } -} -``` - -You can also use the standard [`errors.Unwrap`](https://golang.org/pkg/errors/#Unwrap) -function. This will continue to unwrap into subsequent errors until none exist. - -**Extracting an error** - -The standard library [`errors.As`](https://golang.org/pkg/errors/#As) -function can be used directly with a multierror to extract a specific error: - -```go -// Assume err is a multierror value -err := somefunc() - -// We want to know if "err" has a "RichErrorType" in it and extract it. -var errRich RichErrorType -if errors.As(err, &errRich) { - // It has it, and now errRich is populated. -} -``` - -**Checking for an exact error value** - -Some errors are returned as exact errors such as the [`ErrNotExist`](https://golang.org/pkg/os/#pkg-variables) -error in the `os` package. You can check if this error is present by using -the standard [`errors.Is`](https://golang.org/pkg/errors/#Is) function. - -```go -// Assume err is a multierror value -err := somefunc() -if errors.Is(err, os.ErrNotExist) { - // err contains os.ErrNotExist -} -``` - -**Returning a multierror only if there are errors** - -If you build a `multierror.Error`, you can use the `ErrorOrNil` function -to return an `error` implementation only if there are errors to return: - -```go -var result *multierror.Error - -// ... accumulate errors here - -// Return the `error` only if errors were added to the multierror, otherwise -// return nil since there are no errors. -return result.ErrorOrNil() -``` diff --git a/vendor/github.com/hashicorp/go-multierror/append.go b/vendor/github.com/hashicorp/go-multierror/append.go deleted file mode 100644 index 3e2589bf..00000000 --- a/vendor/github.com/hashicorp/go-multierror/append.go +++ /dev/null @@ -1,43 +0,0 @@ -package multierror - -// Append is a helper function that will append more errors -// onto an Error in order to create a larger multi-error. -// -// If err is not a multierror.Error, then it will be turned into -// one. If any of the errs are multierr.Error, they will be flattened -// one level into err. -// Any nil errors within errs will be ignored. If err is nil, a new -// *Error will be returned. -func Append(err error, errs ...error) *Error { - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Go through each error and flatten - for _, e := range errs { - switch e := e.(type) { - case *Error: - if e != nil { - err.Errors = append(err.Errors, e.Errors...) - } - default: - if e != nil { - err.Errors = append(err.Errors, e) - } - } - } - - return err - default: - newErrs := make([]error, 0, len(errs)+1) - if err != nil { - newErrs = append(newErrs, err) - } - newErrs = append(newErrs, errs...) - - return Append(&Error{}, newErrs...) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/flatten.go b/vendor/github.com/hashicorp/go-multierror/flatten.go deleted file mode 100644 index aab8e9ab..00000000 --- a/vendor/github.com/hashicorp/go-multierror/flatten.go +++ /dev/null @@ -1,26 +0,0 @@ -package multierror - -// Flatten flattens the given error, merging any *Errors together into -// a single *Error. -func Flatten(err error) error { - // If it isn't an *Error, just return the error as-is - if _, ok := err.(*Error); !ok { - return err - } - - // Otherwise, make the result and flatten away! - flatErr := new(Error) - flatten(err, flatErr) - return flatErr -} - -func flatten(err error, flatErr *Error) { - switch err := err.(type) { - case *Error: - for _, e := range err.Errors { - flatten(e, flatErr) - } - default: - flatErr.Errors = append(flatErr.Errors, err) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/format.go b/vendor/github.com/hashicorp/go-multierror/format.go deleted file mode 100644 index 47f13c49..00000000 --- a/vendor/github.com/hashicorp/go-multierror/format.go +++ /dev/null @@ -1,27 +0,0 @@ -package multierror - -import ( - "fmt" - "strings" -) - -// ErrorFormatFunc is a function callback that is called by Error to -// turn the list of errors into a string. -type ErrorFormatFunc func([]error) string - -// ListFormatFunc is a basic formatter that outputs the number of errors -// that occurred along with a bullet point list of the errors. -func ListFormatFunc(es []error) string { - if len(es) == 1 { - return fmt.Sprintf("1 error occurred:\n\t* %s\n\n", es[0]) - } - - points := make([]string, len(es)) - for i, err := range es { - points[i] = fmt.Sprintf("* %s", err) - } - - return fmt.Sprintf( - "%d errors occurred:\n\t%s\n\n", - len(es), strings.Join(points, "\n\t")) -} diff --git a/vendor/github.com/hashicorp/go-multierror/group.go b/vendor/github.com/hashicorp/go-multierror/group.go deleted file mode 100644 index 9c29efb7..00000000 --- a/vendor/github.com/hashicorp/go-multierror/group.go +++ /dev/null @@ -1,38 +0,0 @@ -package multierror - -import "sync" - -// Group is a collection of goroutines which return errors that need to be -// coalesced. -type Group struct { - mutex sync.Mutex - err *Error - wg sync.WaitGroup -} - -// Go calls the given function in a new goroutine. -// -// If the function returns an error it is added to the group multierror which -// is returned by Wait. -func (g *Group) Go(f func() error) { - g.wg.Add(1) - - go func() { - defer g.wg.Done() - - if err := f(); err != nil { - g.mutex.Lock() - g.err = Append(g.err, err) - g.mutex.Unlock() - } - }() -} - -// Wait blocks until all function calls from the Go method have returned, then -// returns the multierror. -func (g *Group) Wait() *Error { - g.wg.Wait() - g.mutex.Lock() - defer g.mutex.Unlock() - return g.err -} diff --git a/vendor/github.com/hashicorp/go-multierror/multierror.go b/vendor/github.com/hashicorp/go-multierror/multierror.go deleted file mode 100644 index f5457432..00000000 --- a/vendor/github.com/hashicorp/go-multierror/multierror.go +++ /dev/null @@ -1,121 +0,0 @@ -package multierror - -import ( - "errors" - "fmt" -) - -// Error is an error type to track multiple errors. This is used to -// accumulate errors in cases and return them as a single "error". -type Error struct { - Errors []error - ErrorFormat ErrorFormatFunc -} - -func (e *Error) Error() string { - fn := e.ErrorFormat - if fn == nil { - fn = ListFormatFunc - } - - return fn(e.Errors) -} - -// ErrorOrNil returns an error interface if this Error represents -// a list of errors, or returns nil if the list of errors is empty. This -// function is useful at the end of accumulation to make sure that the value -// returned represents the existence of errors. -func (e *Error) ErrorOrNil() error { - if e == nil { - return nil - } - if len(e.Errors) == 0 { - return nil - } - - return e -} - -func (e *Error) GoString() string { - return fmt.Sprintf("*%#v", *e) -} - -// WrappedErrors returns the list of errors that this Error is wrapping. It is -// an implementation of the errwrap.Wrapper interface so that multierror.Error -// can be used with that library. -// -// This method is not safe to be called concurrently. Unlike accessing the -// Errors field directly, this function also checks if the multierror is nil to -// prevent a null-pointer panic. It satisfies the errwrap.Wrapper interface. -func (e *Error) WrappedErrors() []error { - if e == nil { - return nil - } - return e.Errors -} - -// Unwrap returns an error from Error (or nil if there are no errors). -// This error returned will further support Unwrap to get the next error, -// etc. The order will match the order of Errors in the multierror.Error -// at the time of calling. -// -// The resulting error supports errors.As/Is/Unwrap so you can continue -// to use the stdlib errors package to introspect further. -// -// This will perform a shallow copy of the errors slice. Any errors appended -// to this error after calling Unwrap will not be available until a new -// Unwrap is called on the multierror.Error. -func (e *Error) Unwrap() error { - // If we have no errors then we do nothing - if e == nil || len(e.Errors) == 0 { - return nil - } - - // If we have exactly one error, we can just return that directly. - if len(e.Errors) == 1 { - return e.Errors[0] - } - - // Shallow copy the slice - errs := make([]error, len(e.Errors)) - copy(errs, e.Errors) - return chain(errs) -} - -// chain implements the interfaces necessary for errors.Is/As/Unwrap to -// work in a deterministic way with multierror. A chain tracks a list of -// errors while accounting for the current represented error. This lets -// Is/As be meaningful. -// -// Unwrap returns the next error. In the cleanest form, Unwrap would return -// the wrapped error here but we can't do that if we want to properly -// get access to all the errors. Instead, users are recommended to use -// Is/As to get the correct error type out. -// -// Precondition: []error is non-empty (len > 0) -type chain []error - -// Error implements the error interface -func (e chain) Error() string { - return e[0].Error() -} - -// Unwrap implements errors.Unwrap by returning the next error in the -// chain or nil if there are no more errors. -func (e chain) Unwrap() error { - if len(e) == 1 { - return nil - } - - return e[1:] -} - -// As implements errors.As by attempting to map to the current value. -func (e chain) As(target interface{}) bool { - return errors.As(e[0], target) -} - -// Is implements errors.Is by comparing the current value directly. -func (e chain) Is(target error) bool { - return errors.Is(e[0], target) -} diff --git a/vendor/github.com/hashicorp/go-multierror/prefix.go b/vendor/github.com/hashicorp/go-multierror/prefix.go deleted file mode 100644 index 5c477abe..00000000 --- a/vendor/github.com/hashicorp/go-multierror/prefix.go +++ /dev/null @@ -1,37 +0,0 @@ -package multierror - -import ( - "fmt" - - "github.com/hashicorp/errwrap" -) - -// Prefix is a helper function that will prefix some text -// to the given error. If the error is a multierror.Error, then -// it will be prefixed to each wrapped error. -// -// This is useful to use when appending multiple multierrors -// together in order to give better scoping. -func Prefix(err error, prefix string) error { - if err == nil { - return nil - } - - format := fmt.Sprintf("%s {{err}}", prefix) - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Wrap each of the errors - for i, e := range err.Errors { - err.Errors[i] = errwrap.Wrapf(format, e) - } - - return err - default: - return errwrap.Wrapf(format, err) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/sort.go b/vendor/github.com/hashicorp/go-multierror/sort.go deleted file mode 100644 index fecb14e8..00000000 --- a/vendor/github.com/hashicorp/go-multierror/sort.go +++ /dev/null @@ -1,16 +0,0 @@ -package multierror - -// Len implements sort.Interface function for length -func (err Error) Len() int { - return len(err.Errors) -} - -// Swap implements sort.Interface function for swapping elements -func (err Error) Swap(i, j int) { - err.Errors[i], err.Errors[j] = err.Errors[j], err.Errors[i] -} - -// Less implements sort.Interface function for determining order -func (err Error) Less(i, j int) bool { - return err.Errors[i].Error() < err.Errors[j].Error() -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/default.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/default.go index c52da0ba..435f33f3 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/default.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/default.go @@ -51,6 +51,11 @@ const ( DefaultImagePullBackOffTimeout = 0 * time.Minute + // Default maximum resolution timeout used by the resolution controller before timing out when exceeded + DefaultMaximumResolutionTimeout = 1 * time.Minute + + DefaultSidecarLogPollingInterval = 100 * time.Millisecond + defaultTimeoutMinutesKey = "default-timeout-minutes" defaultServiceAccountKey = "default-service-account" defaultManagedByLabelValueKey = "default-managed-by-label-value" @@ -63,6 +68,8 @@ const ( defaultResolverTypeKey = "default-resolver-type" defaultContainerResourceRequirementsKey = "default-container-resource-requirements" defaultImagePullBackOffTimeout = "default-imagepullbackoff-timeout" + defaultMaximumResolutionTimeout = "default-maximum-resolution-timeout" + defaultSidecarLogPollingIntervalKey = "default-sidecar-log-polling-interval" ) // DefaultConfig holds all the default configurations for the config. @@ -83,6 +90,11 @@ type Defaults struct { DefaultResolverType string DefaultContainerResourceRequirements map[string]corev1.ResourceRequirements DefaultImagePullBackOffTimeout time.Duration + DefaultMaximumResolutionTimeout time.Duration + // DefaultSidecarLogPollingInterval specifies how frequently (as a time.Duration) the Tekton sidecar log results container polls for step completion files. + // This value is loaded from the 'sidecar-log-polling-interval' key in the config-defaults ConfigMap. + // It is used to control the responsiveness and resource usage of the sidecar in both production and test environments. + DefaultSidecarLogPollingInterval time.Duration } // GetDefaultsConfigName returns the name of the configmap containing all @@ -114,6 +126,8 @@ func (cfg *Defaults) Equals(other *Defaults) bool { other.DefaultMaxMatrixCombinationsCount == cfg.DefaultMaxMatrixCombinationsCount && other.DefaultResolverType == cfg.DefaultResolverType && other.DefaultImagePullBackOffTimeout == cfg.DefaultImagePullBackOffTimeout && + other.DefaultMaximumResolutionTimeout == cfg.DefaultMaximumResolutionTimeout && + other.DefaultSidecarLogPollingInterval == cfg.DefaultSidecarLogPollingInterval && reflect.DeepEqual(other.DefaultForbiddenEnv, cfg.DefaultForbiddenEnv) } @@ -127,12 +141,14 @@ func NewDefaultsFromMap(cfgMap map[string]string) (*Defaults, error) { DefaultMaxMatrixCombinationsCount: DefaultMaxMatrixCombinationsCount, DefaultResolverType: DefaultResolverTypeValue, DefaultImagePullBackOffTimeout: DefaultImagePullBackOffTimeout, + DefaultMaximumResolutionTimeout: DefaultMaximumResolutionTimeout, + DefaultSidecarLogPollingInterval: DefaultSidecarLogPollingInterval, } if defaultTimeoutMin, ok := cfgMap[defaultTimeoutMinutesKey]; ok { timeout, err := strconv.ParseInt(defaultTimeoutMin, 10, 0) if err != nil { - return nil, fmt.Errorf("failed parsing tracing config %q", defaultTimeoutMinutesKey) + return nil, fmt.Errorf("failed parsing default config %q", defaultTimeoutMinutesKey) } tc.DefaultTimeoutMinutes = int(timeout) } @@ -172,7 +188,7 @@ func NewDefaultsFromMap(cfgMap map[string]string) (*Defaults, error) { if defaultMaxMatrixCombinationsCount, ok := cfgMap[defaultMaxMatrixCombinationsCountKey]; ok { matrixCombinationsCount, err := strconv.ParseInt(defaultMaxMatrixCombinationsCount, 10, 0) if err != nil { - return nil, fmt.Errorf("failed parsing tracing config %q", defaultMaxMatrixCombinationsCountKey) + return nil, fmt.Errorf("failed parsing default config %q", defaultMaxMatrixCombinationsCountKey) } tc.DefaultMaxMatrixCombinationsCount = int(matrixCombinationsCount) } @@ -200,11 +216,27 @@ func NewDefaultsFromMap(cfgMap map[string]string) (*Defaults, error) { if defaultImagePullBackOff, ok := cfgMap[defaultImagePullBackOffTimeout]; ok { timeout, err := time.ParseDuration(defaultImagePullBackOff) if err != nil { - return nil, fmt.Errorf("failed parsing tracing config %q", defaultImagePullBackOffTimeout) + return nil, fmt.Errorf("failed parsing default config %q", defaultImagePullBackOffTimeout) } tc.DefaultImagePullBackOffTimeout = timeout } + if defaultMaximumResolutionTimeout, ok := cfgMap[defaultMaximumResolutionTimeout]; ok { + timeout, err := time.ParseDuration(defaultMaximumResolutionTimeout) + if err != nil { + return nil, fmt.Errorf("failed parsing default config %q", defaultMaximumResolutionTimeout) + } + tc.DefaultMaximumResolutionTimeout = timeout + } + + if defaultSidecarPollingInterval, ok := cfgMap[defaultSidecarLogPollingIntervalKey]; ok { + interval, err := time.ParseDuration(defaultSidecarPollingInterval) + if err != nil { + return nil, fmt.Errorf("failed parsing default config %q", defaultSidecarPollingInterval) + } + tc.DefaultSidecarLogPollingInterval = interval + } + return &tc, nil } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/feature_flags.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/feature_flags.go index d0db6205..bac9a55d 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/feature_flags.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/feature_flags.go @@ -17,13 +17,10 @@ limitations under the License. package config import ( - "context" "fmt" "os" "strconv" "strings" - - corev1 "k8s.io/api/core/v1" ) const ( @@ -60,8 +57,6 @@ const ( ResultExtractionMethodTerminationMessage = "termination-message" // ResultExtractionMethodSidecarLogs is the value used for "results-from" as a way to extract results from tasks using sidecar logs. ResultExtractionMethodSidecarLogs = "sidecar-logs" - // DefaultDisableAffinityAssistant is the default value for "disable-affinity-assistant". - DefaultDisableAffinityAssistant = false // DefaultDisableCredsInit is the default value for "disable-creds-init". DefaultDisableCredsInit = false // DefaultRunningInEnvWithInjectedSidecars is the default value for "running-in-environment-with-injected-sidecars". @@ -94,14 +89,14 @@ const ( DefaultMaxResultSize = 4096 // DefaultSetSecurityContext is the default value for "set-security-context" DefaultSetSecurityContext = false + // DefaultSetSecurityContextReadOnlyRootFilesystem is the default value for "set-security-context-read-only-root-filesystem" + DefaultSetSecurityContextReadOnlyRootFilesystem = false // DefaultCoschedule is the default value for coschedule DefaultCoschedule = CoscheduleWorkspaces // KeepPodOnCancel is the flag used to enable cancelling a pod using the entrypoint, and keep pod on cancel KeepPodOnCancel = "keep-pod-on-cancel" // EnableCELInWhenExpression is the flag to enabled CEL in WhenExpression EnableCELInWhenExpression = "enable-cel-in-whenexpression" - // EnableStepActions is the flag to enable the use of StepActions in Steps - EnableStepActions = "enable-step-actions" // EnableArtifacts is the flag to enable the use of Artifacts in Steps EnableArtifacts = "enable-artifacts" // EnableParamEnum is the flag to enabled enum in params @@ -112,26 +107,34 @@ const ( EnableKubernetesSidecar = "enable-kubernetes-sidecar" // DefaultEnableKubernetesSidecar is the default value for EnableKubernetesSidecar DefaultEnableKubernetesSidecar = false + // EnableWaitExponentialBackoff is the flag to enable exponential backoff strategy + EnableWaitExponentialBackoff = "enable-wait-exponential-backoff" + // DefaultEnableWaitExponentialBackoff is the default value for EnableWaitExponentialBackoff + DefaultEnableWaitExponentialBackoff = false + + // EnableStepActions is the flag to enable step actions (no-op since it's stable) + EnableStepActions = "enable-step-actions" // DisableInlineSpec is the flag to disable embedded spec // in Taskrun or Pipelinerun DisableInlineSpec = "disable-inline-spec" - disableAffinityAssistantKey = "disable-affinity-assistant" disableCredsInitKey = "disable-creds-init" runningInEnvWithInjectedSidecarsKey = "running-in-environment-with-injected-sidecars" awaitSidecarReadinessKey = "await-sidecar-readiness" requireGitSSHSecretKnownHostsKey = "require-git-ssh-secret-known-hosts" //nolint:gosec // enableTektonOCIBundles = "enable-tekton-oci-bundles" - enableAPIFields = "enable-api-fields" - sendCloudEventsForRuns = "send-cloudevents-for-runs" - enforceNonfalsifiability = "enforce-nonfalsifiability" - verificationNoMatchPolicy = "trusted-resources-verification-no-match-policy" - enableProvenanceInStatus = "enable-provenance-in-status" - resultExtractionMethod = "results-from" - maxResultSize = "max-result-size" - setSecurityContextKey = "set-security-context" - coscheduleKey = "coschedule" + + enableAPIFields = "enable-api-fields" + sendCloudEventsForRuns = "send-cloudevents-for-runs" + enforceNonfalsifiability = "enforce-nonfalsifiability" + verificationNoMatchPolicy = "trusted-resources-verification-no-match-policy" + enableProvenanceInStatus = "enable-provenance-in-status" + resultExtractionMethod = "results-from" + maxResultSize = "max-result-size" + setSecurityContextKey = "set-security-context" + setSecurityContextReadOnlyRootFilesystemKey = "set-security-context-read-only-root-filesystem" + coscheduleKey = "coschedule" ) // DefaultFeatureFlags holds all the default configurations for the feature flags configmap. @@ -141,8 +144,8 @@ var ( // DefaultEnableKeepPodOnCancel is the default PerFeatureFlag value for "keep-pod-on-cancel" DefaultEnableKeepPodOnCancel = PerFeatureFlag{ Name: KeepPodOnCancel, - Stability: AlphaAPIFields, - Enabled: DefaultAlphaFeatureEnabled, + Stability: BetaAPIFields, + Enabled: DefaultBetaFeatureEnabled, } // DefaultEnableCELInWhenExpression is the default PerFeatureFlag value for EnableCELInWhenExpression @@ -152,13 +155,6 @@ var ( Enabled: DefaultAlphaFeatureEnabled, } - // DefaultEnableStepActions is the default PerFeatureFlag value for EnableStepActions - DefaultEnableStepActions = PerFeatureFlag{ - Name: EnableStepActions, - Stability: BetaAPIFields, - Enabled: DefaultBetaFeatureEnabled, - } - // DefaultEnableArtifacts is the default PerFeatureFlag value for EnableArtifacts DefaultEnableArtifacts = PerFeatureFlag{ Name: EnableArtifacts, @@ -184,35 +180,36 @@ var ( // FeatureFlags holds the features configurations // +k8s:deepcopy-gen=true type FeatureFlags struct { - DisableAffinityAssistant bool - DisableCredsInit bool - RunningInEnvWithInjectedSidecars bool - RequireGitSSHSecretKnownHosts bool - // EnableTektonOCIBundles bool // Deprecated: this is now ignored - // ScopeWhenExpressionsToTask bool // Deprecated: this is now ignored - EnableAPIFields string - SendCloudEventsForRuns bool - AwaitSidecarReadiness bool - EnforceNonfalsifiability string - EnableKeepPodOnCancel bool + DisableCredsInit bool `json:"disableCredsInit,omitempty"` + RunningInEnvWithInjectedSidecars bool `json:"runningInEnvWithInjectedSidecars,omitempty"` + RequireGitSSHSecretKnownHosts bool `json:"requireGitSSHSecretKnownHosts,omitempty"` + + EnableAPIFields string `json:"enableAPIFields,omitempty"` + SendCloudEventsForRuns bool `json:"sendCloudEventsForRuns,omitempty"` + AwaitSidecarReadiness bool `json:"awaitSidecarReadiness,omitempty"` + EnforceNonfalsifiability string `json:"enforceNonfalsifiability,omitempty"` + EnableKeepPodOnCancel bool `json:"enableKeepPodOnCancel,omitempty"` // VerificationNoMatchPolicy is the feature flag for "trusted-resources-verification-no-match-policy" // VerificationNoMatchPolicy can be set to "ignore", "warn" and "fail" values. // ignore: skip trusted resources verification when no matching verification policies found // warn: skip trusted resources verification when no matching verification policies found and log a warning // fail: fail the taskrun or pipelines run if no matching verification policies found - VerificationNoMatchPolicy string - EnableProvenanceInStatus bool - ResultExtractionMethod string - MaxResultSize int - SetSecurityContext bool - Coschedule string - EnableCELInWhenExpression bool - EnableStepActions bool - EnableParamEnum bool - EnableArtifacts bool - DisableInlineSpec string - EnableConciseResolverSyntax bool - EnableKubernetesSidecar bool + VerificationNoMatchPolicy string `json:"verificationNoMatchPolicy,omitempty"` + EnableProvenanceInStatus bool `json:"enableProvenanceInStatus,omitempty"` + ResultExtractionMethod string `json:"resultExtractionMethod,omitempty"` + MaxResultSize int `json:"maxResultSize,omitempty"` + SetSecurityContext bool `json:"setSecurityContext,omitempty"` + SetSecurityContextReadOnlyRootFilesystem bool `json:"setSecurityContextReadOnlyRootFilesystem,omitempty"` + Coschedule string `json:"coschedule,omitempty"` + EnableCELInWhenExpression bool `json:"enableCELInWhenExpression,omitempty"` + // EnableStepActions is a no-op flag since StepActions are stable + EnableStepActions bool `json:"enableStepActions,omitempty"` + EnableParamEnum bool `json:"enableParamEnum,omitempty"` + EnableArtifacts bool `json:"enableArtifacts,omitempty"` + DisableInlineSpec string `json:"disableInlineSpec,omitempty"` + EnableConciseResolverSyntax bool `json:"enableConciseResolverSyntax,omitempty"` + EnableKubernetesSidecar bool `json:"enableKubernetesSidecar,omitempty"` + EnableWaitExponentialBackoff bool `json:"enableWaitExponentialBackoff,omitempty"` } // GetFeatureFlagsConfigName returns the name of the configmap containing all @@ -253,9 +250,6 @@ func NewFeatureFlagsFromMap(cfgMap map[string]string) (*FeatureFlags, error) { } tc := FeatureFlags{} - if err := setFeature(disableAffinityAssistantKey, DefaultDisableAffinityAssistant, &tc.DisableAffinityAssistant); err != nil { - return nil, err - } if err := setFeature(disableCredsInitKey, DefaultDisableCredsInit, &tc.DisableCredsInit); err != nil { return nil, err } @@ -295,13 +289,13 @@ func NewFeatureFlagsFromMap(cfgMap map[string]string) (*FeatureFlags, error) { if err := setFeature(setSecurityContextKey, DefaultSetSecurityContext, &tc.SetSecurityContext); err != nil { return nil, err } - if err := setCoschedule(cfgMap, DefaultCoschedule, tc.DisableAffinityAssistant, &tc.Coschedule); err != nil { + if err := setFeature(setSecurityContextReadOnlyRootFilesystemKey, DefaultSetSecurityContextReadOnlyRootFilesystem, &tc.SetSecurityContextReadOnlyRootFilesystem); err != nil { return nil, err } - if err := setPerFeatureFlag(EnableCELInWhenExpression, DefaultEnableCELInWhenExpression, &tc.EnableCELInWhenExpression); err != nil { + if err := setCoschedule(cfgMap, DefaultCoschedule, &tc.Coschedule); err != nil { return nil, err } - if err := setPerFeatureFlag(EnableStepActions, DefaultEnableStepActions, &tc.EnableStepActions); err != nil { + if err := setPerFeatureFlag(EnableCELInWhenExpression, DefaultEnableCELInWhenExpression, &tc.EnableCELInWhenExpression); err != nil { return nil, err } if err := setPerFeatureFlag(EnableParamEnum, DefaultEnableParamEnum, &tc.EnableParamEnum); err != nil { @@ -320,6 +314,9 @@ func NewFeatureFlagsFromMap(cfgMap map[string]string) (*FeatureFlags, error) { if err := setFeature(EnableKubernetesSidecar, DefaultEnableKubernetesSidecar, &tc.EnableKubernetesSidecar); err != nil { return nil, err } + if err := setFeature(EnableWaitExponentialBackoff, DefaultEnableWaitExponentialBackoff, &tc.EnableWaitExponentialBackoff); err != nil { + return nil, err + } return &tc, nil } @@ -341,8 +338,7 @@ func setEnabledAPIFields(cfgMap map[string]string, defaultValue string, feature } // setCoschedule sets the "coschedule" flag based on the content of a given map. -// If the feature gate is invalid or incompatible with `disable-affinity-assistant`, then an error is returned. -func setCoschedule(cfgMap map[string]string, defaultValue string, disabledAffinityAssistant bool, feature *string) error { +func setCoschedule(cfgMap map[string]string, defaultValue string, feature *string) error { value := defaultValue if cfg, ok := cfgMap[coscheduleKey]; ok { value = strings.ToLower(cfg) @@ -350,11 +346,6 @@ func setCoschedule(cfgMap map[string]string, defaultValue string, disabledAffini switch value { case CoscheduleDisabled, CoscheduleWorkspaces, CoschedulePipelineRuns, CoscheduleIsolatePipelineRun: - // validate that "coschedule" is compatible with "disable-affinity-assistant" - // "coschedule" must be set to "workspaces" when "disable-affinity-assistant" is false - if !disabledAffinityAssistant && value != CoscheduleWorkspaces { - return fmt.Errorf("coschedule value %v is incompatible with %v setting to false", value, disableAffinityAssistantKey) - } *feature = value default: return fmt.Errorf("invalid value for feature flag %q: %q", coscheduleKey, value) @@ -441,21 +432,6 @@ func setVerificationNoMatchPolicy(cfgMap map[string]string, defaultValue string, return nil } -// NewFeatureFlagsFromConfigMap returns a Config for the given configmap -func NewFeatureFlagsFromConfigMap(config *corev1.ConfigMap) (*FeatureFlags, error) { - return NewFeatureFlagsFromMap(config.Data) -} - -// GetVerificationNoMatchPolicy returns the "trusted-resources-verification-no-match-policy" value -func GetVerificationNoMatchPolicy(ctx context.Context) string { - return FromContextOrDefaults(ctx).FeatureFlags.VerificationNoMatchPolicy -} - -// IsSpireEnabled checks if non-falsifiable provenance is enforced through SPIRE -func IsSpireEnabled(ctx context.Context) bool { - return FromContextOrDefaults(ctx).FeatureFlags.EnforceNonfalsifiability == EnforceNonfalsifiabilityWithSpire -} - type PerFeatureFlag struct { // Name of the feature flag Name string diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/featureflags_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/featureflags_validation.go index 92ca4f2b..66256a34 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/featureflags_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/featureflags_validation.go @@ -1,3 +1,5 @@ +//go:build !disable_tls + /* Copyright 2021 The Tekton Authors diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics.go index f86d4a13..3941d084 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics.go @@ -18,7 +18,6 @@ package config import ( corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/metrics" ) const ( @@ -109,12 +108,6 @@ type Metrics struct { ThrottleWithNamespace bool } -// GetMetricsConfigName returns the name of the configmap containing all -// customizations for the storage bucket. -func GetMetricsConfigName() string { - return metrics.ConfigMapName() -} - // Equals returns true if two Configs are identical func (cfg *Metrics) Equals(other *Metrics) bool { if cfg == nil && other == nil { diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics_notls.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics_notls.go new file mode 100644 index 00000000..ffab8f5f --- /dev/null +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics_notls.go @@ -0,0 +1,7 @@ +//go:build disable_tls + +package config + +// GetMetricsConfigName returns the name of the configmap containing all +// customizations for the storage bucket. +func GetMetricsConfigName() string { panic("not supported when tls is disabled") } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics_tls.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics_tls.go new file mode 100644 index 00000000..549ba350 --- /dev/null +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/metrics_tls.go @@ -0,0 +1,31 @@ +//go:build !disable_tls + +package config + +import ( + "context" + + corev1 "k8s.io/api/core/v1" + "knative.dev/pkg/metrics" +) + +// GetMetricsConfigName returns the name of the configmap containing all +// customizations for the storage bucket. +func GetMetricsConfigName() string { + return metrics.ConfigMapName() +} + +// NewFeatureFlagsFromConfigMap returns a Config for the given configmap +func NewFeatureFlagsFromConfigMap(config *corev1.ConfigMap) (*FeatureFlags, error) { + return NewFeatureFlagsFromMap(config.Data) +} + +// GetVerificationNoMatchPolicy returns the "trusted-resources-verification-no-match-policy" value +func GetVerificationNoMatchPolicy(ctx context.Context) string { + return FromContextOrDefaults(ctx).FeatureFlags.VerificationNoMatchPolicy +} + +// IsSpireEnabled checks if non-falsifiable provenance is enforced through SPIRE +func IsSpireEnabled(ctx context.Context) bool { + return FromContextOrDefaults(ctx).FeatureFlags.EnforceNonfalsifiability == EnforceNonfalsifiabilityWithSpire +} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/spire_config.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/spire_config.go index 4a293f04..af876437 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/spire_config.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/spire_config.go @@ -1,3 +1,5 @@ +//go:build !disable_tls + /* Copyright 2022 The Tekton Authors diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/store.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/store.go index a46de411..c2bc7e46 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/store.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/store.go @@ -1,3 +1,5 @@ +//go:build !disable_tls + /* Copyright 2019 The Tekton Authors @@ -28,12 +30,13 @@ type cfgKey struct{} // Config holds the collection of configurations that we attach to contexts. // +k8s:deepcopy-gen=false type Config struct { - Defaults *Defaults - FeatureFlags *FeatureFlags - Metrics *Metrics - SpireConfig *sc.SpireConfig - Events *Events - Tracing *Tracing + Defaults *Defaults + FeatureFlags *FeatureFlags + Metrics *Metrics + SpireConfig *sc.SpireConfig + Events *Events + Tracing *Tracing + WaitExponentialBackoff *WaitExponentialBackoff } // FromContext extracts a Config from the provided context. @@ -53,12 +56,13 @@ func FromContextOrDefaults(ctx context.Context) *Config { } return &Config{ - Defaults: DefaultConfig.DeepCopy(), - FeatureFlags: DefaultFeatureFlags.DeepCopy(), - Metrics: DefaultMetrics.DeepCopy(), - SpireConfig: DefaultSpire.DeepCopy(), - Events: DefaultEvents.DeepCopy(), - Tracing: DefaultTracing.DeepCopy(), + Defaults: DefaultConfig.DeepCopy(), + FeatureFlags: DefaultFeatureFlags.DeepCopy(), + Metrics: DefaultMetrics.DeepCopy(), + SpireConfig: DefaultSpire.DeepCopy(), + Events: DefaultEvents.DeepCopy(), + Tracing: DefaultTracing.DeepCopy(), + WaitExponentialBackoff: DefaultWaitExponentialBackoff.DeepCopy(), } } @@ -81,12 +85,13 @@ func NewStore(logger configmap.Logger, onAfterStore ...func(name string, value i "defaults/features/artifacts", logger, configmap.Constructors{ - GetDefaultsConfigName(): NewDefaultsFromConfigMap, - GetFeatureFlagsConfigName(): NewFeatureFlagsFromConfigMap, - GetMetricsConfigName(): NewMetricsFromConfigMap, - GetSpireConfigName(): NewSpireConfigFromConfigMap, - GetEventsConfigName(): NewEventsFromConfigMap, - GetTracingConfigName(): NewTracingFromConfigMap, + GetDefaultsConfigName(): NewDefaultsFromConfigMap, + GetFeatureFlagsConfigName(): NewFeatureFlagsFromConfigMap, + GetMetricsConfigName(): NewMetricsFromConfigMap, + GetSpireConfigName(): NewSpireConfigFromConfigMap, + GetEventsConfigName(): NewEventsFromConfigMap, + GetTracingConfigName(): NewTracingFromConfigMap, + GetWaitExponentialBackoffConfigName(): NewWaitExponentialBackoffFromConfigMap, }, onAfterStore..., ), @@ -127,13 +132,18 @@ func (s *Store) Load() *Config { if events == nil { events = DefaultEvents.DeepCopy() } + waitExponentialBackoff := s.UntypedLoad(GetWaitExponentialBackoffConfigName()) + if waitExponentialBackoff == nil { + waitExponentialBackoff = DefaultWaitExponentialBackoff.DeepCopy() + } return &Config{ - Defaults: defaults.(*Defaults).DeepCopy(), - FeatureFlags: featureFlags.(*FeatureFlags).DeepCopy(), - Metrics: metrics.(*Metrics).DeepCopy(), - Tracing: tracing.(*Tracing).DeepCopy(), - SpireConfig: spireconfig.(*sc.SpireConfig).DeepCopy(), - Events: events.(*Events).DeepCopy(), + Defaults: defaults.(*Defaults).DeepCopy(), + FeatureFlags: featureFlags.(*FeatureFlags).DeepCopy(), + Metrics: metrics.(*Metrics).DeepCopy(), + Tracing: tracing.(*Tracing).DeepCopy(), + SpireConfig: spireconfig.(*sc.SpireConfig).DeepCopy(), + Events: events.(*Events).DeepCopy(), + WaitExponentialBackoff: waitExponentialBackoff.(*WaitExponentialBackoff).DeepCopy(), } } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/wait_exponential_backoff.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/wait_exponential_backoff.go new file mode 100644 index 00000000..69f4cdc6 --- /dev/null +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/wait_exponential_backoff.go @@ -0,0 +1,138 @@ +/* +Copyright 2025 The Tekton Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package config + +import ( + "fmt" + "os" + "strconv" + "time" + + corev1 "k8s.io/api/core/v1" +) + +const ( + waitExponentialBackoffDurationKey = "duration" + waitExponentialBackoffFactorKey = "factor" + waitExponentialBackoffJitterKey = "jitter" + waitExponentialBackoffStepsKey = "steps" + waitExponentialBackoffCapKey = "cap" + + DefaultWaitExponentialBackoffDuration = "1s" + DefaultWaitExponentialBackoffFactor = 2.0 + DefaultWaitExponentialBackoffJitter = 0.0 + DefaultWaitExponentialBackoffSteps = 10 + DefaultWaitExponentialBackoffCap = "60s" +) + +// DefaultWaitExponentialBackoff holds all the default configurations for wait-exponential-backoff +var DefaultWaitExponentialBackoff, _ = newWaitExponentialBackoffFromMap(map[string]string{}) + +// WaitExponentialBackoff holds the configurations for exponential backoff +// +k8s:deepcopy-gen=true +type WaitExponentialBackoff struct { + Duration time.Duration + Factor float64 + Jitter float64 + Steps int + Cap time.Duration +} + +// Equals returns true if two Configs are identical +func (cfg *WaitExponentialBackoff) Equals(other *WaitExponentialBackoff) bool { + if cfg == nil && other == nil { + return true + } + if cfg == nil || other == nil { + return false + } + return other.Duration == cfg.Duration && + other.Factor == cfg.Factor && + other.Jitter == cfg.Jitter && + other.Steps == cfg.Steps && + other.Cap == cfg.Cap +} + +// GetWaitExponentialBackoffConfigName returns the name of the configmap containing all customizations for wait-exponential-backoff +func GetWaitExponentialBackoffConfigName() string { + if e := os.Getenv("CONFIG_WAIT_EXPONENTIAL_BACKOFF_NAME"); e != "" { + return e + } + return "config-wait-exponential-backoff" +} + +// newWaitExponentialBackoffFromMap returns a Config given a map from ConfigMap +func newWaitExponentialBackoffFromMap(config map[string]string) (*WaitExponentialBackoff, error) { + w := WaitExponentialBackoff{} + + durationStr := DefaultWaitExponentialBackoffDuration + if v, ok := config[waitExponentialBackoffDurationKey]; ok { + durationStr = v + } + dur, err := time.ParseDuration(durationStr) + if err != nil { + return nil, fmt.Errorf("failed parsing duration %q: %w", durationStr, err) + } + w.Duration = dur + + factor := DefaultWaitExponentialBackoffFactor + if v, ok := config[waitExponentialBackoffFactorKey]; ok { + f, err := strconv.ParseFloat(v, 64) + if err != nil { + return nil, fmt.Errorf("failed parsing factor %q: %w", v, err) + } + factor = f + } + w.Factor = factor + + jitter := DefaultWaitExponentialBackoffJitter + if v, ok := config[waitExponentialBackoffJitterKey]; ok { + j, err := strconv.ParseFloat(v, 64) + if err != nil { + return nil, fmt.Errorf("failed parsing jitter %q: %w", v, err) + } + jitter = j + } + w.Jitter = jitter + + steps := DefaultWaitExponentialBackoffSteps + if v, ok := config[waitExponentialBackoffStepsKey]; ok { + s, err := strconv.Atoi(v) + if err != nil { + return nil, fmt.Errorf("failed parsing steps %q: %w", v, err) + } + steps = s + } + w.Steps = steps + + capStr := DefaultWaitExponentialBackoffCap + if v, ok := config[waitExponentialBackoffCapKey]; ok { + capStr = v + } + capDur, err := time.ParseDuration(capStr) + if err != nil { + return nil, fmt.Errorf("failed parsing cap %q: %w", capStr, err) + } + w.Cap = capDur + + return &w, nil +} + +// NewWaitExponentialBackoffFromConfigMap returns a Config given a ConfigMap +func NewWaitExponentialBackoffFromConfigMap(config *corev1.ConfigMap) (*WaitExponentialBackoff, error) { + return newWaitExponentialBackoffFromMap(config.Data) +} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/zz_generated.deepcopy.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/zz_generated.deepcopy.go index b670e280..12ceac04 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/config/zz_generated.deepcopy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/config/zz_generated.deepcopy.go @@ -134,3 +134,19 @@ func (in *Tracing) DeepCopy() *Tracing { in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WaitExponentialBackoff) DeepCopyInto(out *WaitExponentialBackoff) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WaitExponentialBackoff. +func (in *WaitExponentialBackoff) DeepCopy() *WaitExponentialBackoff { + if in == nil { + return nil + } + out := new(WaitExponentialBackoff) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/controller.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/controller.go index 5f155007..a5b2580c 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/controller.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/controller.go @@ -29,9 +29,6 @@ const ( // TaskControllerName holds the name of the Task controller TaskControllerName = "Task" - // ClusterTaskControllerName holds the name of the Task controller - ClusterTaskControllerName = "ClusterTask" - // RunControllerName holds the name of the Custom Task controller RunControllerName = "Run" diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/template.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/template.go index 6bc37fec..5d23e967 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/template.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/template.go @@ -22,6 +22,9 @@ import ( corev1 "k8s.io/api/core/v1" ) +// +listType=atomic +type Volumes []corev1.Volume + // Template holds pod specific configuration // +k8s:deepcopy-gen=true // +k8s:openapi-gen=true @@ -44,22 +47,30 @@ type Template struct { // +listType=atomic Tolerations []corev1.Toleration `json:"tolerations,omitempty"` - // If specified, the pod's scheduling constraints + // If specified, the pod's scheduling constraints. + // See Pod.spec.affinity (API version: v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Affinity *corev1.Affinity `json:"affinity,omitempty"` // SecurityContext holds pod-level security attributes and common container settings. // Optional: Defaults to empty. See type description for default values of each field. + // See Pod.spec.securityContext (API version: v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless SecurityContext *corev1.PodSecurityContext `json:"securityContext,omitempty"` // List of volumes that can be mounted by containers belonging to the pod. // More info: https://kubernetes.io/docs/concepts/storage/volumes + // See Pod.spec.volumes (API version: v1) // +optional // +patchMergeKey=name // +patchStrategy=merge,retainKeys - // +listType=atomic - Volumes []corev1.Volume `json:"volumes,omitempty" patchMergeKey:"name" patchStrategy:"merge,retainKeys" protobuf:"bytes,1,rep,name=volumes"` + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + Volumes Volumes `json:"volumes,omitempty" patchMergeKey:"name" patchStrategy:"merge,retainKeys" protobuf:"bytes,1,rep,name=volumes"` // RuntimeClassName refers to a RuntimeClass object in the node.k8s.io // group, which should be used to run this pod. If no RuntimeClass resource diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/zz_generated.deepcopy.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/zz_generated.deepcopy.go index 098b0fbe..350f3b7e 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/zz_generated.deepcopy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/pod/zz_generated.deepcopy.go @@ -106,7 +106,7 @@ func (in *Template) DeepCopyInto(out *Template) { } if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes - *out = make([]v1.Volume, len(*in)) + *out = make(Volumes, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/register.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/register.go index 9971a9b7..40662f31 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/register.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/register.go @@ -22,9 +22,6 @@ const ( // GroupName is the Kubernetes resource group name for Pipeline types. GroupName = "tekton.dev" - // ClusterTaskLabelKey is used as the label identifier for a ClusterTask - ClusterTaskLabelKey = GroupName + "/clusterTask" - // StepActionLabelKey is used as the label identifier for a StepAction StepActionLabelKey = GroupName + "/stepAction" @@ -71,11 +68,6 @@ var ( Group: GroupName, Resource: "tasks", } - // ClusterTaskResource represents a Tekton ClusterTask - ClusterTaskResource = schema.GroupResource{ - Group: GroupName, - Resource: "clustertasks", - } // TaskRunResource represents a Tekton TaskRun TaskRunResource = schema.GroupResource{ Group: GroupName, diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/artifact_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/artifact_types.go index 6281c3e1..54538faf 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/artifact_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/artifact_types.go @@ -48,7 +48,9 @@ type TaskRunStepArtifact = Artifact // a task run or a similar process. Artifacts in this context are units of data or resources // that the process either consumes as input or produces as output. type Artifacts struct { - Inputs []Artifact `json:"inputs,omitempty"` + // +listType=atomic + Inputs []Artifact `json:"inputs,omitempty"` + // +listType=atomic Outputs []Artifact `json:"outputs,omitempty"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_types.go index 2dc4a898..3e20e349 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_types.go @@ -140,12 +140,9 @@ type Step struct { Ref *Ref `json:"ref,omitempty"` // Params declares parameters passed to this step action. // +optional - // +listType=atomic Params Params `json:"params,omitempty"` // Results declares StepResults produced by the Step. // - // This is field is at an ALPHA stability level and gated by "enable-step-actions" feature flag. - // // It can be used in an inlined Step when used to store Results to $(step.results.resultName.path). // It cannot be used when referencing StepActions using [v1.Step.Ref]. // The Results declared by the StepActions will be stored here instead. diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_validation.go index ec55189b..becf3541 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/container_validation.go @@ -21,13 +21,27 @@ import ( "errors" "fmt" "regexp" + "slices" "strings" + "time" + "github.com/tektoncd/pipeline/internal/artifactref" "github.com/tektoncd/pipeline/pkg/apis/config" + "github.com/tektoncd/pipeline/pkg/apis/pipeline" + "github.com/tektoncd/pipeline/pkg/internal/resultref" "k8s.io/apimachinery/pkg/util/validation" "knative.dev/pkg/apis" ) +// Validate ensures that a supplied Ref field is populated +// correctly. No errors are returned for a nil Ref. +func (ref *Ref) Validate(ctx context.Context) (errs *apis.FieldError) { + if ref == nil { + return errs + } + return validateRef(ctx, ref.Name, ref.Resolver, ref.Params) +} + func validateRef(ctx context.Context, refName string, refResolver ResolverName, refParams Params) (errs *apis.FieldError) { switch { case refResolver != "" || refParams != nil: @@ -80,15 +94,6 @@ func validateRef(ctx context.Context, refName string, refResolver ResolverName, return errs } -// Validate ensures that a supplied Ref field is populated -// correctly. No errors are returned for a nil Ref. -func (ref *Ref) Validate(ctx context.Context) (errs *apis.FieldError) { - if ref == nil { - return errs - } - return validateRef(ctx, ref.Name, ref.Resolver, ref.Params) -} - // RefNameLikeUrl checks if the name is url parsable and returns an error if it isn't. func RefNameLikeUrl(name string) error { schemeRegex := regexp.MustCompile(`[\w-]+:\/\/*`) @@ -97,3 +102,288 @@ func RefNameLikeUrl(name string) error { } return nil } + +// Validate implements apis.Validatable +func (s *Step) Validate(ctx context.Context) (errs *apis.FieldError) { + if err := validateArtifactsReferencesInStep(ctx, s); err != nil { + return err + } + + if s.Ref != nil { + errs = errs.Also(s.Ref.Validate(ctx)) + if s.Image != "" { + errs = errs.Also(&apis.FieldError{ + Message: "image cannot be used with Ref", + Paths: []string{"image"}, + }) + } + if len(s.Command) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "command cannot be used with Ref", + Paths: []string{"command"}, + }) + } + if len(s.Args) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "args cannot be used with Ref", + Paths: []string{"args"}, + }) + } + if s.Script != "" { + errs = errs.Also(&apis.FieldError{ + Message: "script cannot be used with Ref", + Paths: []string{"script"}, + }) + } + if s.WorkingDir != "" { + errs = errs.Also(&apis.FieldError{ + Message: "working dir cannot be used with Ref", + Paths: []string{"workingDir"}, + }) + } + if s.Env != nil { + errs = errs.Also(&apis.FieldError{ + Message: "env cannot be used with Ref", + Paths: []string{"env"}, + }) + } + if len(s.VolumeMounts) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "volumeMounts cannot be used with Ref", + Paths: []string{"volumeMounts"}, + }) + } + if len(s.Results) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "results cannot be used with Ref", + Paths: []string{"results"}, + }) + } + } else { + if len(s.Params) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "params cannot be used without Ref", + Paths: []string{"params"}, + }) + } + if s.Image == "" { + errs = errs.Also(apis.ErrMissingField("Image")) + } + + if s.Script != "" { + if len(s.Command) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "script cannot be used with command", + Paths: []string{"script"}, + }) + } + } + } + + if s.Name != "" { + if e := validation.IsDNS1123Label(s.Name); len(e) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("invalid value %q", s.Name), + Paths: []string{"name"}, + Details: "Task step name must be a valid DNS Label, For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + }) + } + } + + if s.Timeout != nil { + if s.Timeout.Duration < time.Duration(0) { + return apis.ErrInvalidValue(s.Timeout.Duration, "negative timeout") + } + } + + for j, vm := range s.VolumeMounts { + if strings.HasPrefix(vm.MountPath, "/tekton/") && + !strings.HasPrefix(vm.MountPath, "/tekton/home") { + errs = errs.Also(apis.ErrGeneric(fmt.Sprintf("volumeMount cannot be mounted under /tekton/ (volumeMount %q mounted at %q)", vm.Name, vm.MountPath), "mountPath").ViaFieldIndex("volumeMounts", j)) + } + if strings.HasPrefix(vm.Name, "tekton-internal-") { + errs = errs.Also(apis.ErrGeneric(fmt.Sprintf(`volumeMount name %q cannot start with "tekton-internal-"`, vm.Name), "name").ViaFieldIndex("volumeMounts", j)) + } + } + + if s.OnError != "" { + if !isParamRefs(string(s.OnError)) && s.OnError != Continue && s.OnError != StopAndFail { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("invalid value: \"%v\"", s.OnError), + Paths: []string{"onError"}, + Details: "Task step onError must be either \"continue\" or \"stopAndFail\"", + }) + } + } + + if s.Script != "" { + cleaned := strings.TrimSpace(s.Script) + if strings.HasPrefix(cleaned, "#!win") { + errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "windows script support", config.AlphaAPIFields).ViaField("script")) + } + } + + // StdoutConfig is an alpha feature and will fail validation if it's used in a task spec + // when the enable-api-fields feature gate is not "alpha". + if s.StdoutConfig != nil { + errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "step stdout stream support", config.AlphaAPIFields).ViaField("stdoutconfig")) + } + // StderrConfig is an alpha feature and will fail validation if it's used in a task spec + // when the enable-api-fields feature gate is not "alpha". + if s.StderrConfig != nil { + errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "step stderr stream support", config.AlphaAPIFields).ViaField("stderrconfig")) + } + + // Validate usage of step result reference. + // Referencing previous step's results are only allowed in `env`, `command` and `args`. + errs = errs.Also(validateStepResultReference(s)) + + // Validate usage of step artifacts output reference + // Referencing previous step's results are only allowed in `env`, `command` and `args`, `script`. + errs = errs.Also(validateStepArtifactsReference(s)) + return errs +} + +// isParamRefs attempts to check if a specified string looks like it contains any parameter reference +// This is useful to make sure the specified value looks like a Parameter Reference before performing any strict validation +func isParamRefs(s string) bool { + return strings.HasPrefix(s, "$("+ParamsPrefix) +} + +func validateArtifactsReferencesInStep(ctx context.Context, s *Step) *apis.FieldError { + cfg := config.FromContextOrDefaults(ctx) + if cfg == nil || cfg.FeatureFlags == nil { + cfg = &config.Config{ + FeatureFlags: &config.FeatureFlags{}, + } + } + + if !cfg.FeatureFlags.EnableArtifacts { + var t []string + if s.Script != "" { + t = append(t, s.Script) + } + if len(s.Command) > 0 { + t = append(t, s.Command...) + } + if len(s.Args) > 0 { + t = append(t, s.Args...) + } + if s.Env != nil { + for _, e := range s.Env { + if e.Value != "" { + t = append(t, e.Value) + } + } + } + if slices.ContainsFunc(t, stepArtifactReferenceExists) || slices.ContainsFunc(t, taskArtifactReferenceExists) { + return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true to use artifacts feature.", config.EnableArtifacts), "") + } + } + return nil +} + +func stepArtifactReferenceExists(src string) bool { + return len(artifactref.StepArtifactRegex.FindAllStringSubmatch(src, -1)) > 0 || strings.Contains(src, "$("+artifactref.StepArtifactPathPattern+")") +} + +func taskArtifactReferenceExists(src string) bool { + return len(artifactref.TaskArtifactRegex.FindAllStringSubmatch(src, -1)) > 0 || strings.Contains(src, "$("+artifactref.TaskArtifactPathPattern+")") +} + +func validateStepResultReference(s *Step) (errs *apis.FieldError) { + errs = errs.Also(errorIfStepResultReferencedInField(s.Name, "name")) + errs = errs.Also(errorIfStepResultReferencedInField(s.Image, "image")) + errs = errs.Also(errorIfStepResultReferencedInField(s.Script, "script")) + errs = errs.Also(errorIfStepResultReferencedInField(string(s.ImagePullPolicy), "imagePullPolicy")) + errs = errs.Also(errorIfStepResultReferencedInField(s.WorkingDir, "workingDir")) + for _, e := range s.EnvFrom { + errs = errs.Also(errorIfStepResultReferencedInField(e.Prefix, "envFrom.prefix")) + if e.ConfigMapRef != nil { + errs = errs.Also(errorIfStepResultReferencedInField(e.ConfigMapRef.LocalObjectReference.Name, "envFrom.configMapRef")) + } + if e.SecretRef != nil { + errs = errs.Also(errorIfStepResultReferencedInField(e.SecretRef.LocalObjectReference.Name, "envFrom.secretRef")) + } + } + for _, v := range s.VolumeMounts { + errs = errs.Also(errorIfStepResultReferencedInField(v.Name, "volumeMounts.name")) + errs = errs.Also(errorIfStepResultReferencedInField(v.MountPath, "volumeMounts.mountPath")) + errs = errs.Also(errorIfStepResultReferencedInField(v.SubPath, "volumeMounts.subPath")) + } + for _, v := range s.VolumeDevices { + errs = errs.Also(errorIfStepResultReferencedInField(v.Name, "volumeDevices.name")) + errs = errs.Also(errorIfStepResultReferencedInField(v.DevicePath, "volumeDevices.devicePath")) + } + return errs +} + +func errorIfStepResultReferencedInField(value, fieldName string) (errs *apis.FieldError) { + matches := resultref.StepResultRegex.FindAllStringSubmatch(value, -1) + if len(matches) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "stepResult substitutions are only allowed in env, command and args. Found usage in", + Paths: []string{fieldName}, + }) + } + return errs +} + +func validateStepArtifactsReference(s *Step) (errs *apis.FieldError) { + errs = errs.Also(errorIfStepArtifactReferencedInField(s.Name, "name")) + errs = errs.Also(errorIfStepArtifactReferencedInField(s.Image, "image")) + errs = errs.Also(errorIfStepArtifactReferencedInField(string(s.ImagePullPolicy), "imagePullPolicy")) + errs = errs.Also(errorIfStepArtifactReferencedInField(s.WorkingDir, "workingDir")) + for _, e := range s.EnvFrom { + errs = errs.Also(errorIfStepArtifactReferencedInField(e.Prefix, "envFrom.prefix")) + if e.ConfigMapRef != nil { + errs = errs.Also(errorIfStepArtifactReferencedInField(e.ConfigMapRef.LocalObjectReference.Name, "envFrom.configMapRef")) + } + if e.SecretRef != nil { + errs = errs.Also(errorIfStepArtifactReferencedInField(e.SecretRef.LocalObjectReference.Name, "envFrom.secretRef")) + } + } + for _, v := range s.VolumeMounts { + errs = errs.Also(errorIfStepArtifactReferencedInField(v.Name, "volumeMounts.name")) + errs = errs.Also(errorIfStepArtifactReferencedInField(v.MountPath, "volumeMounts.mountPath")) + errs = errs.Also(errorIfStepArtifactReferencedInField(v.SubPath, "volumeMounts.subPath")) + } + for _, v := range s.VolumeDevices { + errs = errs.Also(errorIfStepArtifactReferencedInField(v.Name, "volumeDevices.name")) + errs = errs.Also(errorIfStepArtifactReferencedInField(v.DevicePath, "volumeDevices.devicePath")) + } + return errs +} + +func errorIfStepArtifactReferencedInField(value, fieldName string) (errs *apis.FieldError) { + if stepArtifactReferenceExists(value) { + errs = errs.Also(&apis.FieldError{ + Message: "stepArtifact substitutions are only allowed in env, command, args and script. Found usage in", + Paths: []string{fieldName}, + }) + } + return errs +} + +func (sc *Sidecar) Validate(ctx context.Context) (errs *apis.FieldError) { + if sc.Name == pipeline.ReservedResultsSidecarName { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("Invalid: cannot use reserved sidecar name %v ", sc.Name), + Paths: []string{"name"}, + }) + } + + if sc.Image == "" { + errs = errs.Also(apis.ErrMissingField("image")) + } + + if sc.Script != "" { + if len(sc.Command) > 0 { + errs = errs.Also(&apis.FieldError{ + Message: "script cannot be used with command", + Paths: []string{"script"}, + }) + } + } + return errs +} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/matrix_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/matrix_types.go index f51a0ac4..6de9aacd 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/matrix_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/matrix_types.go @@ -16,10 +16,10 @@ package v1 import ( "context" "fmt" + "maps" "sort" "github.com/tektoncd/pipeline/pkg/apis/config" - "golang.org/x/exp/maps" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/utils/strings/slices" "knative.dev/pkg/apis" @@ -31,16 +31,15 @@ type Matrix struct { // Params takes only `Parameters` of type `"array"` // Each array element is supplied to the `PipelineTask` by substituting `params` of type `"string"` in the underlying `Task`. // The names of the `params` in the `Matrix` must match the names of the `params` in the underlying `Task` that they will be substituting. - // +listType=atomic Params Params `json:"params,omitempty"` // Include is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix. // +optional - // +listType=atomic Include IncludeParamsList `json:"include,omitempty"` } // IncludeParamsList is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix. +// +listType=atomic type IncludeParamsList []IncludeParams // IncludeParams allows passing in a specific combinations of Parameters into the Matrix. @@ -50,7 +49,6 @@ type IncludeParams struct { // Params takes only `Parameters` of type `"string"` // The names of the `params` must match the names of the `params` in the underlying `Task` - // +listType=atomic Params Params `json:"params,omitempty"` } @@ -236,7 +234,9 @@ func (m *Matrix) countGeneratedCombinationsFromParams() int { } count := 1 for _, param := range m.Params { - count *= len(param.Value.ArrayVal) + if len(param.Value.ArrayVal) > 0 { + count *= len(param.Value.ArrayVal) + } } return count } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/openapi_generated.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/openapi_generated.go index d05c2178..f8c9053b 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/openapi_generated.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/openapi_generated.go @@ -19,8 +19,6 @@ limitations under the License. // Code generated by openapi-gen. DO NOT EDIT. -// This file was autogenerated by openapi-gen. Do not edit it manually! - package v1 import ( @@ -248,26 +246,25 @@ func schema_pkg_apis_pipeline_pod_Template(ref common.ReferenceCallback) common. }, "affinity": { SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's scheduling constraints", + Description: "If specified, the pod's scheduling constraints. See Pod.spec.affinity (API version: v1)", Ref: ref("k8s.io/api/core/v1.Affinity"), }, }, "securityContext": { SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", + Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. See Pod.spec.securityContext (API version: v1)", Ref: ref("k8s.io/api/core/v1.PodSecurityContext"), }, }, "volumes": { VendorExtensible: spec.VendorExtensible{ Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", "x-kubernetes-patch-merge-key": "name", "x-kubernetes-patch-strategy": "merge,retainKeys", }, }, SchemaProps: spec.SchemaProps{ - Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", + Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes See Pod.spec.volumes (API version: v1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -485,6 +482,11 @@ func schema_pkg_apis_pipeline_v1_Artifacts(ref common.ReferenceCallback) common. Type: []string{"object"}, Properties: map[string]spec.Schema{ "inputs": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, SchemaProps: spec.SchemaProps{ Type: []string{"array"}, Items: &spec.SchemaOrArray{ @@ -498,6 +500,11 @@ func schema_pkg_apis_pipeline_v1_Artifacts(ref common.ReferenceCallback) common. }, }, "outputs": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, SchemaProps: spec.SchemaProps{ Type: []string{"array"}, Items: &spec.SchemaOrArray{ @@ -617,11 +624,6 @@ func schema_pkg_apis_pipeline_v1_EmbeddedTask(ref common.ReferenceCallback) comm }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of input parameters required to run the task. Params must be supplied as inputs in TaskRuns unless they declare a default value.", Type: []string{"array"}, @@ -669,13 +671,8 @@ func schema_pkg_apis_pipeline_v1_EmbeddedTask(ref common.ReferenceCallback) comm }, }, "volumes": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ - Description: "Volumes is a collection of volumes that are available to mount into the steps of the build.", + Description: "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -773,11 +770,6 @@ func schema_pkg_apis_pipeline_v1_IncludeParams(ref common.ReferenceCallback) com }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params takes only `Parameters` of type `\"string\"` The names of the `params` must match the names of the `params` in the underlying `Task`", Type: []string{"array"}, @@ -807,11 +799,6 @@ func schema_pkg_apis_pipeline_v1_Matrix(ref common.ReferenceCallback) common.Ope Type: []string{"object"}, Properties: map[string]spec.Schema{ "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of parameters used to fan out the pipelineTask Params takes only `Parameters` of type `\"array\"` Each array element is supplied to the `PipelineTask` by substituting `params` of type `\"string\"` in the underlying `Task`. The names of the `params` in the `Matrix` must match the names of the `params` in the underlying `Task` that they will be substituting.", Type: []string{"array"}, @@ -826,11 +813,6 @@ func schema_pkg_apis_pipeline_v1_Matrix(ref common.ReferenceCallback) common.Ope }, }, "include": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Include is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix.", Type: []string{"array"}, @@ -1366,16 +1348,11 @@ func schema_pkg_apis_pipeline_v1_PipelineRunSpec(ref common.ReferenceCallback) c }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.PipelineSpec"), }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of parameter names and values.", Type: []string{"array"}, @@ -1538,7 +1515,7 @@ func schema_pkg_apis_pipeline_v1_PipelineRunStatus(ref common.ReferenceCallback) }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "PipelineRunSpec contains the exact spec used to instantiate the run", + Description: "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.PipelineSpec"), }, }, @@ -1656,7 +1633,7 @@ func schema_pkg_apis_pipeline_v1_PipelineRunStatusFields(ref common.ReferenceCal }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "PipelineRunSpec contains the exact spec used to instantiate the run", + Description: "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.PipelineSpec"), }, }, @@ -1822,11 +1799,6 @@ func schema_pkg_apis_pipeline_v1_PipelineSpec(ref common.ReferenceCallback) comm }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params declares a list of input parameters that must be supplied when this Pipeline is run.", Type: []string{"array"}, @@ -1941,7 +1913,7 @@ func schema_pkg_apis_pipeline_v1_PipelineTask(ref common.ReferenceCallback) comm }, "taskSpec": { SchemaProps: spec.SchemaProps{ - Description: "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.EmbeddedTask"), }, }, @@ -1987,11 +1959,6 @@ func schema_pkg_apis_pipeline_v1_PipelineTask(ref common.ReferenceCallback) comm }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Parameters declares parameters passed to this task.", Type: []string{"array"}, @@ -2044,7 +2011,7 @@ func schema_pkg_apis_pipeline_v1_PipelineTask(ref common.ReferenceCallback) comm }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.PipelineSpec"), }, }, @@ -2392,7 +2359,7 @@ func schema_pkg_apis_pipeline_v1_RefSource(ref common.ReferenceCallback) common. }, "entryPoint": { SchemaProps: spec.SchemaProps{ - Description: "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.8/git-clone.yaml\"", + Description: "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.10/git-clone.yaml\"", Type: []string{"string"}, Format: "", }, @@ -2418,11 +2385,6 @@ func schema_pkg_apis_pipeline_v1_ResolverRef(ref common.ReferenceCallback) commo }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params contains the parameters used to identify the referenced Tekton resource. Example entries might include \"repo\" or \"path\" but the set of params ultimately depends on the chosen resolver.", Type: []string{"array"}, @@ -3113,11 +3075,6 @@ func schema_pkg_apis_pipeline_v1_Step(ref common.ReferenceCallback) common.OpenA }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params declares parameters passed to this step action.", Type: []string{"array"}, @@ -3138,7 +3095,7 @@ func schema_pkg_apis_pipeline_v1_Step(ref common.ReferenceCallback) common.OpenA }, }, SchemaProps: spec.SchemaProps{ - Description: "Results declares StepResults produced by the Step.\n\nThis is field is at an ALPHA stability level and gated by \"enable-step-actions\" feature flag.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", + Description: "Results declares StepResults produced by the Step.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -3197,7 +3154,7 @@ func schema_pkg_apis_pipeline_v1_StepResult(ref common.ReferenceCallback) common return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ - Description: "StepResult used to describe the Results of a Step.\n\nThis is field is at an BETA stability level and gated by \"enable-step-actions\" feature flag.", + Description: "StepResult used to describe the Results of a Step.", Type: []string{"object"}, Properties: map[string]spec.Schema{ "name": { @@ -3971,11 +3928,6 @@ func schema_pkg_apis_pipeline_v1_TaskRunSpec(ref common.ReferenceCallback) commo }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Type: []string{"array"}, Items: &spec.SchemaOrArray{ @@ -4003,7 +3955,7 @@ func schema_pkg_apis_pipeline_v1_TaskRunSpec(ref common.ReferenceCallback) commo }, "taskSpec": { SchemaProps: spec.SchemaProps{ - Description: "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.TaskSpec"), }, }, @@ -4201,11 +4153,6 @@ func schema_pkg_apis_pipeline_v1_TaskRunStatus(ref common.ReferenceCallback) com }, }, "retriesStatus": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant.", Type: []string{"array"}, @@ -4239,11 +4186,6 @@ func schema_pkg_apis_pipeline_v1_TaskRunStatus(ref common.ReferenceCallback) com }, }, "artifacts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Artifacts are the list of artifacts written out by the task's containers", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.Artifacts"), @@ -4352,11 +4294,6 @@ func schema_pkg_apis_pipeline_v1_TaskRunStatusFields(ref common.ReferenceCallbac }, }, "retriesStatus": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant.", Type: []string{"array"}, @@ -4390,11 +4327,6 @@ func schema_pkg_apis_pipeline_v1_TaskRunStatusFields(ref common.ReferenceCallbac }, }, "artifacts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Artifacts are the list of artifacts written out by the task's containers", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1.Artifacts"), @@ -4495,11 +4427,6 @@ func schema_pkg_apis_pipeline_v1_TaskSpec(ref common.ReferenceCallback) common.O Type: []string{"object"}, Properties: map[string]spec.Schema{ "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of input parameters required to run the task. Params must be supplied as inputs in TaskRuns unless they declare a default value.", Type: []string{"array"}, @@ -4547,13 +4474,8 @@ func schema_pkg_apis_pipeline_v1_TaskSpec(ref common.ReferenceCallback) common.O }, }, "volumes": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ - Description: "Volumes is a collection of volumes that are available to mount into the steps of the build.", + Description: "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -4747,7 +4669,7 @@ func schema_pkg_apis_pipeline_v1_WorkspaceBinding(ref common.ReferenceCallback) }, "volumeClaimTemplate": { SchemaProps: spec.SchemaProps{ - Description: "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun.", + Description: "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun. See PersistentVolumeClaim (API version: v1)", Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaim"), }, }, diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/param_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/param_types.go index c5973544..2d450941 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/param_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/param_types.go @@ -54,6 +54,8 @@ type ParamSpec struct { // default is set, a Task may be executed without a supplied value for the // parameter. // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Default *ParamValue `json:"default,omitempty"` // Enum declares a set of allowed param input values for tasks/pipelines that can be validated. // If Enum is not set, no input validation is performed for the param. @@ -62,6 +64,7 @@ type ParamSpec struct { } // ParamSpecs is a list of ParamSpec +// +listType=atomic type ParamSpecs []ParamSpec // PropertySpec defines the struct for object keys @@ -146,7 +149,7 @@ func (ps ParamSpecs) ValidateNoDuplicateNames() *apis.FieldError { return errs } -// validateParamEnum validates feature flag, duplication and allowed types for Param Enum +// validateParamEnums validates feature flag, duplication and allowed types for Param Enum func (ps ParamSpecs) validateParamEnums(ctx context.Context) *apis.FieldError { var errs *apis.FieldError for _, p := range ps { @@ -186,7 +189,9 @@ func findDups(vals []string) sets.String { // Param declares an ParamValues to use for the parameter called name. type Param struct { - Name string `json:"name"` + Name string `json:"name"` + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ParamValue `json:"value"` } @@ -268,6 +273,7 @@ func (p Param) ParseTaskandResultName() (string, string) { } // Params is a list of Param +// +listType=atomic type Params []Param // ExtractParamArrayLengths extract and return the lengths of all array params diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_types.go index 4d6e20d6..272a9f6e 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_types.go @@ -51,6 +51,7 @@ const ( // Pipeline describes a list of Tasks to execute. It expresses how outputs // of tasks feed into inputs of subsequent tasks. // +k8s:openapi-gen=true +// +kubebuilder:storageversion type Pipeline struct { metav1.TypeMeta `json:",inline"` // +optional @@ -114,7 +115,6 @@ type PipelineSpec struct { Tasks []PipelineTask `json:"tasks,omitempty"` // Params declares a list of input parameters that must be supplied when // this Pipeline is run. - // +listType=atomic Params ParamSpecs `json:"params,omitempty"` // Workspaces declares a set of named workspaces that are expected to be // provided by a PipelineRun. @@ -147,6 +147,8 @@ type PipelineResult struct { Description string `json:"description"` // Value the expression used to retrieve the value + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ResultValue `json:"value"` } @@ -200,8 +202,11 @@ type PipelineTask struct { // TaskSpec is a specification of a task // Specifying TaskSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // `disable-inline-spec` feature flag. + // See Task.spec (API version: tekton.dev/v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless TaskSpec *EmbeddedTask `json:"taskSpec,omitempty"` // When is a list of when expressions that need to be true for the task to run @@ -220,7 +225,6 @@ type PipelineTask struct { // Parameters declares parameters passed to this task. // +optional - // +listType=atomic Params Params `json:"params,omitempty"` // Matrix declares parameters used to fan out this task. @@ -246,8 +250,11 @@ type PipelineTask struct { // PipelineSpec is a specification of a pipeline // Note: PipelineSpec is in preview mode and not yet supported // Specifying PipelineSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // `disable-inline-spec` feature flag. + // See Pipeline.spec (API version: tekton.dev/v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless PipelineSpec *PipelineSpec `json:"pipelineSpec,omitempty"` // OnError defines the exiting behavior of a PipelineRun on error diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_validation.go index c17293a0..8d109c10 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipeline_validation.go @@ -188,18 +188,9 @@ func (pt PipelineTask) Validate(ctx context.Context) (errs *apis.FieldError) { taskKinds := map[TaskKind]bool{ "": true, NamespacedTaskKind: true, - ClusterTaskRefKind: true, } - if pt.OnError != "" { - errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "OnError", config.BetaAPIFields)) - if pt.OnError != PipelineTaskContinue && pt.OnError != PipelineTaskStopAndFail { - errs = errs.Also(apis.ErrInvalidValue(pt.OnError, "OnError", "PipelineTask OnError must be either \"continue\" or \"stopAndFail\"")) - } - if pt.OnError == PipelineTaskContinue && pt.Retries > 0 { - errs = errs.Also(apis.ErrGeneric("PipelineTask OnError cannot be set to \"continue\" when Retries is greater than 0")) - } - } + errs = errs.Also(pt.ValidateOnError(ctx)) // Pipeline task having taskRef/taskSpec with APIVersion is classified as custom task switch { @@ -217,6 +208,20 @@ func (pt PipelineTask) Validate(ctx context.Context) (errs *apis.FieldError) { return errs } +// ValidateOnError validates the OnError field of a PipelineTask +func (pt PipelineTask) ValidateOnError(ctx context.Context) (errs *apis.FieldError) { + if pt.OnError != "" && !isParamRefs(string(pt.OnError)) { + errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "OnError", config.BetaAPIFields)) + if pt.OnError != PipelineTaskContinue && pt.OnError != PipelineTaskStopAndFail { + errs = errs.Also(apis.ErrInvalidValue(pt.OnError, "OnError", "PipelineTask OnError must be either \"continue\" or \"stopAndFail\"")) + } + if pt.OnError == PipelineTaskContinue && pt.Retries > 0 { + errs = errs.Also(apis.ErrGeneric("PipelineTask OnError cannot be set to \"continue\" when Retries is greater than 0")) + } + } + return errs +} + func (pt *PipelineTask) validateMatrix(ctx context.Context) (errs *apis.FieldError) { if pt.IsMatrixed() { // This is a beta feature and will fail validation if it's used in a pipeline spec diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipelinerun_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipelinerun_types.go index f171719d..52175cab 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipelinerun_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/pipelinerun_types.go @@ -47,6 +47,7 @@ import ( // PipelineRun creates TaskRuns for Tasks in the referenced Pipeline. // // +k8s:openapi-gen=true +// +kubebuilder:storageversion type PipelineRun struct { metav1.TypeMeta `json:",inline"` // +optional @@ -250,11 +251,13 @@ type PipelineRunSpec struct { // +optional PipelineRef *PipelineRef `json:"pipelineRef,omitempty"` // Specifying PipelineSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // `disable-inline-spec` feature flag. + // See Pipeline.spec (API version: tekton.dev/v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless PipelineSpec *PipelineSpec `json:"pipelineSpec,omitempty"` // Params is a list of parameter names and values. - // +listType=atomic Params Params `json:"params,omitempty"` // Used for cancelling a pipelinerun (and maybe more later on) @@ -513,7 +516,10 @@ type PipelineRunStatusFields struct { // +listType=atomic Results []PipelineRunResult `json:"results,omitempty"` - // PipelineRunSpec contains the exact spec used to instantiate the run + // PipelineSpec contains the exact spec used to instantiate the run. + // See Pipeline.spec (API version: tekton.dev/v1) + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless PipelineSpec *PipelineSpec `json:"pipelineSpec,omitempty"` // list of tasks that were skipped due to when expressions evaluating to false @@ -586,6 +592,8 @@ type PipelineRunResult struct { Name string `json:"name"` // Value is the result returned from the execution of this PipelineRun + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ResultValue `json:"value"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/provenance.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/provenance.go index de9f2a5c..ea123433 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/provenance.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/provenance.go @@ -41,6 +41,6 @@ type RefSource struct { // EntryPoint identifies the entry point into the build. This is often a path to a // build definition file and/or a target label within that file. - // Example: "task/git-clone/0.8/git-clone.yaml" + // Example: "task/git-clone/0.10/git-clone.yaml" EntryPoint string `json:"entryPoint,omitempty"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/resolver_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/resolver_types.go index 095a9d00..66032992 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/resolver_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/resolver_types.go @@ -33,6 +33,5 @@ type ResolverRef struct { // "repo" or "path" but the set of params ultimately depends on // the chosen resolver. // +optional - // +listType=atomic Params Params `json:"params,omitempty"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_types.go index b36bf6fc..0e6d28d5 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_types.go @@ -35,12 +35,12 @@ type TaskResult struct { // Value the expression used to retrieve the value of the result from an underlying Step. // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value *ResultValue `json:"value,omitempty"` } // StepResult used to describe the Results of a Step. -// -// This is field is at an BETA stability level and gated by "enable-step-actions" feature flag. type StepResult struct { // Name the given name Name string `json:"name"` @@ -69,6 +69,8 @@ type TaskRunResult struct { Type ResultsType `json:"type,omitempty"` // Value the given value of the result + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ResultValue `json:"value"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_validation.go index 0ce08fc1..6f4298da 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/result_validation.go @@ -18,7 +18,6 @@ import ( "fmt" "regexp" - "github.com/tektoncd/pipeline/pkg/apis/config" "k8s.io/apimachinery/pkg/util/validation" "knative.dev/pkg/apis" ) @@ -67,15 +66,12 @@ func validateObjectResult(tr TaskResult) (errs *apis.FieldError) { } // validateValue validates the value of the TaskResult. -// It requires that enable-step-actions is true, the value is of type string +// It requires that the value is of type string // and format $(steps..results.) func (tr TaskResult) validateValue(ctx context.Context) (errs *apis.FieldError) { if tr.Value == nil { return nil } - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true to fetch Results from Steps using StepActions.", config.EnableStepActions)) - } if tr.Value.Type != ParamTypeString { return &apis.FieldError{ Message: fmt.Sprintf( diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/swagger.json b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/swagger.json index 73544e75..5f8710cf 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/swagger.json +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/swagger.json @@ -52,7 +52,7 @@ "type": "object", "properties": { "affinity": { - "description": "If specified, the pod's scheduling constraints", + "description": "If specified, the pod's scheduling constraints. See Pod.spec.affinity (API version: v1)", "$ref": "#/definitions/v1.Affinity" }, "automountServiceAccountToken": { @@ -125,7 +125,7 @@ "type": "string" }, "securityContext": { - "description": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", + "description": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. See Pod.spec.securityContext (API version: v1)", "$ref": "#/definitions/v1.PodSecurityContext" }, "tolerations": { @@ -147,13 +147,12 @@ "x-kubernetes-list-type": "atomic" }, "volumes": { - "description": "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", + "description": "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes See Pod.spec.volumes (API version: v1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Volume" }, - "x-kubernetes-list-type": "atomic", "x-kubernetes-patch-merge-key": "name", "x-kubernetes-patch-strategy": "merge,retainKeys" } @@ -207,14 +206,16 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Artifact" - } + }, + "x-kubernetes-list-type": "atomic" }, "outputs": { "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Artifact" - } + }, + "x-kubernetes-list-type": "atomic" } } }, @@ -279,8 +280,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "results": { "description": "Results are values that this Task can output", @@ -318,13 +318,12 @@ "x-kubernetes-list-type": "atomic" }, "volumes": { - "description": "Volumes is a collection of volumes that are available to mount into the steps of the build.", + "description": "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Volume" - }, - "x-kubernetes-list-type": "atomic" + } }, "workspaces": { "description": "Workspaces are the volumes that this Task requires.", @@ -351,8 +350,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Param" - }, - "x-kubernetes-list-type": "atomic" + } } } }, @@ -366,8 +364,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.IncludeParams" - }, - "x-kubernetes-list-type": "atomic" + } }, "params": { "description": "Params is a list of parameters used to fan out the pipelineTask Params takes only `Parameters` of type `\"array\"` Each array element is supplied to the `PipelineTask` by substituting `params` of type `\"string\"` in the underlying `Task`. The names of the `params` in the `Matrix` must match the names of the `params` in the underlying `Task` that they will be substituting.", @@ -375,8 +372,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Param" - }, - "x-kubernetes-list-type": "atomic" + } } } }, @@ -671,14 +667,13 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "pipelineRef": { "$ref": "#/definitions/v1.PipelineRef" }, "pipelineSpec": { - "description": "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1)", "$ref": "#/definitions/v1.PipelineSpec" }, "status": { @@ -759,7 +754,7 @@ "format": "int64" }, "pipelineSpec": { - "description": "PipelineRunSpec contains the exact spec used to instantiate the run", + "description": "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1)", "$ref": "#/definitions/v1.PipelineSpec" }, "provenance": { @@ -820,7 +815,7 @@ "$ref": "#/definitions/v1.Time" }, "pipelineSpec": { - "description": "PipelineRunSpec contains the exact spec used to instantiate the run", + "description": "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1)", "$ref": "#/definitions/v1.PipelineSpec" }, "provenance": { @@ -909,8 +904,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "results": { "description": "Results are values that this pipeline can output once run", @@ -971,15 +965,14 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "pipelineRef": { "description": "PipelineRef is a reference to a pipeline definition Note: PipelineRef is in preview mode and not yet supported", "$ref": "#/definitions/v1.PipelineRef" }, "pipelineSpec": { - "description": "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1)", "$ref": "#/definitions/v1.PipelineSpec" }, "retries": { @@ -1001,7 +994,7 @@ "$ref": "#/definitions/v1.TaskRef" }, "taskSpec": { - "description": "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1)", "$ref": "#/definitions/v1.EmbeddedTask" }, "timeout": { @@ -1192,7 +1185,7 @@ } }, "entryPoint": { - "description": "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.8/git-clone.yaml\"", + "description": "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.10/git-clone.yaml\"", "type": "string" }, "uri": { @@ -1211,8 +1204,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "resolver": { "description": "Resolver is the name of the resolver that should perform resolution of the referenced Tekton resource, such as \"git\".", @@ -1540,15 +1532,14 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "ref": { "description": "Contains the reference to an existing StepAction.", "$ref": "#/definitions/v1.Ref" }, "results": { - "description": "Results declares StepResults produced by the Step.\n\nThis is field is at an ALPHA stability level and gated by \"enable-step-actions\" feature flag.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", + "description": "Results declares StepResults produced by the Step.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", "type": "array", "items": { "default": {}, @@ -1632,7 +1623,7 @@ } }, "v1.StepResult": { - "description": "StepResult used to describe the Results of a Step.\n\nThis is field is at an BETA stability level and gated by \"enable-step-actions\" feature flag.", + "description": "StepResult used to describe the Results of a Step.", "type": "object", "required": [ "name" @@ -2059,8 +2050,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "podTemplate": { "description": "PodTemplate holds pod specific configuration", @@ -2106,7 +2096,7 @@ "$ref": "#/definitions/v1.TaskRef" }, "taskSpec": { - "description": "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1)", "$ref": "#/definitions/v1.TaskSpec" }, "timeout": { @@ -2141,8 +2131,7 @@ }, "artifacts": { "description": "Artifacts are the list of artifacts written out by the task's containers", - "$ref": "#/definitions/v1.Artifacts", - "x-kubernetes-list-type": "atomic" + "$ref": "#/definitions/v1.Artifacts" }, "completionTime": { "description": "CompletionTime is the time the build completed.", @@ -2187,8 +2176,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.TaskRunStatus" - }, - "x-kubernetes-list-type": "atomic" + } }, "sidecars": { "description": "The list has one entry per sidecar in the manifest. Each entry is represents the imageid of the corresponding sidecar.", @@ -2235,8 +2223,7 @@ "properties": { "artifacts": { "description": "Artifacts are the list of artifacts written out by the task's containers", - "$ref": "#/definitions/v1.Artifacts", - "x-kubernetes-list-type": "atomic" + "$ref": "#/definitions/v1.Artifacts" }, "completionTime": { "description": "CompletionTime is the time the build completed.", @@ -2266,8 +2253,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.TaskRunStatus" - }, - "x-kubernetes-list-type": "atomic" + } }, "sidecars": { "description": "The list has one entry per sidecar in the manifest. Each entry is represents the imageid of the corresponding sidecar.", @@ -2343,8 +2329,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "results": { "description": "Results are values that this Task can output", @@ -2378,13 +2363,12 @@ "x-kubernetes-list-type": "atomic" }, "volumes": { - "description": "Volumes is a collection of volumes that are available to mount into the steps of the build.", + "description": "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Volume" - }, - "x-kubernetes-list-type": "atomic" + } }, "workspaces": { "description": "Workspaces are the volumes that this Task requires.", @@ -2483,7 +2467,7 @@ "type": "string" }, "volumeClaimTemplate": { - "description": "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun.", + "description": "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun. See PersistentVolumeClaim (API version: v1)", "$ref": "#/definitions/v1.PersistentVolumeClaim" } } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_types.go index 89459050..05fb47f1 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_types.go @@ -36,6 +36,7 @@ import ( // output resources the Task requires. // // +k8s:openapi-gen=true +// +kubebuilder:storageversion type Task struct { metav1.TypeMeta `json:",inline"` // +optional @@ -74,13 +75,15 @@ func (t *Task) Checksum() ([]byte, error) { return sha256Checksum, nil } +// +listType=atomic +type Volumes []corev1.Volume + // TaskSpec defines the desired state of Task. type TaskSpec struct { // Params is a list of input parameters required to run the task. Params // must be supplied as inputs in TaskRuns unless they declare a default // value. // +optional - // +listType=atomic Params ParamSpecs `json:"params,omitempty"` // DisplayName is a user-facing name of the task that may be @@ -100,8 +103,10 @@ type TaskSpec struct { // Volumes is a collection of volumes that are available to mount into the // steps of the build. - // +listType=atomic - Volumes []corev1.Volume `json:"volumes,omitempty"` + // See Pod.spec.volumes (API version: v1) + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + Volumes Volumes `json:"volumes,omitempty"` // StepTemplate can be used as the basis for all step containers within the // Task, so that the steps inherit settings on the base container. @@ -129,3 +134,9 @@ type TaskList struct { metav1.ListMeta `json:"metadata,omitempty"` Items []Task `json:"items"` } + +// StepList is a list of Steps +type StepList []Step + +// SidecarList is a list of Sidecars +type SidecarList []Sidecar diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_validation.go index 4232d295..5106a5fa 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/task_validation.go @@ -20,23 +20,15 @@ import ( "context" "fmt" "path/filepath" - "reflect" "regexp" - "strings" - "time" - "github.com/tektoncd/pipeline/internal/artifactref" "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline" "github.com/tektoncd/pipeline/pkg/apis/validate" - "github.com/tektoncd/pipeline/pkg/internal/resultref" "github.com/tektoncd/pipeline/pkg/substitution" - "golang.org/x/exp/slices" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/validation" "knative.dev/pkg/apis" "knative.dev/pkg/webhook/resourcesemantics" ) @@ -47,7 +39,7 @@ const ( // - Must begin with a letter or an underscore (_) stringAndArrayVariableNameFormat = "^[_a-zA-Z][_a-zA-Z0-9.-]*$" - // objectVariableNameFormat is the regext used to validate object name and key names format + // objectVariableNameFormat is the regex used to validate object name and key names format // The difference with the array or string name format is that object variable names shouldn't contain dots. objectVariableNameFormat = "^[_a-zA-Z][_a-zA-Z0-9-]*$" ) @@ -95,8 +87,8 @@ func (ts *TaskSpec) Validate(ctx context.Context) (errs *apis.FieldError) { }) } - errs = errs.Also(validateSteps(ctx, mergedSteps).ViaField("steps")) - errs = errs.Also(validateSidecars(ts.Sidecars).ViaField("sidecars")) + errs = errs.Also(StepList(mergedSteps).Validate(ctx).ViaField("steps")) + errs = errs.Also(SidecarList(ts.Sidecars).Validate(ctx).ViaField("sidecars")) errs = errs.Also(ValidateParameterTypes(ctx, ts.Params).ViaField("params")) errs = errs.Also(ValidateParameterVariables(ctx, ts.Steps, ts.Params)) errs = errs.Also(validateTaskContextVariables(ctx, ts.Steps)) @@ -127,36 +119,6 @@ func ValidateObjectParamsHaveProperties(ctx context.Context, params ParamSpecs) return errs } -func validateSidecars(sidecars []Sidecar) (errs *apis.FieldError) { - for _, sc := range sidecars { - errs = errs.Also(validateSidecarName(sc)) - - if sc.Image == "" { - errs = errs.Also(apis.ErrMissingField("image")) - } - - if sc.Script != "" { - if len(sc.Command) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "script cannot be used with command", - Paths: []string{"script"}, - }) - } - } - } - return errs -} - -func validateSidecarName(sc Sidecar) (errs *apis.FieldError) { - if sc.Name == pipeline.ReservedResultsSidecarName { - errs = errs.Also(&apis.FieldError{ - Message: fmt.Sprintf("Invalid: cannot use reserved sidecar name %v ", sc.Name), - Paths: []string{"name"}, - }) - } - return errs -} - func validateResults(ctx context.Context, results []TaskResult) (errs *apis.FieldError) { for index, result := range results { errs = errs.Also(result.Validate(ctx).ViaIndex(index)) @@ -237,7 +199,7 @@ func validateWorkspaceUsages(ctx context.Context, ts *TaskSpec) (errs *apis.Fiel return errs } -// ValidateVolumes validates a slice of volumes to make sure there are no dupilcate names +// ValidateVolumes validates a slice of volumes to make sure there are no duplicate names func ValidateVolumes(volumes []corev1.Volume) (errs *apis.FieldError) { // Task must not have duplicate volume names. vols := sets.NewString() @@ -251,11 +213,20 @@ func ValidateVolumes(volumes []corev1.Volume) (errs *apis.FieldError) { return errs } -func validateSteps(ctx context.Context, steps []Step) (errs *apis.FieldError) { +// Validate implements apis.Validatable +func (l StepList) Validate(ctx context.Context) (errs *apis.FieldError) { // Task must not have duplicate step names. names := sets.NewString() - for idx, s := range steps { - errs = errs.Also(validateStep(ctx, s, names).ViaIndex(idx)) + for idx, s := range l { + // names cannot be duplicated - checking that Step names are unique + if s.Name != "" { + if names.Has(s.Name) { + errs = errs.Also(apis.ErrMultipleOneOf("name").ViaIndex(idx)) + } + names.Insert(s.Name) + } + + errs = errs.Also(s.Validate(ctx).ViaIndex(idx)) if s.Results != nil { errs = errs.Also(ValidateStepResultsVariables(ctx, s.Results, s.Script).ViaIndex(idx)) errs = errs.Also(ValidateStepResults(ctx, s.Results).ViaIndex(idx).ViaField("results")) @@ -267,295 +238,32 @@ func validateSteps(ctx context.Context, steps []Step) (errs *apis.FieldError) { return errs } -// isCreateOrUpdateAndDiverged checks if the webhook event was create or update -// if create, it returns true. -// if update, it checks if the step results have diverged and returns if diverged. -// if neither, it returns false. -func isCreateOrUpdateAndDiverged(ctx context.Context, s Step) bool { - if apis.IsInCreate(ctx) { - return true - } - if apis.IsInUpdate(ctx) { - baseline := apis.GetBaseline(ctx) - var baselineStep Step - switch o := baseline.(type) { - case *TaskRun: - if o.Spec.TaskSpec != nil { - for _, step := range o.Spec.TaskSpec.Steps { - if s.Name == step.Name { - baselineStep = step - break - } - } - } - default: - // the baseline is not a taskrun. - // return true so that the validation can happen - return true - } - // If an update event, check if the results have diverged from the baseline - // this way, the feature flag check wont happen. - // This will avoid issues like https://github.com/tektoncd/pipeline/issues/5203 - // when the feature is turned off mid-run. - diverged := !reflect.DeepEqual(s.Results, baselineStep.Results) - return diverged - } - return false -} - -func errorIfStepResultReferenceinField(value, fieldName string) (errs *apis.FieldError) { - matches := resultref.StepResultRegex.FindAllStringSubmatch(value, -1) - if len(matches) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "stepResult substitutions are only allowed in env, command and args. Found usage in", - Paths: []string{fieldName}, - }) - } - return errs -} - -func stepArtifactReferenceExists(src string) bool { - return len(artifactref.StepArtifactRegex.FindAllStringSubmatch(src, -1)) > 0 || strings.Contains(src, "$("+artifactref.StepArtifactPathPattern+")") -} -func taskArtifactReferenceExists(src string) bool { - return len(artifactref.TaskArtifactRegex.FindAllStringSubmatch(src, -1)) > 0 || strings.Contains(src, "$("+artifactref.TaskArtifactPathPattern+")") -} -func errorIfStepArtifactReferencedInField(value, fieldName string) (errs *apis.FieldError) { - if stepArtifactReferenceExists(value) { - errs = errs.Also(&apis.FieldError{ - Message: "stepArtifact substitutions are only allowed in env, command, args and script. Found usage in", - Paths: []string{fieldName}, - }) - } - return errs -} - -func validateStepArtifactsReference(s Step) (errs *apis.FieldError) { - errs = errs.Also(errorIfStepArtifactReferencedInField(s.Name, "name")) - errs = errs.Also(errorIfStepArtifactReferencedInField(s.Image, "image")) - errs = errs.Also(errorIfStepArtifactReferencedInField(string(s.ImagePullPolicy), "imagePullPoliicy")) - errs = errs.Also(errorIfStepArtifactReferencedInField(s.WorkingDir, "workingDir")) - for _, e := range s.EnvFrom { - errs = errs.Also(errorIfStepArtifactReferencedInField(e.Prefix, "envFrom.prefix")) - if e.ConfigMapRef != nil { - errs = errs.Also(errorIfStepArtifactReferencedInField(e.ConfigMapRef.LocalObjectReference.Name, "envFrom.configMapRef")) - } - if e.SecretRef != nil { - errs = errs.Also(errorIfStepArtifactReferencedInField(e.SecretRef.LocalObjectReference.Name, "envFrom.secretRef")) - } - } - for _, v := range s.VolumeMounts { - errs = errs.Also(errorIfStepArtifactReferencedInField(v.Name, "volumeMounts.name")) - errs = errs.Also(errorIfStepArtifactReferencedInField(v.MountPath, "volumeMounts.mountPath")) - errs = errs.Also(errorIfStepArtifactReferencedInField(v.SubPath, "volumeMounts.subPath")) - } - for _, v := range s.VolumeDevices { - errs = errs.Also(errorIfStepArtifactReferencedInField(v.Name, "volumeDevices.name")) - errs = errs.Also(errorIfStepArtifactReferencedInField(v.DevicePath, "volumeDevices.devicePath")) +// ValidateStepResults validates that all of the declared StepResults are valid. +func ValidateStepResults(ctx context.Context, results []StepResult) (errs *apis.FieldError) { + for index, result := range results { + errs = errs.Also(result.Validate(ctx).ViaIndex(index)) } return errs } -func validateStepResultReference(s Step) (errs *apis.FieldError) { - errs = errs.Also(errorIfStepResultReferenceinField(s.Name, "name")) - errs = errs.Also(errorIfStepResultReferenceinField(s.Image, "image")) - errs = errs.Also(errorIfStepResultReferenceinField(s.Script, "script")) - errs = errs.Also(errorIfStepResultReferenceinField(string(s.ImagePullPolicy), "imagePullPoliicy")) - errs = errs.Also(errorIfStepResultReferenceinField(s.WorkingDir, "workingDir")) - for _, e := range s.EnvFrom { - errs = errs.Also(errorIfStepResultReferenceinField(e.Prefix, "envFrom.prefix")) - if e.ConfigMapRef != nil { - errs = errs.Also(errorIfStepResultReferenceinField(e.ConfigMapRef.LocalObjectReference.Name, "envFrom.configMapRef")) - } - if e.SecretRef != nil { - errs = errs.Also(errorIfStepResultReferenceinField(e.SecretRef.LocalObjectReference.Name, "envFrom.secretRef")) - } - } - for _, v := range s.VolumeMounts { - errs = errs.Also(errorIfStepResultReferenceinField(v.Name, "volumeMounts.name")) - errs = errs.Also(errorIfStepResultReferenceinField(v.MountPath, "volumeMounts.mountPath")) - errs = errs.Also(errorIfStepResultReferenceinField(v.SubPath, "volumeMounts.subPath")) - } - for _, v := range s.VolumeDevices { - errs = errs.Also(errorIfStepResultReferenceinField(v.Name, "volumeDevices.name")) - errs = errs.Also(errorIfStepResultReferenceinField(v.DevicePath, "volumeDevices.devicePath")) +// ValidateStepResultsVariables validates if the StepResults referenced in step script are defined in step's results. +func ValidateStepResultsVariables(ctx context.Context, results []StepResult, script string) (errs *apis.FieldError) { + resultsNames := sets.NewString() + for _, r := range results { + resultsNames.Insert(r.Name) } + errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(script, "step.results", resultsNames).ViaField("script")) + errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(script, "results", resultsNames).ViaField("script")) return errs } -func validateStep(ctx context.Context, s Step, names sets.String) (errs *apis.FieldError) { - if err := validateArtifactsReferencesInStep(ctx, s); err != nil { - return err - } - - if s.Ref != nil { - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions && isCreateOrUpdateAndDiverged(ctx, s) { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true to reference StepActions in Steps.", config.EnableStepActions), "") - } - errs = errs.Also(s.Ref.Validate(ctx)) - if s.Image != "" { - errs = errs.Also(&apis.FieldError{ - Message: "image cannot be used with Ref", - Paths: []string{"image"}, - }) - } - if len(s.Command) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "command cannot be used with Ref", - Paths: []string{"command"}, - }) - } - if len(s.Args) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "args cannot be used with Ref", - Paths: []string{"args"}, - }) - } - if s.Script != "" { - errs = errs.Also(&apis.FieldError{ - Message: "script cannot be used with Ref", - Paths: []string{"script"}, - }) - } - if s.WorkingDir != "" { - errs = errs.Also(&apis.FieldError{ - Message: "working dir cannot be used with Ref", - Paths: []string{"workingDir"}, - }) - } - if s.Env != nil { - errs = errs.Also(&apis.FieldError{ - Message: "env cannot be used with Ref", - Paths: []string{"env"}, - }) - } - if len(s.VolumeMounts) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "volumeMounts cannot be used with Ref", - Paths: []string{"volumeMounts"}, - }) - } - if len(s.Results) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "results cannot be used with Ref", - Paths: []string{"results"}, - }) - } - } else { - if len(s.Params) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "params cannot be used without Ref", - Paths: []string{"params"}, - }) - } - if len(s.Results) > 0 { - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions && isCreateOrUpdateAndDiverged(ctx, s) { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true in order to use Results in Steps.", config.EnableStepActions), "") - } - } - if len(s.When) > 0 { - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions && isCreateOrUpdateAndDiverged(ctx, s) { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true in order to use When in Steps.", config.EnableStepActions), "") - } - } - if s.Image == "" { - errs = errs.Also(apis.ErrMissingField("Image")) - } - - if s.Script != "" { - if len(s.Command) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: "script cannot be used with command", - Paths: []string{"script"}, - }) - } - } - } - - if s.Name != "" { - if names.Has(s.Name) { - errs = errs.Also(apis.ErrInvalidValue(s.Name, "name")) - } - if e := validation.IsDNS1123Label(s.Name); len(e) > 0 { - errs = errs.Also(&apis.FieldError{ - Message: fmt.Sprintf("invalid value %q", s.Name), - Paths: []string{"name"}, - Details: "Task step name must be a valid DNS Label, For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - }) - } - names.Insert(s.Name) - } - - if s.Timeout != nil { - if s.Timeout.Duration < time.Duration(0) { - return apis.ErrInvalidValue(s.Timeout.Duration, "negative timeout") - } - } - - for j, vm := range s.VolumeMounts { - if strings.HasPrefix(vm.MountPath, "/tekton/") && - !strings.HasPrefix(vm.MountPath, "/tekton/home") { - errs = errs.Also(apis.ErrGeneric(fmt.Sprintf("volumeMount cannot be mounted under /tekton/ (volumeMount %q mounted at %q)", vm.Name, vm.MountPath), "mountPath").ViaFieldIndex("volumeMounts", j)) - } - if strings.HasPrefix(vm.Name, "tekton-internal-") { - errs = errs.Also(apis.ErrGeneric(fmt.Sprintf(`volumeMount name %q cannot start with "tekton-internal-"`, vm.Name), "name").ViaFieldIndex("volumeMounts", j)) - } - } - - if s.OnError != "" { - if !isParamRefs(string(s.OnError)) && s.OnError != Continue && s.OnError != StopAndFail { - errs = errs.Also(&apis.FieldError{ - Message: fmt.Sprintf("invalid value: \"%v\"", s.OnError), - Paths: []string{"onError"}, - Details: "Task step onError must be either \"continue\" or \"stopAndFail\"", - }) - } +func (l SidecarList) Validate(ctx context.Context) (errs *apis.FieldError) { + for _, sc := range l { + errs = errs.Also(sc.Validate(ctx)) } - - if s.Script != "" { - cleaned := strings.TrimSpace(s.Script) - if strings.HasPrefix(cleaned, "#!win") { - errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "windows script support", config.AlphaAPIFields).ViaField("script")) - } - } - - // StdoutConfig is an alpha feature and will fail validation if it's used in a task spec - // when the enable-api-fields feature gate is not "alpha". - if s.StdoutConfig != nil { - errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "step stdout stream support", config.AlphaAPIFields).ViaField("stdoutconfig")) - } - // StderrConfig is an alpha feature and will fail validation if it's used in a task spec - // when the enable-api-fields feature gate is not "alpha". - if s.StderrConfig != nil { - errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "step stderr stream support", config.AlphaAPIFields).ViaField("stderrconfig")) - } - - // Validate usage of step result reference. - // Referencing previous step's results are only allowed in `env`, `command` and `args`. - errs = errs.Also(validateStepResultReference(s)) - - // Validate usage of step artifacts output reference - // Referencing previous step's results are only allowed in `env`, `command` and `args`, `script`. - errs = errs.Also(validateStepArtifactsReference(s)) return errs } -func validateArtifactsReferencesInStep(ctx context.Context, s Step) *apis.FieldError { - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableArtifacts { - var t []string - t = append(t, s.Script) - t = append(t, s.Command...) - t = append(t, s.Args...) - for _, e := range s.Env { - t = append(t, e.Value) - } - if slices.ContainsFunc(t, stepArtifactReferenceExists) || slices.ContainsFunc(t, taskArtifactReferenceExists) { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true to use artifacts feature.", config.EnableArtifacts), "") - } - } - return nil -} - // ValidateParameterTypes validates all the types within a slice of ParamSpecs func ValidateParameterTypes(ctx context.Context, params []ParamSpec) (errs *apis.FieldError) { for _, p := range params { @@ -816,12 +524,6 @@ func validateStepVariables(ctx context.Context, step Step, prefix string, vars s return errs } -// isParamRefs attempts to check if a specified string looks like it contains any parameter reference -// This is useful to make sure the specified value looks like a Parameter Reference before performing any strict validation -func isParamRefs(s string) bool { - return strings.HasPrefix(s, "$("+ParamsPrefix) -} - // GetIndexingReferencesToArrayParams returns all strings referencing indices of TaskRun array parameters // from parameters, workspaces, and when expressions defined in the Task. // For example, if a Task has a parameter with a value "$(params.array-param-name[1])", @@ -843,22 +545,3 @@ func (ts *TaskSpec) GetIndexingReferencesToArrayParams() sets.String { } return sets.NewString(arrayIndexParamRefs...) } - -// ValidateStepResults validates that all of the declared StepResults are valid. -func ValidateStepResults(ctx context.Context, results []StepResult) (errs *apis.FieldError) { - for index, result := range results { - errs = errs.Also(result.Validate(ctx).ViaIndex(index)) - } - return errs -} - -// ValidateStepResultsVariables validates if the StepResults referenced in step script are defined in step's results. -func ValidateStepResultsVariables(ctx context.Context, results []StepResult, script string) (errs *apis.FieldError) { - resultsNames := sets.NewString() - for _, r := range results { - resultsNames.Insert(r.Name) - } - errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(script, "step.results", resultsNames).ViaField("script")) - errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(script, "results", resultsNames).ViaField("script")) - return errs -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskref_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskref_types.go index f7558333..2bb395da 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskref_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskref_types.go @@ -42,9 +42,6 @@ type TaskKind string const ( // NamespacedTaskKind indicates that the task type has a namespaced scope. NamespacedTaskKind TaskKind = "Task" - // ClusterTaskRefKind is the task type for a reference to a task with cluster scope. - // ClusterTasks are not supported in v1, but v1 types may reference ClusterTasks. - ClusterTaskRefKind TaskKind = "ClusterTask" ) // IsCustomTask checks whether the reference is to a Custom Task diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskrun_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskrun_types.go index b5305937..1e2946fc 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskrun_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/taskrun_types.go @@ -37,16 +37,18 @@ type TaskRunSpec struct { // +optional Debug *TaskRunDebug `json:"debug,omitempty"` // +optional - // +listType=atomic Params Params `json:"params,omitempty"` // +optional ServiceAccountName string `json:"serviceAccountName"` // no more than one of the TaskRef and TaskSpec may be specified. // +optional TaskRef *TaskRef `json:"taskRef,omitempty"` - // Specifying PipelineSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // Specifying TaskSpec can be disabled by setting + // `disable-inline-spec` feature flag. + // See Task.spec (API version: tekton.dev/v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless TaskSpec *TaskSpec `json:"taskSpec,omitempty"` // Used for cancelling a TaskRun (and maybe more later on) // +optional @@ -268,6 +270,9 @@ func (trs *TaskRunStatus) MarkResourceFailed(reason TaskRunReason, err error) { trs.CompletionTime = &succeeded.LastTransitionTime.Inner } +// +listType=atomic +type RetriesStatus []TaskRunStatus + // TaskRunStatusFields holds the fields of TaskRun's status. This is defined // separately and inlined so that other types can readily consume these fields // via duck typing. @@ -289,8 +294,9 @@ type TaskRunStatusFields struct { // RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. // All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant. // +optional - // +listType=atomic - RetriesStatus []TaskRunStatus `json:"retriesStatus,omitempty"` + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + RetriesStatus RetriesStatus `json:"retriesStatus,omitempty"` // Results are the list of results written out by the task's containers // +optional @@ -299,7 +305,6 @@ type TaskRunStatusFields struct { // Artifacts are the list of artifacts written out by the task's containers // +optional - // +listType=atomic Artifacts *Artifacts `json:"artifacts,omitempty"` // The list has one entry per sidecar in the manifest. Each entry is @@ -405,6 +410,7 @@ type SidecarState struct { // used to run the steps in a Task. // // +k8s:openapi-gen=true +// +kubebuilder:storageversion type TaskRun struct { metav1.TypeMeta `json:",inline"` // +optional diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/workspace_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/workspace_types.go index f556201c..441fa67a 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/workspace_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/workspace_types.go @@ -60,7 +60,10 @@ type WorkspaceBinding struct { SubPath string `json:"subPath,omitempty"` // VolumeClaimTemplate is a template for a claim that will be created in the same namespace. // The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun. + // See PersistentVolumeClaim (API version: v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless VolumeClaimTemplate *corev1.PersistentVolumeClaim `json:"volumeClaimTemplate,omitempty"` // PersistentVolumeClaimVolumeSource represents a reference to a // PersistentVolumeClaim in the same namespace. Either this OR EmptyDir can be used. diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/zz_generated.deepcopy.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/zz_generated.deepcopy.go index c3057d33..469dda07 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/zz_generated.deepcopy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1/zz_generated.deepcopy.go @@ -1173,6 +1173,28 @@ func (in *ResultRef) DeepCopy() *ResultRef { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in RetriesStatus) DeepCopyInto(out *RetriesStatus) { + { + in := &in + *out = make(RetriesStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RetriesStatus. +func (in RetriesStatus) DeepCopy() RetriesStatus { + if in == nil { + return nil + } + out := new(RetriesStatus) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Sidecar) DeepCopyInto(out *Sidecar) { *out = *in @@ -1266,6 +1288,28 @@ func (in *Sidecar) DeepCopy() *Sidecar { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in SidecarList) DeepCopyInto(out *SidecarList) { + { + in := &in + *out = make(SidecarList, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SidecarList. +func (in SidecarList) DeepCopy() SidecarList { + if in == nil { + return nil + } + out := new(SidecarList) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SidecarState) DeepCopyInto(out *SidecarState) { *out = *in @@ -1410,6 +1454,28 @@ func (in *Step) DeepCopy() *Step { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in StepList) DeepCopyInto(out *StepList) { + { + in := &in + *out = make(StepList, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StepList. +func (in StepList) DeepCopy() StepList { + if in == nil { + return nil + } + out := new(StepList) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *StepOutputConfig) DeepCopyInto(out *StepOutputConfig) { *out = *in @@ -1927,7 +1993,7 @@ func (in *TaskRunStatusFields) DeepCopyInto(out *TaskRunStatusFields) { } if in.RetriesStatus != nil { in, out := &in.RetriesStatus, &out.RetriesStatus - *out = make([]TaskRunStatus, len(*in)) + *out = make(RetriesStatus, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -2017,7 +2083,7 @@ func (in *TaskSpec) DeepCopyInto(out *TaskSpec) { } if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes - *out = make([]corev1.Volume, len(*in)) + *out = make(Volumes, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -2090,6 +2156,28 @@ func (in *TimeoutFields) DeepCopy() *TimeoutFields { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in Volumes) DeepCopyInto(out *Volumes) { + { + in := &in + *out = make(Volumes, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Volumes. +func (in Volumes) DeepCopy() Volumes { + if in == nil { + return nil + } + out := new(Volumes) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WhenExpression) DeepCopyInto(out *WhenExpression) { *out = *in diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/openapi_generated.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/openapi_generated.go index cbcdc1dd..5b2dc4e7 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/openapi_generated.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/openapi_generated.go @@ -19,8 +19,6 @@ limitations under the License. // Code generated by openapi-gen. DO NOT EDIT. -// This file was autogenerated by openapi-gen. Do not edit it manually! - package v1alpha1 import ( @@ -195,26 +193,25 @@ func schema_pkg_apis_pipeline_pod_Template(ref common.ReferenceCallback) common. }, "affinity": { SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's scheduling constraints", + Description: "If specified, the pod's scheduling constraints. See Pod.spec.affinity (API version: v1)", Ref: ref("k8s.io/api/core/v1.Affinity"), }, }, "securityContext": { SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", + Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. See Pod.spec.securityContext (API version: v1)", Ref: ref("k8s.io/api/core/v1.PodSecurityContext"), }, }, "volumes": { VendorExtensible: spec.VendorExtensible{ Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", "x-kubernetes-patch-merge-key": "name", "x-kubernetes-patch-strategy": "merge,retainKeys", }, }, SchemaProps: spec.SchemaProps{ - Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", + Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes See Pod.spec.volumes (API version: v1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -856,11 +853,6 @@ func schema_pkg_apis_pipeline_v1alpha1_StepActionSpec(ref common.ReferenceCallba }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of input parameters required to run the stepAction. Params must be supplied as inputs in Steps unless they declare a defaultvalue.", Type: []string{"array"}, diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_types.go index 8fff027b..c13b8997 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_types.go @@ -125,7 +125,6 @@ type StepActionSpec struct { // Params is a list of input parameters required to run the stepAction. // Params must be supplied as inputs in Steps unless they declare a defaultvalue. // +optional - // +listType=atomic Params v1.ParamSpecs `json:"params,omitempty"` // Results are values that this StepAction can output // +optional diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_validation.go index f61d1379..66b8daab 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/stepaction_validation.go @@ -15,6 +15,7 @@ package v1alpha1 import ( "context" + "fmt" "strings" "github.com/tektoncd/pipeline/pkg/apis/config" @@ -128,7 +129,80 @@ func validateParameterVariables(ctx context.Context, sas StepActionSpec, params stringParameterNames := sets.NewString(stringParams.GetNames()...) arrayParameterNames := sets.NewString(arrayParams.GetNames()...) errs = errs.Also(v1.ValidateNameFormat(stringParameterNames.Insert(arrayParameterNames.List()...), objectParams)) - return errs.Also(validateStepActionArrayUsage(sas, "params", arrayParameterNames)) + errs = errs.Also(validateStepActionArrayUsage(sas, "params", arrayParameterNames)) + return errs.Also(validateDefaultParameterReferences(params)) +} + +// validateDefaultParameterReferences ensures that parameters referenced in default values are defined +func validateDefaultParameterReferences(params v1.ParamSpecs) *apis.FieldError { + var errs *apis.FieldError + allParams := sets.NewString(params.GetNames()...) + + // First pass: collect all parameters that have no references in their default values + resolvedParams := sets.NewString() + paramsNeedingResolution := make(map[string][]string) + + for _, p := range params { + if p.Default != nil { + matches, _ := substitution.ExtractVariableExpressions(p.Default.StringVal, "params") + if len(matches) == 0 { + resolvedParams.Insert(p.Name) + } else { + // Track which parameters this parameter depends on + referencedParams := make([]string, 0, len(matches)) + hasUndefinedParam := false + for _, match := range matches { + paramName := strings.TrimSuffix(strings.TrimPrefix(match, "$(params."), ")") + if !allParams.Has(paramName) { + hasUndefinedParam = true + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("param %q default value references param %q which is not defined", p.Name, paramName), + Paths: []string{"params"}, + }) + } + referencedParams = append(referencedParams, paramName) + } + // Only track dependencies if all referenced parameters exist + if !hasUndefinedParam { + paramsNeedingResolution[p.Name] = referencedParams + } + } + } else { + resolvedParams.Insert(p.Name) + } + } + + // Second pass: iteratively resolve parameters whose dependencies are satisfied + for len(paramsNeedingResolution) > 0 { + paramWasResolved := false + for paramName, referencedParams := range paramsNeedingResolution { + canResolveParam := true + for _, referencedParam := range referencedParams { + if !resolvedParams.Has(referencedParam) { + canResolveParam = false + break + } + } + if canResolveParam { + resolvedParams.Insert(paramName) + delete(paramsNeedingResolution, paramName) + paramWasResolved = true + } + } + if !paramWasResolved { + // If we couldn't resolve any parameters in this iteration, + // we have a circular dependency + for paramName := range paramsNeedingResolution { + errs = errs.Also(&apis.FieldError{ + Message: fmt.Sprintf("param %q default value has a circular dependency", paramName), + Paths: []string{"params"}, + }) + } + break + } + } + + return errs } // validateObjectUsage validates the usage of individual attributes of an object param and the usage of the entire object diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/swagger.json b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/swagger.json index 12ecda63..0efc19a9 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/swagger.json +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/swagger.json @@ -52,7 +52,7 @@ "type": "object", "properties": { "affinity": { - "description": "If specified, the pod's scheduling constraints", + "description": "If specified, the pod's scheduling constraints. See Pod.spec.affinity (API version: v1)", "$ref": "#/definitions/v1.Affinity" }, "automountServiceAccountToken": { @@ -125,7 +125,7 @@ "type": "string" }, "securityContext": { - "description": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", + "description": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. See Pod.spec.securityContext (API version: v1)", "$ref": "#/definitions/v1.PodSecurityContext" }, "tolerations": { @@ -147,13 +147,12 @@ "x-kubernetes-list-type": "atomic" }, "volumes": { - "description": "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", + "description": "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes See Pod.spec.volumes (API version: v1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Volume" }, - "x-kubernetes-list-type": "atomic", "x-kubernetes-patch-merge-key": "name", "x-kubernetes-patch-strategy": "merge,retainKeys" } @@ -438,8 +437,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "results": { "description": "Results are values that this StepAction can output", diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_conversion.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_conversion.go deleted file mode 100644 index e7bac12b..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_conversion.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import ( - "context" - "fmt" - - "knative.dev/pkg/apis" -) - -var _ apis.Convertible = (*ClusterTask)(nil) - -// ConvertTo implements apis.Convertible -func (ct *ClusterTask) ConvertTo(ctx context.Context, sink apis.Convertible) error { - if apis.IsInDelete(ctx) { - return nil - } - return fmt.Errorf("v1beta1 is the highest known version, got: %T", sink) -} - -// ConvertFrom implements apis.Convertible -func (ct *ClusterTask) ConvertFrom(ctx context.Context, source apis.Convertible) error { - if apis.IsInDelete(ctx) { - return nil - } - return fmt.Errorf("v1beta1 is the highest known version, got: %T", source) -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_defaults.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_defaults.go deleted file mode 100644 index fda6d76e..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_defaults.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -var _ apis.Defaultable = (*ClusterTask)(nil) - -// SetDefaults sets the default values for the ClusterTask's Spec. -func (t *ClusterTask) SetDefaults(ctx context.Context) { - t.Spec.SetDefaults(ctx) -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_types.go deleted file mode 100644 index aaaf03b9..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_types.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import ( - "github.com/tektoncd/pipeline/pkg/apis/pipeline" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +genclient:noStatus -// +genclient:nonNamespaced -// +genreconciler:krshapedlogic=false -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterTask is a Task with a cluster scope. ClusterTasks are used to -// represent Tasks that should be publicly addressable from any namespace in the -// cluster. -// -// Deprecated: Please use the cluster resolver instead. -type ClusterTask struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // Spec holds the desired state of the Task from the client - // +optional - Spec TaskSpec `json:"spec,omitempty"` -} - -var _ kmeta.OwnerRefable = (*ClusterTask)(nil) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterTaskList contains a list of ClusterTask -type ClusterTaskList struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ListMeta `json:"metadata,omitempty"` - Items []ClusterTask `json:"items"` -} - -// TaskSpec returns the ClusterTask's Spec -func (t *ClusterTask) TaskSpec() TaskSpec { - return t.Spec -} - -// TaskMetadata returns the ObjectMeta for the ClusterTask -func (t *ClusterTask) TaskMetadata() metav1.ObjectMeta { - return t.ObjectMeta -} - -// Copy returns a DeepCopy of the ClusterTask -func (t *ClusterTask) Copy() TaskObject { - return t.DeepCopy() -} - -// GetGroupVersionKind implements kmeta.OwnerRefable. -func (*ClusterTask) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind(pipeline.ClusterTaskControllerName) -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_validation.go deleted file mode 100644 index 5dfa6278..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/cluster_task_validation.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import ( - "context" - - "github.com/tektoncd/pipeline/pkg/apis/validate" - "knative.dev/pkg/apis" -) - -var _ apis.Validatable = (*ClusterTask)(nil) - -// Validate performs validation of the metadata and spec of this ClusterTask. -func (t *ClusterTask) Validate(ctx context.Context) *apis.FieldError { - if apis.IsInDelete(ctx) { - return nil - } - errs := validate.ObjectMetadata(t.GetObjectMeta()).ViaField("metadata") - errs = errs.Also(t.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")) - // We do not support propagated parameters in ClusterTasks. - // Validate that all params the ClusterTask uses are declared. - return errs.Also(ValidateUsageOfDeclaredParameters(ctx, t.Spec.Steps, t.Spec.Params)) -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/container_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/container_types.go index 95f852bf..83387893 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/container_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/container_types.go @@ -235,12 +235,9 @@ type Step struct { Ref *Ref `json:"ref,omitempty"` // Params declares parameters passed to this step action. // +optional - // +listType=atomic Params Params `json:"params,omitempty"` // Results declares StepResults produced by the Step. // - // This is field is at an ALPHA stability level and gated by "enable-step-actions" feature flag. - // // It can be used in an inlined Step when used to store Results to $(step.results.resultName.path). // It cannot be used when referencing StepActions using [v1beta1.Step.Ref]. // The Results declared by the StepActions will be stored here instead. diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/customrun_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/customrun_types.go index e74f4834..c1459094 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/customrun_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/customrun_types.go @@ -53,7 +53,6 @@ type CustomRunSpec struct { CustomSpec *EmbeddedCustomRunSpec `json:"customSpec,omitempty"` // +optional - // +listType=atomic Params Params `json:"params,omitempty"` // Used for cancelling a customrun (and maybe more later on) diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/matrix_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/matrix_types.go index 19042e11..f7b55613 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/matrix_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/matrix_types.go @@ -16,10 +16,10 @@ package v1beta1 import ( "context" "fmt" + "maps" "sort" "github.com/tektoncd/pipeline/pkg/apis/config" - "golang.org/x/exp/maps" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/utils/strings/slices" "knative.dev/pkg/apis" @@ -31,16 +31,15 @@ type Matrix struct { // Params takes only `Parameters` of type `"array"` // Each array element is supplied to the `PipelineTask` by substituting `params` of type `"string"` in the underlying `Task`. // The names of the `params` in the `Matrix` must match the names of the `params` in the underlying `Task` that they will be substituting. - // +listType=atomic Params Params `json:"params,omitempty"` // Include is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix. // +optional - // +listType=atomic Include IncludeParamsList `json:"include,omitempty"` } // IncludeParamsList is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix. +// +listType=atomic type IncludeParamsList []IncludeParams // IncludeParams allows passing in a specific combinations of Parameters into the Matrix. @@ -50,7 +49,6 @@ type IncludeParams struct { // Params takes only `Parameters` of type `"string"` // The names of the `params` must match the names of the `params` in the underlying `Task` - // +listType=atomic Params Params `json:"params,omitempty"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/openapi_generated.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/openapi_generated.go index 145e72b0..f0c68b77 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/openapi_generated.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/openapi_generated.go @@ -19,8 +19,6 @@ limitations under the License. // Code generated by openapi-gen. DO NOT EDIT. -// This file was autogenerated by openapi-gen. Do not edit it manually! - package v1beta1 import ( @@ -38,8 +36,6 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.ChildStatusReference": schema_pkg_apis_pipeline_v1beta1_ChildStatusReference(ref), "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.CloudEventDelivery": schema_pkg_apis_pipeline_v1beta1_CloudEventDelivery(ref), "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.CloudEventDeliveryState": schema_pkg_apis_pipeline_v1beta1_CloudEventDeliveryState(ref), - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.ClusterTask": schema_pkg_apis_pipeline_v1beta1_ClusterTask(ref), - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.ClusterTaskList": schema_pkg_apis_pipeline_v1beta1_ClusterTaskList(ref), "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.ConfigSource": schema_pkg_apis_pipeline_v1beta1_ConfigSource(ref), "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.CustomRun": schema_pkg_apis_pipeline_v1beta1_CustomRun(ref), "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.CustomRunList": schema_pkg_apis_pipeline_v1beta1_CustomRunList(ref), @@ -275,26 +271,25 @@ func schema_pkg_apis_pipeline_pod_Template(ref common.ReferenceCallback) common. }, "affinity": { SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's scheduling constraints", + Description: "If specified, the pod's scheduling constraints. See Pod.spec.affinity (API version: v1)", Ref: ref("k8s.io/api/core/v1.Affinity"), }, }, "securityContext": { SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", + Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. See Pod.spec.securityContext (API version: v1)", Ref: ref("k8s.io/api/core/v1.PodSecurityContext"), }, }, "volumes": { VendorExtensible: spec.VendorExtensible{ Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", "x-kubernetes-patch-merge-key": "name", "x-kubernetes-patch-strategy": "merge,retainKeys", }, }, SchemaProps: spec.SchemaProps{ - Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", + Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes See Pod.spec.volumes (API version: v1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -685,97 +680,6 @@ func schema_pkg_apis_pipeline_v1beta1_CloudEventDeliveryState(ref common.Referen } } -func schema_pkg_apis_pipeline_v1beta1_ClusterTask(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterTask is a Task with a cluster scope. ClusterTasks are used to represent Tasks that should be publicly addressable from any namespace in the cluster.\n\nDeprecated: Please use the cluster resolver instead.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec holds the desired state of the Task from the client", - Default: map[string]interface{}{}, - Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.TaskSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.TaskSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_pkg_apis_pipeline_v1beta1_ClusterTaskList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterTaskList contains a list of ClusterTask", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.ClusterTask"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.ClusterTask", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - func schema_pkg_apis_pipeline_v1beta1_ConfigSource(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -808,7 +712,7 @@ func schema_pkg_apis_pipeline_v1beta1_ConfigSource(ref common.ReferenceCallback) }, "entryPoint": { SchemaProps: spec.SchemaProps{ - Description: "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.8/git-clone.yaml\"", + Description: "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.10/git-clone.yaml\"", Type: []string{"string"}, Format: "", }, @@ -934,11 +838,6 @@ func schema_pkg_apis_pipeline_v1beta1_CustomRunSpec(ref common.ReferenceCallback }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Type: []string{"array"}, Items: &spec.SchemaOrArray{ @@ -1089,11 +988,6 @@ func schema_pkg_apis_pipeline_v1beta1_EmbeddedTask(ref common.ReferenceCallback) }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of input parameters required to run the task. Params must be supplied as inputs in TaskRuns unless they declare a default value.", Type: []string{"array"}, @@ -1141,13 +1035,8 @@ func schema_pkg_apis_pipeline_v1beta1_EmbeddedTask(ref common.ReferenceCallback) }, }, "volumes": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ - Description: "Volumes is a collection of volumes that are available to mount into the steps of the build.", + Description: "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -1245,11 +1134,6 @@ func schema_pkg_apis_pipeline_v1beta1_IncludeParams(ref common.ReferenceCallback }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params takes only `Parameters` of type `\"string\"` The names of the `params` must match the names of the `params` in the underlying `Task`", Type: []string{"array"}, @@ -1349,11 +1233,6 @@ func schema_pkg_apis_pipeline_v1beta1_Matrix(ref common.ReferenceCallback) commo Type: []string{"object"}, Properties: map[string]spec.Schema{ "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of parameters used to fan out the pipelineTask Params takes only `Parameters` of type `\"array\"` Each array element is supplied to the `PipelineTask` by substituting `params` of type `\"string\"` in the underlying `Task`. The names of the `params` in the `Matrix` must match the names of the `params` in the underlying `Task` that they will be substituting.", Type: []string{"array"}, @@ -1368,11 +1247,6 @@ func schema_pkg_apis_pipeline_v1beta1_Matrix(ref common.ReferenceCallback) commo }, }, "include": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Include is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix.", Type: []string{"array"}, @@ -2013,7 +1887,7 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineRunSpec(ref common.ReferenceCallba }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.PipelineSpec"), }, }, @@ -2037,11 +1911,6 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineRunSpec(ref common.ReferenceCallba }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of parameter names and values.", Type: []string{"array"}, @@ -2243,7 +2112,7 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineRunStatus(ref common.ReferenceCall }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "PipelineRunSpec contains the exact spec used to instantiate the run", + Description: "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.PipelineSpec"), }, }, @@ -2389,7 +2258,7 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineRunStatusFields(ref common.Referen }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "PipelineRunSpec contains the exact spec used to instantiate the run", + Description: "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.PipelineSpec"), }, }, @@ -2574,11 +2443,6 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineSpec(ref common.ReferenceCallback) }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params declares a list of input parameters that must be supplied when this Pipeline is run.", Type: []string{"array"}, @@ -2693,7 +2557,7 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineTask(ref common.ReferenceCallback) }, "taskSpec": { SchemaProps: spec.SchemaProps{ - Description: "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.EmbeddedTask"), }, }, @@ -2745,11 +2609,6 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineTask(ref common.ReferenceCallback) }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Parameters declares parameters passed to this task.", Type: []string{"array"}, @@ -2802,7 +2661,7 @@ func schema_pkg_apis_pipeline_v1beta1_PipelineTask(ref common.ReferenceCallback) }, "pipelineSpec": { SchemaProps: spec.SchemaProps{ - Description: "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.PipelineSpec"), }, }, @@ -3263,7 +3122,7 @@ func schema_pkg_apis_pipeline_v1beta1_RefSource(ref common.ReferenceCallback) co }, "entryPoint": { SchemaProps: spec.SchemaProps{ - Description: "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.8/git-clone.yaml\"", + Description: "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.10/git-clone.yaml\"", Type: []string{"string"}, Format: "", }, @@ -3289,11 +3148,6 @@ func schema_pkg_apis_pipeline_v1beta1_ResolverRef(ref common.ReferenceCallback) }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params contains the parameters used to identify the referenced Tekton resource. Example entries might include \"repo\" or \"path\" but the set of params ultimately depends on the chosen resolver.", Type: []string{"array"}, @@ -4068,11 +3922,6 @@ func schema_pkg_apis_pipeline_v1beta1_Step(ref common.ReferenceCallback) common. }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params declares parameters passed to this step action.", Type: []string{"array"}, @@ -4093,7 +3942,7 @@ func schema_pkg_apis_pipeline_v1beta1_Step(ref common.ReferenceCallback) common. }, }, SchemaProps: spec.SchemaProps{ - Description: "Results declares StepResults produced by the Step.\n\nThis is field is at an ALPHA stability level and gated by \"enable-step-actions\" feature flag.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1beta1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", + Description: "Results declares StepResults produced by the Step.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1beta1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -4260,11 +4109,6 @@ func schema_pkg_apis_pipeline_v1beta1_StepActionSpec(ref common.ReferenceCallbac }, }, "args": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Arguments to the entrypoint. The image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", Type: []string{"array"}, @@ -4315,11 +4159,6 @@ func schema_pkg_apis_pipeline_v1beta1_StepActionSpec(ref common.ReferenceCallbac }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of input parameters required to run the stepAction. Params must be supplied as inputs in Steps unless they declare a defaultvalue.", Type: []string{"array"}, @@ -4912,7 +4751,7 @@ func schema_pkg_apis_pipeline_v1beta1_TaskRef(ref common.ReferenceCallback) comm }, "kind": { SchemaProps: spec.SchemaProps{ - Description: "TaskKind indicates the Kind of the Task: 1. Namespaced Task when Kind is set to \"Task\". If Kind is \"\", it defaults to \"Task\". 2. Cluster-Scoped Task when Kind is set to \"ClusterTask\" 3. Custom Task when Kind is non-empty and APIVersion is non-empty", + Description: "TaskKind indicates the Kind of the Task: 1. Namespaced Task when Kind is set to \"Task\". If Kind is \"\", it defaults to \"Task\". 2. Custom Task when Kind is non-empty and APIVersion is non-empty", Type: []string{"string"}, Format: "", }, @@ -5488,11 +5327,6 @@ func schema_pkg_apis_pipeline_v1beta1_TaskRunSpec(ref common.ReferenceCallback) }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Type: []string{"array"}, Items: &spec.SchemaOrArray{ @@ -5526,7 +5360,7 @@ func schema_pkg_apis_pipeline_v1beta1_TaskRunSpec(ref common.ReferenceCallback) }, "taskSpec": { SchemaProps: spec.SchemaProps{ - Description: "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + Description: "Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.TaskSpec"), }, }, @@ -5743,13 +5577,8 @@ func schema_pkg_apis_pipeline_v1beta1_TaskRunStatus(ref common.ReferenceCallback }, }, "retriesStatus": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ - Description: "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant.", + Description: "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant. See TaskRun.status (API version: tekton.dev/v1beta1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -5820,7 +5649,7 @@ func schema_pkg_apis_pipeline_v1beta1_TaskRunStatus(ref common.ReferenceCallback }, "taskSpec": { SchemaProps: spec.SchemaProps{ - Description: "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun.", + Description: "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun. See Task.spec (API version tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.TaskSpec"), }, }, @@ -5921,13 +5750,8 @@ func schema_pkg_apis_pipeline_v1beta1_TaskRunStatusFields(ref common.ReferenceCa }, }, "retriesStatus": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ - Description: "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant.", + Description: "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant. See TaskRun.status (API version: tekton.dev/v1beta1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -5998,7 +5822,7 @@ func schema_pkg_apis_pipeline_v1beta1_TaskRunStatusFields(ref common.ReferenceCa }, "taskSpec": { SchemaProps: spec.SchemaProps{ - Description: "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun.", + Description: "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun. See Task.spec (API version tekton.dev/v1beta1)", Ref: ref("github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1.TaskSpec"), }, }, @@ -6078,11 +5902,6 @@ func schema_pkg_apis_pipeline_v1beta1_TaskSpec(ref common.ReferenceCallback) com }, }, "params": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ Description: "Params is a list of input parameters required to run the task. Params must be supplied as inputs in TaskRuns unless they declare a default value.", Type: []string{"array"}, @@ -6130,13 +5949,8 @@ func schema_pkg_apis_pipeline_v1beta1_TaskSpec(ref common.ReferenceCallback) com }, }, "volumes": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, SchemaProps: spec.SchemaProps{ - Description: "Volumes is a collection of volumes that are available to mount into the steps of the build.", + Description: "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -6330,7 +6144,7 @@ func schema_pkg_apis_pipeline_v1beta1_WorkspaceBinding(ref common.ReferenceCallb }, "volumeClaimTemplate": { SchemaProps: spec.SchemaProps{ - Description: "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun.", + Description: "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun. See PersistentVolumeClaim (API version: v1)", Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaim"), }, }, diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/param_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/param_types.go index f0634f8c..e784a3f5 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/param_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/param_types.go @@ -54,6 +54,8 @@ type ParamSpec struct { // default is set, a Task may be executed without a supplied value for the // parameter. // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Default *ParamValue `json:"default,omitempty"` // Enum declares a set of allowed param input values for tasks/pipelines that can be validated. // If Enum is not set, no input validation is performed for the param. @@ -62,6 +64,7 @@ type ParamSpec struct { } // ParamSpecs is a list of ParamSpec +// +listType=atomic type ParamSpecs []ParamSpec // PropertySpec defines the struct for object keys @@ -137,7 +140,7 @@ func (ps ParamSpecs) validateNoDuplicateNames() *apis.FieldError { return errs } -// validateParamEnum validates feature flag, duplication and allowed types for Param Enum +// validateParamEnums validates feature flag, duplication and allowed types for Param Enum func (ps ParamSpecs) validateParamEnums(ctx context.Context) *apis.FieldError { var errs *apis.FieldError for _, p := range ps { @@ -186,11 +189,14 @@ func (pp *ParamSpec) setDefaultsForProperties() { // Param declares an ParamValues to use for the parameter called name. type Param struct { - Name string `json:"name"` + Name string `json:"name"` + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ParamValue `json:"value"` } // Params is a list of Param +// +listType=atomic type Params []Param // ExtractNames returns a set of unique names diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_types.go index 804bcbd3..7161ed29 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_types.go @@ -124,7 +124,6 @@ type PipelineSpec struct { Tasks []PipelineTask `json:"tasks,omitempty"` // Params declares a list of input parameters that must be supplied when // this Pipeline is run. - // +listType=atomic Params ParamSpecs `json:"params,omitempty"` // Workspaces declares a set of named workspaces that are expected to be // provided by a PipelineRun. @@ -157,6 +156,8 @@ type PipelineResult struct { Description string `json:"description"` // Value the expression used to retrieve the value + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ResultValue `json:"value"` } @@ -210,8 +211,11 @@ type PipelineTask struct { // TaskSpec is a specification of a task // Specifying TaskSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // `disable-inline-spec` feature flag. + // See Task.spec (API version: tekton.dev/v1beta1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless TaskSpec *EmbeddedTask `json:"taskSpec,omitempty"` // WhenExpressions is a list of when expressions that need to be true for the task to run @@ -234,7 +238,6 @@ type PipelineTask struct { // Parameters declares parameters passed to this task. // +optional - // +listType=atomic Params Params `json:"params,omitempty"` // Matrix declares parameters used to fan out this task. @@ -259,9 +262,12 @@ type PipelineTask struct { // PipelineSpec is a specification of a pipeline // Note: PipelineSpec is in preview mode and not yet supported - // Specifying TaskSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // Specifying PipelineSpec can be disabled by setting + // `disable-inline-spec` feature flag. + // See Pipeline.spec (API version: tekton.dev/v1beta1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless PipelineSpec *PipelineSpec `json:"pipelineSpec,omitempty"` // OnError defines the exiting behavior of a PipelineRun on error diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_validation.go index 8f8d6a1f..e0c9b736 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipeline_validation.go @@ -193,18 +193,9 @@ func (pt PipelineTask) Validate(ctx context.Context) (errs *apis.FieldError) { taskKinds := map[TaskKind]bool{ "": true, NamespacedTaskKind: true, - ClusterTaskKind: true, } - if pt.OnError != "" { - errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "OnError", config.BetaAPIFields)) - if pt.OnError != PipelineTaskContinue && pt.OnError != PipelineTaskStopAndFail { - errs = errs.Also(apis.ErrInvalidValue(pt.OnError, "OnError", "PipelineTask OnError must be either \"continue\" or \"stopAndFail\"")) - } - if pt.OnError == PipelineTaskContinue && pt.Retries > 0 { - errs = errs.Also(apis.ErrGeneric("PipelineTask OnError cannot be set to \"continue\" when Retries is greater than 0")) - } - } + errs = errs.Also(pt.ValidateOnError(ctx)) // Pipeline task having taskRef/taskSpec with APIVersion is classified as custom task switch { @@ -222,6 +213,20 @@ func (pt PipelineTask) Validate(ctx context.Context) (errs *apis.FieldError) { return //nolint:nakedret } +// ValidateOnError validates the OnError field of a PipelineTask +func (pt PipelineTask) ValidateOnError(ctx context.Context) (errs *apis.FieldError) { + if pt.OnError != "" && !isParamRefs(string(pt.OnError)) { + errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "OnError", config.BetaAPIFields)) + if pt.OnError != PipelineTaskContinue && pt.OnError != PipelineTaskStopAndFail { + errs = errs.Also(apis.ErrInvalidValue(pt.OnError, "OnError", "PipelineTask OnError must be either \"continue\" or \"stopAndFail\"")) + } + if pt.OnError == PipelineTaskContinue && pt.Retries > 0 { + errs = errs.Also(apis.ErrGeneric("PipelineTask OnError cannot be set to \"continue\" when Retries is greater than 0")) + } + } + return errs +} + // validateEnabledInlineSpec validates that pipelineSpec or taskSpec is allowed by checking // disable-inline-spec field func (pt PipelineTask) validateEnabledInlineSpec(ctx context.Context) (errs *apis.FieldError) { diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipelinerun_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipelinerun_types.go index 453c3778..7b2344cb 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipelinerun_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/pipelinerun_types.go @@ -253,8 +253,11 @@ type PipelineRunSpec struct { // +optional PipelineRef *PipelineRef `json:"pipelineRef,omitempty"` // Specifying PipelineSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // `disable-inline-spec` feature flag. + // See Pipeline.spec (API version: tekton.dev/v1beta1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless PipelineSpec *PipelineSpec `json:"pipelineSpec,omitempty"` // Resources is a list of bindings specifying which actual instances of // PipelineResources to use for the resources the Pipeline has declared @@ -264,7 +267,6 @@ type PipelineRunSpec struct { // +listType=atomic Resources []PipelineResourceBinding `json:"resources,omitempty"` // Params is a list of parameter names and values. - // +listType=atomic Params Params `json:"params,omitempty"` // +optional ServiceAccountName string `json:"serviceAccountName,omitempty"` @@ -477,7 +479,10 @@ type PipelineRunStatusFields struct { // +listType=atomic PipelineResults []PipelineRunResult `json:"pipelineResults,omitempty"` - // PipelineRunSpec contains the exact spec used to instantiate the run + // PipelineSpec contains the exact spec used to instantiate the run. + // See Pipeline.spec (API version: tekton.dev/v1beta1) + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless PipelineSpec *PipelineSpec `json:"pipelineSpec,omitempty"` // list of tasks that were skipped due to when expressions evaluating to false @@ -550,6 +555,8 @@ type PipelineRunResult struct { Name string `json:"name"` // Value is the result returned from the execution of this PipelineRun + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ResultValue `json:"value"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/provenance.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/provenance.go index 3ae27eb5..7fadd2c9 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/provenance.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/provenance.go @@ -44,7 +44,7 @@ type RefSource struct { // EntryPoint identifies the entry point into the build. This is often a path to a // build definition file and/or a target label within that file. - // Example: "task/git-clone/0.8/git-clone.yaml" + // Example: "task/git-clone/0.10/git-clone.yaml" EntryPoint string `json:"entryPoint,omitempty"` } @@ -62,6 +62,6 @@ type ConfigSource struct { // EntryPoint identifies the entry point into the build. This is often a path to a // build definition file and/or a target label within that file. - // Example: "task/git-clone/0.8/git-clone.yaml" + // Example: "task/git-clone/0.10/git-clone.yaml" EntryPoint string `json:"entryPoint,omitempty"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/register.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/register.go index c33fa8a8..e5164996 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/register.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/register.go @@ -50,8 +50,6 @@ func addKnownTypes(scheme *runtime.Scheme) error { &TaskList{}, &Pipeline{}, &PipelineList{}, - &ClusterTask{}, - &ClusterTaskList{}, &TaskRun{}, &TaskRunList{}, &PipelineRun{}, diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/resolver_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/resolver_types.go index 70b1c788..34e49278 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/resolver_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/resolver_types.go @@ -32,6 +32,5 @@ type ResolverRef struct { // "repo" or "path" but the set of params ultimately depends on // the chosen resolver. // +optional - // +listType=atomic Params Params `json:"params,omitempty"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_types.go index ec3192d3..302fa1b7 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_types.go @@ -35,6 +35,8 @@ type TaskResult struct { // Value the expression used to retrieve the value of the result from an underlying Step. // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value *ResultValue `json:"value,omitempty"` } @@ -49,6 +51,8 @@ type TaskRunResult struct { Type ResultsType `json:"type,omitempty"` // Value the given value of the result + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless Value ResultValue `json:"value"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_validation.go index 24162763..4bdf1a71 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/result_validation.go @@ -17,7 +17,6 @@ import ( "context" "fmt" - "github.com/tektoncd/pipeline/pkg/apis/config" v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" "k8s.io/apimachinery/pkg/util/validation" "knative.dev/pkg/apis" @@ -67,15 +66,12 @@ func validateObjectResult(tr TaskResult) (errs *apis.FieldError) { } // validateValue validates the value of the TaskResult. -// It requires that enable-step-actions is true, the value is of type string +// It requires the value is of type string // and format $(steps..results.) func (tr TaskResult) validateValue(ctx context.Context) (errs *apis.FieldError) { if tr.Value == nil { return nil } - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true to fetch Results from Steps using StepActions.", config.EnableStepActions)) - } if tr.Value.Type != ParamTypeString { return &apis.FieldError{ Message: fmt.Sprintf( diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/stepaction_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/stepaction_types.go index ab000a6d..d6276bde 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/stepaction_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/stepaction_types.go @@ -32,6 +32,7 @@ import ( // The Step can only reference it from the cluster or using remote resolution. // // +k8s:openapi-gen=true +// +kubebuilder:storageversion type StepAction struct { metav1.TypeMeta `json:",inline"` // +optional @@ -95,6 +96,9 @@ type StepActionList struct { Items []StepAction `json:"items"` } +// +listType=atomic +type Args []string + // StepActionSpec contains the actionable components of a step. type StepActionSpec struct { // Description is a user-facing description of the stepaction that may be @@ -125,8 +129,7 @@ type StepActionSpec struct { // of whether the variable exists or not. Cannot be updated. // More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell // +optional - // +listType=atomic - Args []string `json:"args,omitempty" protobuf:"bytes,4,rep,name=args"` + Args Args `json:"args,omitempty" protobuf:"bytes,4,rep,name=args"` // List of environment variables to set in the container. // Cannot be updated. // +optional @@ -148,7 +151,6 @@ type StepActionSpec struct { // Params is a list of input parameters required to run the stepAction. // Params must be supplied as inputs in Steps unless they declare a defaultvalue. // +optional - // +listType=atomic Params v1.ParamSpecs `json:"params,omitempty"` // Results are values that this StepAction can output // +optional diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/swagger.json b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/swagger.json index 7e2d8d9d..4340e774 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/swagger.json +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/swagger.json @@ -52,7 +52,7 @@ "type": "object", "properties": { "affinity": { - "description": "If specified, the pod's scheduling constraints", + "description": "If specified, the pod's scheduling constraints. See Pod.spec.affinity (API version: v1)", "$ref": "#/definitions/v1.Affinity" }, "automountServiceAccountToken": { @@ -125,7 +125,7 @@ "type": "string" }, "securityContext": { - "description": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", + "description": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. See Pod.spec.securityContext (API version: v1)", "$ref": "#/definitions/v1.PodSecurityContext" }, "tolerations": { @@ -147,13 +147,12 @@ "x-kubernetes-list-type": "atomic" }, "volumes": { - "description": "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", + "description": "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes See Pod.spec.volumes (API version: v1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Volume" }, - "x-kubernetes-list-type": "atomic", "x-kubernetes-patch-merge-key": "name", "x-kubernetes-patch-strategy": "merge,retainKeys" } @@ -294,57 +293,6 @@ } } }, - "v1beta1.ClusterTask": { - "description": "ClusterTask is a Task with a cluster scope. ClusterTasks are used to represent Tasks that should be publicly addressable from any namespace in the cluster.\n\nDeprecated: Please use the cluster resolver instead.", - "type": "object", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "default": {}, - "$ref": "#/definitions/v1.ObjectMeta" - }, - "spec": { - "description": "Spec holds the desired state of the Task from the client", - "default": {}, - "$ref": "#/definitions/v1beta1.TaskSpec" - } - } - }, - "v1beta1.ClusterTaskList": { - "description": "ClusterTaskList contains a list of ClusterTask", - "type": "object", - "required": [ - "items" - ], - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "items": { - "type": "array", - "items": { - "default": {}, - "$ref": "#/definitions/v1beta1.ClusterTask" - } - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "default": {}, - "$ref": "#/definitions/v1.ListMeta" - } - } - }, "v1beta1.ConfigSource": { "description": "ConfigSource contains the information that can uniquely identify where a remote built definition came from i.e. Git repositories, Tekton Bundles in OCI registry and hub.", "type": "object", @@ -358,7 +306,7 @@ } }, "entryPoint": { - "description": "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.8/git-clone.yaml\"", + "description": "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.10/git-clone.yaml\"", "type": "string" }, "uri": { @@ -437,8 +385,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "retries": { "description": "Used for propagating retries count to custom tasks", @@ -520,8 +467,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "resources": { "description": "Resources is a list input and output resource to run the task Resources are represented in TaskRuns as bindings to instances of PipelineResources.\n\nDeprecated: Unused, preserved only for backwards compatibility", @@ -563,13 +509,12 @@ "x-kubernetes-list-type": "atomic" }, "volumes": { - "description": "Volumes is a collection of volumes that are available to mount into the steps of the build.", + "description": "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Volume" - }, - "x-kubernetes-list-type": "atomic" + } }, "workspaces": { "description": "Workspaces are the volumes that this Task requires.", @@ -596,8 +541,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } } } }, @@ -646,8 +590,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.IncludeParams" - }, - "x-kubernetes-list-type": "atomic" + } }, "params": { "description": "Params is a list of parameters used to fan out the pipelineTask Params takes only `Parameters` of type `\"array\"` Each array element is supplied to the `PipelineTask` by substituting `params` of type `\"string\"` in the underlying `Task`. The names of the `params` in the `Matrix` must match the names of the `params` in the underlying `Task` that they will be substituting.", @@ -655,8 +598,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } } } }, @@ -1011,14 +953,13 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "pipelineRef": { "$ref": "#/definitions/v1beta1.PipelineRef" }, "pipelineSpec": { - "description": "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.PipelineSpec" }, "podTemplate": { @@ -1123,7 +1064,7 @@ "x-kubernetes-list-type": "atomic" }, "pipelineSpec": { - "description": "PipelineRunSpec contains the exact spec used to instantiate the run", + "description": "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.PipelineSpec" }, "provenance": { @@ -1198,7 +1139,7 @@ "x-kubernetes-list-type": "atomic" }, "pipelineSpec": { - "description": "PipelineRunSpec contains the exact spec used to instantiate the run", + "description": "PipelineSpec contains the exact spec used to instantiate the run. See Pipeline.spec (API version: tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.PipelineSpec" }, "provenance": { @@ -1292,8 +1233,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "resources": { "description": "Deprecated: Unused, preserved only for backwards compatibility", @@ -1363,15 +1303,14 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "pipelineRef": { "description": "PipelineRef is a reference to a pipeline definition Note: PipelineRef is in preview mode and not yet supported", "$ref": "#/definitions/v1beta1.PipelineRef" }, "pipelineSpec": { - "description": "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "PipelineSpec is a specification of a pipeline Note: PipelineSpec is in preview mode and not yet supported Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag. See Pipeline.spec (API version: tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.PipelineSpec" }, "resources": { @@ -1397,7 +1336,7 @@ "$ref": "#/definitions/v1beta1.TaskRef" }, "taskSpec": { - "description": "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "TaskSpec is a specification of a task Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.EmbeddedTask" }, "timeout": { @@ -1653,7 +1592,7 @@ } }, "entryPoint": { - "description": "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.8/git-clone.yaml\"", + "description": "EntryPoint identifies the entry point into the build. This is often a path to a build definition file and/or a target label within that file. Example: \"task/git-clone/0.10/git-clone.yaml\"", "type": "string" }, "uri": { @@ -1818,8 +1757,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "resolver": { "description": "Resolver is the name of the resolver that should perform resolution of the referenced Tekton resource, such as \"git\".", @@ -2150,8 +2088,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "ports": { "description": "List of ports to expose from the Step's container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Cannot be updated.\n\nDeprecated: This field will be removed in a future release.", @@ -2182,7 +2119,7 @@ "$ref": "#/definitions/v1.ResourceRequirements" }, "results": { - "description": "Results declares StepResults produced by the Step.\n\nThis is field is at an ALPHA stability level and gated by \"enable-step-actions\" feature flag.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1beta1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", + "description": "Results declares StepResults produced by the Step.\n\nIt can be used in an inlined Step when used to store Results to $(step.results.resultName.path). It cannot be used when referencing StepActions using [v1beta1.Step.Ref]. The Results declared by the StepActions will be stored here instead.", "type": "array", "items": { "default": {}, @@ -2339,8 +2276,7 @@ "items": { "type": "string", "default": "" - }, - "x-kubernetes-list-type": "atomic" + } }, "command": { "description": "Entrypoint array. Not executed within a shell. The image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", @@ -2376,8 +2312,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "results": { "description": "Results are values that this StepAction can output", @@ -2702,7 +2637,7 @@ "type": "string" }, "kind": { - "description": "TaskKind indicates the Kind of the Task: 1. Namespaced Task when Kind is set to \"Task\". If Kind is \"\", it defaults to \"Task\". 2. Cluster-Scoped Task when Kind is set to \"ClusterTask\" 3. Custom Task when Kind is non-empty and APIVersion is non-empty", + "description": "TaskKind indicates the Kind of the Task: 1. Namespaced Task when Kind is set to \"Task\". If Kind is \"\", it defaults to \"Task\". 2. Custom Task when Kind is non-empty and APIVersion is non-empty", "type": "string" }, "name": { @@ -3010,8 +2945,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.Param" - }, - "x-kubernetes-list-type": "atomic" + } }, "podTemplate": { "description": "PodTemplate holds pod specific configuration", @@ -3061,7 +2995,7 @@ "$ref": "#/definitions/v1beta1.TaskRef" }, "taskSpec": { - "description": "Specifying PipelineSpec can be disabled by setting `disable-inline-spec` feature flag..", + "description": "Specifying TaskSpec can be disabled by setting `disable-inline-spec` feature flag. See Task.spec (API version: tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.TaskSpec" }, "timeout": { @@ -3141,13 +3075,12 @@ "x-kubernetes-list-type": "atomic" }, "retriesStatus": { - "description": "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant.", + "description": "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant. See TaskRun.status (API version: tekton.dev/v1beta1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1beta1.TaskRunStatus" - }, - "x-kubernetes-list-type": "atomic" + } }, "sidecars": { "description": "The list has one entry per sidecar in the manifest. Each entry is represents the imageid of the corresponding sidecar.", @@ -3189,7 +3122,7 @@ "x-kubernetes-list-type": "atomic" }, "taskSpec": { - "description": "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun.", + "description": "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun. See Task.spec (API version tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.TaskSpec" } } @@ -3233,13 +3166,12 @@ "x-kubernetes-list-type": "atomic" }, "retriesStatus": { - "description": "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant.", + "description": "RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant. See TaskRun.status (API version: tekton.dev/v1beta1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1beta1.TaskRunStatus" - }, - "x-kubernetes-list-type": "atomic" + } }, "sidecars": { "description": "The list has one entry per sidecar in the manifest. Each entry is represents the imageid of the corresponding sidecar.", @@ -3281,7 +3213,7 @@ "x-kubernetes-list-type": "atomic" }, "taskSpec": { - "description": "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun.", + "description": "TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun. See Task.spec (API version tekton.dev/v1beta1)", "$ref": "#/definitions/v1beta1.TaskSpec" } } @@ -3324,8 +3256,7 @@ "items": { "default": {}, "$ref": "#/definitions/v1beta1.ParamSpec" - }, - "x-kubernetes-list-type": "atomic" + } }, "resources": { "description": "Resources is a list input and output resource to run the task Resources are represented in TaskRuns as bindings to instances of PipelineResources.\n\nDeprecated: Unused, preserved only for backwards compatibility", @@ -3363,13 +3294,12 @@ "x-kubernetes-list-type": "atomic" }, "volumes": { - "description": "Volumes is a collection of volumes that are available to mount into the steps of the build.", + "description": "Volumes is a collection of volumes that are available to mount into the steps of the build. See Pod.spec.volumes (API version: v1)", "type": "array", "items": { "default": {}, "$ref": "#/definitions/v1.Volume" - }, - "x-kubernetes-list-type": "atomic" + } }, "workspaces": { "description": "Workspaces are the volumes that this Task requires.", @@ -3468,7 +3398,7 @@ "type": "string" }, "volumeClaimTemplate": { - "description": "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun.", + "description": "VolumeClaimTemplate is a template for a claim that will be created in the same namespace. The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun. See PersistentVolumeClaim (API version: v1)", "$ref": "#/definitions/v1.PersistentVolumeClaim" } } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_conversion.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_conversion.go index 9a0d4fe5..c1f7b866 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_conversion.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_conversion.go @@ -89,7 +89,7 @@ func (ts *TaskSpec) ConvertTo(ctx context.Context, sink *v1.TaskSpec, meta *meta s.convertTo(ctx, &new) sink.Steps = append(sink.Steps, new) } - sink.Volumes = ts.Volumes + sink.Volumes = v1.Volumes(ts.Volumes) if ts.StepTemplate != nil { new := v1.StepTemplate{} ts.StepTemplate.convertTo(ctx, &new) @@ -149,7 +149,7 @@ func (ts *TaskSpec) ConvertFrom(ctx context.Context, source *v1.TaskSpec, meta * new.convertFrom(ctx, s) ts.Steps = append(ts.Steps, new) } - ts.Volumes = source.Volumes + ts.Volumes = Volumes(source.Volumes) if source.StepTemplate != nil { new := StepTemplate{} new.convertFrom(ctx, source.StepTemplate) diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_interface.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_interface.go index ac018081..91acc832 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_interface.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_interface.go @@ -21,7 +21,7 @@ import ( "knative.dev/pkg/apis" ) -// TaskObject is implemented by Task and ClusterTask +// TaskObject is implemented by Task type TaskObject interface { apis.Defaultable TaskMetadata() metav1.ObjectMeta diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_types.go index 2961ade3..7f1d8c1e 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_types.go @@ -90,6 +90,9 @@ func (t *Task) Checksum() ([]byte, error) { return sha256Checksum, nil } +// +listType=atomic +type Volumes []corev1.Volume + // TaskSpec defines the desired state of Task. type TaskSpec struct { // Resources is a list input and output resource to run the task @@ -104,7 +107,6 @@ type TaskSpec struct { // must be supplied as inputs in TaskRuns unless they declare a default // value. // +optional - // +listType=atomic Params ParamSpecs `json:"params,omitempty"` // DisplayName is a user-facing name of the task that may be @@ -124,8 +126,10 @@ type TaskSpec struct { // Volumes is a collection of volumes that are available to mount into the // steps of the build. - // +listType=atomic - Volumes []corev1.Volume `json:"volumes,omitempty"` + // See Pod.spec.volumes (API version: v1) + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + Volumes Volumes `json:"volumes,omitempty"` // StepTemplate can be used as the basis for all step containers within the // Task, so that the steps inherit settings on the base container. diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_validation.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_validation.go index 4d03a950..c2d918d4 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_validation.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/task_validation.go @@ -20,8 +20,8 @@ import ( "context" "fmt" "path/filepath" - "reflect" "regexp" + "slices" "strings" "time" @@ -33,7 +33,6 @@ import ( "github.com/tektoncd/pipeline/pkg/internal/resultref" "github.com/tektoncd/pipeline/pkg/substitution" - "golang.org/x/exp/slices" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/sets" @@ -256,42 +255,6 @@ func validateSteps(ctx context.Context, steps []Step) (errs *apis.FieldError) { return errs } -// isCreateOrUpdateAndDiverged checks if the webhook event was create or update -// if create, it returns true. -// if update, it checks if the step results have diverged and returns if diverged. -// if neither, it returns false. -func isCreateOrUpdateAndDiverged(ctx context.Context, s Step) bool { - if apis.IsInCreate(ctx) { - return true - } - if apis.IsInUpdate(ctx) { - baseline := apis.GetBaseline(ctx) - var baselineStep Step - switch o := baseline.(type) { - case *TaskRun: - if o.Spec.TaskSpec != nil { - for _, step := range o.Spec.TaskSpec.Steps { - if s.Name == step.Name { - baselineStep = step - break - } - } - } - default: - // the baseline is not a taskrun. - // return true so that the validation can happen - return true - } - // If an update event, check if the results have diverged from the baseline - // this way, the feature flag check wont happen. - // This will avoid issues like https://github.com/tektoncd/pipeline/issues/5203 - // when the feature is turned off mid-run. - diverged := !reflect.DeepEqual(s.Results, baselineStep.Results) - return diverged - } - return false -} - func errorIfStepResultReferenceinField(value, fieldName string) (errs *apis.FieldError) { matches := resultref.StepResultRegex.FindAllStringSubmatch(value, -1) if len(matches) > 0 { @@ -324,7 +287,7 @@ func errorIfStepArtifactReferencedInField(value, fieldName string) (errs *apis.F func validateStepArtifactsReference(s Step) (errs *apis.FieldError) { errs = errs.Also(errorIfStepArtifactReferencedInField(s.Name, "name")) errs = errs.Also(errorIfStepArtifactReferencedInField(s.Image, "image")) - errs = errs.Also(errorIfStepArtifactReferencedInField(string(s.ImagePullPolicy), "imagePullPoliicy")) + errs = errs.Also(errorIfStepArtifactReferencedInField(string(s.ImagePullPolicy), "imagePullPolicy")) errs = errs.Also(errorIfStepArtifactReferencedInField(s.WorkingDir, "workingDir")) for _, e := range s.EnvFrom { errs = errs.Also(errorIfStepArtifactReferencedInField(e.Prefix, "envFrom.prefix")) @@ -351,7 +314,7 @@ func validateStepResultReference(s Step) (errs *apis.FieldError) { errs = errs.Also(errorIfStepResultReferenceinField(s.Name, "name")) errs = errs.Also(errorIfStepResultReferenceinField(s.Image, "image")) errs = errs.Also(errorIfStepResultReferenceinField(s.Script, "script")) - errs = errs.Also(errorIfStepResultReferenceinField(string(s.ImagePullPolicy), "imagePullPoliicy")) + errs = errs.Also(errorIfStepResultReferenceinField(string(s.ImagePullPolicy), "imagePullPolicy")) errs = errs.Also(errorIfStepResultReferenceinField(s.WorkingDir, "workingDir")) for _, e := range s.EnvFrom { errs = errs.Also(errorIfStepResultReferenceinField(e.Prefix, "envFrom.prefix")) @@ -380,9 +343,6 @@ func validateStep(ctx context.Context, s Step, names sets.String) (errs *apis.Fi } if s.Ref != nil { - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions && isCreateOrUpdateAndDiverged(ctx, s) { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true to reference StepActions in Steps.", config.EnableStepActions), "") - } errs = errs.Also(s.Ref.Validate(ctx)) if s.Image != "" { errs = errs.Also(&apis.FieldError{ @@ -439,16 +399,6 @@ func validateStep(ctx context.Context, s Step, names sets.String) (errs *apis.Fi Paths: []string{"params"}, }) } - if len(s.Results) > 0 { - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions && isCreateOrUpdateAndDiverged(ctx, s) { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true in order to use Results in Steps.", config.EnableStepActions), "") - } - } - if len(s.When) > 0 { - if !config.FromContextOrDefaults(ctx).FeatureFlags.EnableStepActions && isCreateOrUpdateAndDiverged(ctx, s) { - return apis.ErrGeneric(fmt.Sprintf("feature flag %s should be set to true in order to use When in Steps.", config.EnableStepActions), "") - } - } if s.Image == "" { errs = errs.Also(apis.ErrMissingField("Image")) } @@ -640,7 +590,7 @@ func validateTaskResultsVariables(ctx context.Context, steps []Step, results []T resultsNames.Insert(r.Name) } for idx, step := range steps { - errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(step.Script, "results", resultsNames).ViaField("script").ViaFieldIndex("steps", idx)) + errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariablesWithDetail(step.Script, "results", resultsNames).ViaField("script").ViaFieldIndex("steps", idx)) } return errs } @@ -790,7 +740,7 @@ func validateStepVariables(ctx context.Context, step Step, prefix string, vars s errs := substitution.ValidateNoReferencesToUnknownVariables(step.Name, prefix, vars).ViaField("name") errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(step.Image, prefix, vars).ViaField("image")) errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(step.WorkingDir, prefix, vars).ViaField("workingDir")) - errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(step.Script, prefix, vars).ViaField("script")) + errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariablesWithDetail(step.Script, prefix, vars).ViaField("script")) for i, cmd := range step.Command { errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(cmd, prefix, vars).ViaFieldIndex("command", i)) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskref_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskref_types.go index 9781a4a2..b3bb2c9f 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskref_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskref_types.go @@ -22,8 +22,7 @@ type TaskRef struct { Name string `json:"name,omitempty"` // TaskKind indicates the Kind of the Task: // 1. Namespaced Task when Kind is set to "Task". If Kind is "", it defaults to "Task". - // 2. Cluster-Scoped Task when Kind is set to "ClusterTask" - // 3. Custom Task when Kind is non-empty and APIVersion is non-empty + // 2. Custom Task when Kind is non-empty and APIVersion is non-empty Kind TaskKind `json:"kind,omitempty"` // API version of the referent // Note: A Task with non-empty APIVersion and Kind is considered a Custom Task @@ -51,8 +50,6 @@ type TaskKind string const ( // NamespacedTaskKind indicates that the task type has a namespaced scope. NamespacedTaskKind TaskKind = "Task" - // ClusterTaskKind indicates that task type has a cluster scope. - ClusterTaskKind TaskKind = "ClusterTask" ) // IsCustomTask checks whether the reference is to a Custom Task diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskrun_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskrun_types.go index 2cd76f0e..bc7870d6 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskrun_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/taskrun_types.go @@ -39,7 +39,6 @@ type TaskRunSpec struct { // +optional Debug *TaskRunDebug `json:"debug,omitempty"` // +optional - // +listType=atomic Params Params `json:"params,omitempty"` // Deprecated: Unused, preserved only for backwards compatibility // +optional @@ -49,9 +48,12 @@ type TaskRunSpec struct { // no more than one of the TaskRef and TaskSpec may be specified. // +optional TaskRef *TaskRef `json:"taskRef,omitempty"` - // Specifying PipelineSpec can be disabled by setting - // `disable-inline-spec` feature flag.. + // Specifying TaskSpec can be disabled by setting + // `disable-inline-spec` feature flag. + // See Task.spec (API version: tekton.dev/v1beta1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless TaskSpec *TaskSpec `json:"taskSpec,omitempty"` // Used for cancelling a TaskRun (and maybe more later on) // +optional @@ -265,6 +267,9 @@ func (trs *TaskRunStatus) MarkResourceFailed(reason TaskRunReason, err error) { trs.CompletionTime = &succeeded.LastTransitionTime.Inner } +// +listType=atomic +type RetriesStatus []TaskRunStatus + // TaskRunStatusFields holds the fields of TaskRun's status. This is defined // separately and inlined so that other types can readily consume these fields // via duck typing. @@ -294,9 +299,11 @@ type TaskRunStatusFields struct { // RetriesStatus contains the history of TaskRunStatus in case of a retry in order to keep record of failures. // All TaskRunStatus stored in RetriesStatus will have no date within the RetriesStatus as is redundant. + // See TaskRun.status (API version: tekton.dev/v1beta1) // +optional - // +listType=atomic - RetriesStatus []TaskRunStatus `json:"retriesStatus,omitempty"` + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + RetriesStatus RetriesStatus `json:"retriesStatus,omitempty"` // Results from Resources built during the TaskRun. // This is tomb-stoned along with the removal of pipelineResources @@ -316,6 +323,9 @@ type TaskRunStatusFields struct { Sidecars []SidecarState `json:"sidecars,omitempty"` // TaskSpec contains the Spec from the dereferenced Task definition used to instantiate this TaskRun. + // See Task.spec (API version tekton.dev/v1beta1) + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless TaskSpec *TaskSpec `json:"taskSpec,omitempty"` // Provenance contains some key authenticated metadata about how a software artifact was built (what sources, what inputs/outputs, etc.). diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/workspace_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/workspace_types.go index 194821af..8d49ad98 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/workspace_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/workspace_types.go @@ -60,7 +60,10 @@ type WorkspaceBinding struct { SubPath string `json:"subPath,omitempty"` // VolumeClaimTemplate is a template for a claim that will be created in the same namespace. // The PipelineRun controller is responsible for creating a unique claim for each instance of PipelineRun. + // See PersistentVolumeClaim (API version: v1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless VolumeClaimTemplate *corev1.PersistentVolumeClaim `json:"volumeClaimTemplate,omitempty"` // PersistentVolumeClaimVolumeSource represents a reference to a // PersistentVolumeClaim in the same namespace. Either this OR EmptyDir can be used. diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/zz_generated.deepcopy.go index 8c2afe35..e80d3ba3 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/zz_generated.deepcopy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1/zz_generated.deepcopy.go @@ -33,6 +33,26 @@ import ( runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in Args) DeepCopyInto(out *Args) { + { + in := &in + *out = make(Args, len(*in)) + copy(*out, *in) + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Args. +func (in Args) DeepCopy() Args { + if in == nil { + return nil + } + out := new(Args) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Artifact) DeepCopyInto(out *Artifact) { *out = *in @@ -170,66 +190,6 @@ func (in *CloudEventDeliveryState) DeepCopy() *CloudEventDeliveryState { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterTask) DeepCopyInto(out *ClusterTask) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterTask. -func (in *ClusterTask) DeepCopy() *ClusterTask { - if in == nil { - return nil - } - out := new(ClusterTask) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterTask) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterTaskList) DeepCopyInto(out *ClusterTaskList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ClusterTask, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterTaskList. -func (in *ClusterTaskList) DeepCopy() *ClusterTaskList { - if in == nil { - return nil - } - out := new(ClusterTaskList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterTaskList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in Combination) DeepCopyInto(out *Combination) { { @@ -1621,6 +1581,28 @@ func (in *ResultRef) DeepCopy() *ResultRef { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in RetriesStatus) DeepCopyInto(out *RetriesStatus) { + { + in := &in + *out = make(RetriesStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RetriesStatus. +func (in RetriesStatus) DeepCopy() RetriesStatus { + if in == nil { + return nil + } + out := new(RetriesStatus) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Sidecar) DeepCopyInto(out *Sidecar) { *out = *in @@ -1953,7 +1935,7 @@ func (in *StepActionSpec) DeepCopyInto(out *StepActionSpec) { } if in.Args != nil { in, out := &in.Args, &out.Args - *out = make([]string, len(*in)) + *out = make(Args, len(*in)) copy(*out, *in) } if in.Env != nil { @@ -2658,7 +2640,7 @@ func (in *TaskRunStatusFields) DeepCopyInto(out *TaskRunStatusFields) { } if in.RetriesStatus != nil { in, out := &in.RetriesStatus, &out.RetriesStatus - *out = make([]TaskRunStatus, len(*in)) + *out = make(RetriesStatus, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -2753,7 +2735,7 @@ func (in *TaskSpec) DeepCopyInto(out *TaskSpec) { } if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes - *out = make([]corev1.Volume, len(*in)) + *out = make(Volumes, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -2826,6 +2808,28 @@ func (in *TimeoutFields) DeepCopy() *TimeoutFields { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in Volumes) DeepCopyInto(out *Volumes) { + { + in := &in + *out = make(Volumes, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Volumes. +func (in Volumes) DeepCopy() Volumes { + if in == nil { + return nil + } + out := new(Volumes) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WhenExpression) DeepCopyInto(out *WhenExpression) { *out = *in diff --git a/vendor/github.com/tektoncd/pipeline/pkg/apis/run/v1beta1/customrunstatus_types.go b/vendor/github.com/tektoncd/pipeline/pkg/apis/run/v1beta1/customrunstatus_types.go index 2f8d9847..511e815e 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/apis/run/v1beta1/customrunstatus_types.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/apis/run/v1beta1/customrunstatus_types.go @@ -59,11 +59,16 @@ type CustomRunStatusFields struct { Results []CustomRunResult `json:"results,omitempty"` // RetriesStatus contains the history of CustomRunStatus, in case of a retry. + // See CustomRun.status (API version: tekton.dev/v1beta1) // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless RetriesStatus []CustomRunStatus `json:"retriesStatus,omitempty"` // ExtraFields holds arbitrary fields provided by the custom task // controller. + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless ExtraFields runtime.RawExtension `json:"extraFields,omitempty"` } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/clientset.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/clientset.go index 56848e8d..b2f52f99 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/clientset.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/clientset.go @@ -19,8 +19,8 @@ limitations under the License. package versioned import ( - "fmt" - "net/http" + fmt "fmt" + http "net/http" tektonv1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1" tektonv1alpha1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1" diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/doc.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/doc.go deleted file mode 100644 index 0d13552a..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated clientset. -package versioned diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake/clientset_generated.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake/clientset_generated.go index 98218788..9dc230fb 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -35,8 +35,12 @@ import ( // NewSimpleClientset returns a clientset that will respond with the provided objects. // It's backed by a very simple object tracker that processes creates, updates and deletions as-is, -// without applying any validations and/or defaults. It shouldn't be considered a replacement +// without applying any field management, validations and/or defaults. It shouldn't be considered a replacement // for a real clientset and is mostly useful in simple unit tests. +// +// DEPRECATED: NewClientset replaces this with support for field management, which significantly improves +// server side apply testing. NewClientset is only available when apply configurations are generated (e.g. +// via --with-applyconfig). func NewSimpleClientset(objects ...runtime.Object) *Clientset { o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder()) for _, obj := range objects { diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline.go index 8df2f03e..9cbfb5f5 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline.go @@ -19,111 +19,30 @@ limitations under the License. package fake import ( - "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1" + gentype "k8s.io/client-go/gentype" ) -// FakePipelines implements PipelineInterface -type FakePipelines struct { +// fakePipelines implements PipelineInterface +type fakePipelines struct { + *gentype.FakeClientWithList[*v1.Pipeline, *v1.PipelineList] Fake *FakeTektonV1 - ns string -} - -var pipelinesResource = v1.SchemeGroupVersion.WithResource("pipelines") - -var pipelinesKind = v1.SchemeGroupVersion.WithKind("Pipeline") - -// Get takes name of the pipeline, and returns the corresponding pipeline object, and an error if there is any. -func (c *FakePipelines) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(pipelinesResource, c.ns, name), &v1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.Pipeline), err -} - -// List takes label and field selectors, and returns the list of Pipelines that match those selectors. -func (c *FakePipelines) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PipelineList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(pipelinesResource, pipelinesKind, c.ns, opts), &v1.PipelineList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1.PipelineList{ListMeta: obj.(*v1.PipelineList).ListMeta} - for _, item := range obj.(*v1.PipelineList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested pipelines. -func (c *FakePipelines) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(pipelinesResource, c.ns, opts)) - -} - -// Create takes the representation of a pipeline and creates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *FakePipelines) Create(ctx context.Context, pipeline *v1.Pipeline, opts metav1.CreateOptions) (result *v1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(pipelinesResource, c.ns, pipeline), &v1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.Pipeline), err -} - -// Update takes the representation of a pipeline and updates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *FakePipelines) Update(ctx context.Context, pipeline *v1.Pipeline, opts metav1.UpdateOptions) (result *v1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(pipelinesResource, c.ns, pipeline), &v1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.Pipeline), err -} - -// Delete takes name of the pipeline and deletes it. Returns an error if one occurs. -func (c *FakePipelines) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(pipelinesResource, c.ns, name, opts), &v1.Pipeline{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakePipelines) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - action := testing.NewDeleteCollectionAction(pipelinesResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1.PipelineList{}) - return err -} - -// Patch applies the patch and returns the patched pipeline. -func (c *FakePipelines) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(pipelinesResource, c.ns, name, pt, data, subresources...), &v1.Pipeline{}) - - if obj == nil { - return nil, err +func newFakePipelines(fake *FakeTektonV1, namespace string) pipelinev1.PipelineInterface { + return &fakePipelines{ + gentype.NewFakeClientWithList[*v1.Pipeline, *v1.PipelineList]( + fake.Fake, + namespace, + v1.SchemeGroupVersion.WithResource("pipelines"), + v1.SchemeGroupVersion.WithKind("Pipeline"), + func() *v1.Pipeline { return &v1.Pipeline{} }, + func() *v1.PipelineList { return &v1.PipelineList{} }, + func(dst, src *v1.PipelineList) { dst.ListMeta = src.ListMeta }, + func(list *v1.PipelineList) []*v1.Pipeline { return gentype.ToPointerSlice(list.Items) }, + func(list *v1.PipelineList, items []*v1.Pipeline) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, } - return obj.(*v1.Pipeline), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline_client.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline_client.go index 8b2549cf..9c1aaf02 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline_client.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipeline_client.go @@ -29,19 +29,19 @@ type FakeTektonV1 struct { } func (c *FakeTektonV1) Pipelines(namespace string) v1.PipelineInterface { - return &FakePipelines{c, namespace} + return newFakePipelines(c, namespace) } func (c *FakeTektonV1) PipelineRuns(namespace string) v1.PipelineRunInterface { - return &FakePipelineRuns{c, namespace} + return newFakePipelineRuns(c, namespace) } func (c *FakeTektonV1) Tasks(namespace string) v1.TaskInterface { - return &FakeTasks{c, namespace} + return newFakeTasks(c, namespace) } func (c *FakeTektonV1) TaskRuns(namespace string) v1.TaskRunInterface { - return &FakeTaskRuns{c, namespace} + return newFakeTaskRuns(c, namespace) } // RESTClient returns a RESTClient that is used to communicate diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipelinerun.go index ab540607..4b727f67 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_pipelinerun.go @@ -19,123 +19,30 @@ limitations under the License. package fake import ( - "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1" + gentype "k8s.io/client-go/gentype" ) -// FakePipelineRuns implements PipelineRunInterface -type FakePipelineRuns struct { +// fakePipelineRuns implements PipelineRunInterface +type fakePipelineRuns struct { + *gentype.FakeClientWithList[*v1.PipelineRun, *v1.PipelineRunList] Fake *FakeTektonV1 - ns string -} - -var pipelinerunsResource = v1.SchemeGroupVersion.WithResource("pipelineruns") - -var pipelinerunsKind = v1.SchemeGroupVersion.WithKind("PipelineRun") - -// Get takes name of the pipelineRun, and returns the corresponding pipelineRun object, and an error if there is any. -func (c *FakePipelineRuns) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(pipelinerunsResource, c.ns, name), &v1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.PipelineRun), err -} - -// List takes label and field selectors, and returns the list of PipelineRuns that match those selectors. -func (c *FakePipelineRuns) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PipelineRunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(pipelinerunsResource, pipelinerunsKind, c.ns, opts), &v1.PipelineRunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1.PipelineRunList{ListMeta: obj.(*v1.PipelineRunList).ListMeta} - for _, item := range obj.(*v1.PipelineRunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested pipelineRuns. -func (c *FakePipelineRuns) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(pipelinerunsResource, c.ns, opts)) - -} - -// Create takes the representation of a pipelineRun and creates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *FakePipelineRuns) Create(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.CreateOptions) (result *v1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(pipelinerunsResource, c.ns, pipelineRun), &v1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.PipelineRun), err -} - -// Update takes the representation of a pipelineRun and updates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *FakePipelineRuns) Update(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.UpdateOptions) (result *v1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(pipelinerunsResource, c.ns, pipelineRun), &v1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.PipelineRun), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakePipelineRuns) UpdateStatus(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.UpdateOptions) (*v1.PipelineRun, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(pipelinerunsResource, "status", c.ns, pipelineRun), &v1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.PipelineRun), err -} - -// Delete takes name of the pipelineRun and deletes it. Returns an error if one occurs. -func (c *FakePipelineRuns) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(pipelinerunsResource, c.ns, name, opts), &v1.PipelineRun{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakePipelineRuns) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - action := testing.NewDeleteCollectionAction(pipelinerunsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1.PipelineRunList{}) - return err -} - -// Patch applies the patch and returns the patched pipelineRun. -func (c *FakePipelineRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(pipelinerunsResource, c.ns, name, pt, data, subresources...), &v1.PipelineRun{}) - - if obj == nil { - return nil, err +func newFakePipelineRuns(fake *FakeTektonV1, namespace string) pipelinev1.PipelineRunInterface { + return &fakePipelineRuns{ + gentype.NewFakeClientWithList[*v1.PipelineRun, *v1.PipelineRunList]( + fake.Fake, + namespace, + v1.SchemeGroupVersion.WithResource("pipelineruns"), + v1.SchemeGroupVersion.WithKind("PipelineRun"), + func() *v1.PipelineRun { return &v1.PipelineRun{} }, + func() *v1.PipelineRunList { return &v1.PipelineRunList{} }, + func(dst, src *v1.PipelineRunList) { dst.ListMeta = src.ListMeta }, + func(list *v1.PipelineRunList) []*v1.PipelineRun { return gentype.ToPointerSlice(list.Items) }, + func(list *v1.PipelineRunList, items []*v1.PipelineRun) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, } - return obj.(*v1.PipelineRun), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_task.go index 926feffe..c16fcaf1 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_task.go @@ -19,111 +19,30 @@ limitations under the License. package fake import ( - "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1" + gentype "k8s.io/client-go/gentype" ) -// FakeTasks implements TaskInterface -type FakeTasks struct { +// fakeTasks implements TaskInterface +type fakeTasks struct { + *gentype.FakeClientWithList[*v1.Task, *v1.TaskList] Fake *FakeTektonV1 - ns string -} - -var tasksResource = v1.SchemeGroupVersion.WithResource("tasks") - -var tasksKind = v1.SchemeGroupVersion.WithKind("Task") - -// Get takes name of the task, and returns the corresponding task object, and an error if there is any. -func (c *FakeTasks) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(tasksResource, c.ns, name), &v1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.Task), err -} - -// List takes label and field selectors, and returns the list of Tasks that match those selectors. -func (c *FakeTasks) List(ctx context.Context, opts metav1.ListOptions) (result *v1.TaskList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(tasksResource, tasksKind, c.ns, opts), &v1.TaskList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1.TaskList{ListMeta: obj.(*v1.TaskList).ListMeta} - for _, item := range obj.(*v1.TaskList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested tasks. -func (c *FakeTasks) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(tasksResource, c.ns, opts)) - -} - -// Create takes the representation of a task and creates it. Returns the server's representation of the task, and an error, if there is any. -func (c *FakeTasks) Create(ctx context.Context, task *v1.Task, opts metav1.CreateOptions) (result *v1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(tasksResource, c.ns, task), &v1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.Task), err -} - -// Update takes the representation of a task and updates it. Returns the server's representation of the task, and an error, if there is any. -func (c *FakeTasks) Update(ctx context.Context, task *v1.Task, opts metav1.UpdateOptions) (result *v1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(tasksResource, c.ns, task), &v1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.Task), err -} - -// Delete takes name of the task and deletes it. Returns an error if one occurs. -func (c *FakeTasks) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(tasksResource, c.ns, name, opts), &v1.Task{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeTasks) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - action := testing.NewDeleteCollectionAction(tasksResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1.TaskList{}) - return err -} - -// Patch applies the patch and returns the patched task. -func (c *FakeTasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(tasksResource, c.ns, name, pt, data, subresources...), &v1.Task{}) - - if obj == nil { - return nil, err +func newFakeTasks(fake *FakeTektonV1, namespace string) pipelinev1.TaskInterface { + return &fakeTasks{ + gentype.NewFakeClientWithList[*v1.Task, *v1.TaskList]( + fake.Fake, + namespace, + v1.SchemeGroupVersion.WithResource("tasks"), + v1.SchemeGroupVersion.WithKind("Task"), + func() *v1.Task { return &v1.Task{} }, + func() *v1.TaskList { return &v1.TaskList{} }, + func(dst, src *v1.TaskList) { dst.ListMeta = src.ListMeta }, + func(list *v1.TaskList) []*v1.Task { return gentype.ToPointerSlice(list.Items) }, + func(list *v1.TaskList, items []*v1.Task) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, } - return obj.(*v1.Task), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_taskrun.go index 95773426..d345ec00 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/fake/fake_taskrun.go @@ -19,123 +19,30 @@ limitations under the License. package fake import ( - "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1" + gentype "k8s.io/client-go/gentype" ) -// FakeTaskRuns implements TaskRunInterface -type FakeTaskRuns struct { +// fakeTaskRuns implements TaskRunInterface +type fakeTaskRuns struct { + *gentype.FakeClientWithList[*v1.TaskRun, *v1.TaskRunList] Fake *FakeTektonV1 - ns string -} - -var taskrunsResource = v1.SchemeGroupVersion.WithResource("taskruns") - -var taskrunsKind = v1.SchemeGroupVersion.WithKind("TaskRun") - -// Get takes name of the taskRun, and returns the corresponding taskRun object, and an error if there is any. -func (c *FakeTaskRuns) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(taskrunsResource, c.ns, name), &v1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.TaskRun), err -} - -// List takes label and field selectors, and returns the list of TaskRuns that match those selectors. -func (c *FakeTaskRuns) List(ctx context.Context, opts metav1.ListOptions) (result *v1.TaskRunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(taskrunsResource, taskrunsKind, c.ns, opts), &v1.TaskRunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1.TaskRunList{ListMeta: obj.(*v1.TaskRunList).ListMeta} - for _, item := range obj.(*v1.TaskRunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested taskRuns. -func (c *FakeTaskRuns) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(taskrunsResource, c.ns, opts)) - -} - -// Create takes the representation of a taskRun and creates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *FakeTaskRuns) Create(ctx context.Context, taskRun *v1.TaskRun, opts metav1.CreateOptions) (result *v1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(taskrunsResource, c.ns, taskRun), &v1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.TaskRun), err -} - -// Update takes the representation of a taskRun and updates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *FakeTaskRuns) Update(ctx context.Context, taskRun *v1.TaskRun, opts metav1.UpdateOptions) (result *v1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(taskrunsResource, c.ns, taskRun), &v1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.TaskRun), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeTaskRuns) UpdateStatus(ctx context.Context, taskRun *v1.TaskRun, opts metav1.UpdateOptions) (*v1.TaskRun, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(taskrunsResource, "status", c.ns, taskRun), &v1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1.TaskRun), err -} - -// Delete takes name of the taskRun and deletes it. Returns an error if one occurs. -func (c *FakeTaskRuns) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(taskrunsResource, c.ns, name, opts), &v1.TaskRun{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeTaskRuns) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - action := testing.NewDeleteCollectionAction(taskrunsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1.TaskRunList{}) - return err -} - -// Patch applies the patch and returns the patched taskRun. -func (c *FakeTaskRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(taskrunsResource, c.ns, name, pt, data, subresources...), &v1.TaskRun{}) - - if obj == nil { - return nil, err +func newFakeTaskRuns(fake *FakeTektonV1, namespace string) pipelinev1.TaskRunInterface { + return &fakeTaskRuns{ + gentype.NewFakeClientWithList[*v1.TaskRun, *v1.TaskRunList]( + fake.Fake, + namespace, + v1.SchemeGroupVersion.WithResource("taskruns"), + v1.SchemeGroupVersion.WithKind("TaskRun"), + func() *v1.TaskRun { return &v1.TaskRun{} }, + func() *v1.TaskRunList { return &v1.TaskRunList{} }, + func(dst, src *v1.TaskRunList) { dst.ListMeta = src.ListMeta }, + func(list *v1.TaskRunList) []*v1.TaskRun { return gentype.ToPointerSlice(list.Items) }, + func(list *v1.TaskRunList, items []*v1.TaskRun) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, } - return obj.(*v1.TaskRun), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline.go index 38a3b33f..faca0148 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline.go @@ -19,15 +19,14 @@ limitations under the License. package v1 import ( - "context" - "time" + context "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // PipelinesGetter has a method to return a PipelineInterface. @@ -38,141 +37,32 @@ type PipelinesGetter interface { // PipelineInterface has methods to work with Pipeline resources. type PipelineInterface interface { - Create(ctx context.Context, pipeline *v1.Pipeline, opts metav1.CreateOptions) (*v1.Pipeline, error) - Update(ctx context.Context, pipeline *v1.Pipeline, opts metav1.UpdateOptions) (*v1.Pipeline, error) + Create(ctx context.Context, pipeline *pipelinev1.Pipeline, opts metav1.CreateOptions) (*pipelinev1.Pipeline, error) + Update(ctx context.Context, pipeline *pipelinev1.Pipeline, opts metav1.UpdateOptions) (*pipelinev1.Pipeline, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error - Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Pipeline, error) - List(ctx context.Context, opts metav1.ListOptions) (*v1.PipelineList, error) + Get(ctx context.Context, name string, opts metav1.GetOptions) (*pipelinev1.Pipeline, error) + List(ctx context.Context, opts metav1.ListOptions) (*pipelinev1.PipelineList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pipeline, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *pipelinev1.Pipeline, err error) PipelineExpansion } // pipelines implements PipelineInterface type pipelines struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1.Pipeline, *pipelinev1.PipelineList] } // newPipelines returns a Pipelines func newPipelines(c *TektonV1Client, namespace string) *pipelines { return &pipelines{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1.Pipeline, *pipelinev1.PipelineList]( + "pipelines", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1.Pipeline { return &pipelinev1.Pipeline{} }, + func() *pipelinev1.PipelineList { return &pipelinev1.PipelineList{} }, + ), } } - -// Get takes name of the pipeline, and returns the corresponding pipeline object, and an error if there is any. -func (c *pipelines) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Pipeline, err error) { - result = &v1.Pipeline{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Pipelines that match those selectors. -func (c *pipelines) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PipelineList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1.PipelineList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested pipelines. -func (c *pipelines) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a pipeline and creates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *pipelines) Create(ctx context.Context, pipeline *v1.Pipeline, opts metav1.CreateOptions) (result *v1.Pipeline, err error) { - result = &v1.Pipeline{} - err = c.client.Post(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipeline). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a pipeline and updates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *pipelines) Update(ctx context.Context, pipeline *v1.Pipeline, opts metav1.UpdateOptions) (result *v1.Pipeline, err error) { - result = &v1.Pipeline{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelines"). - Name(pipeline.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipeline). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the pipeline and deletes it. Returns an error if one occurs. -func (c *pipelines) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *pipelines) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched pipeline. -func (c *pipelines) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pipeline, err error) { - result = &v1.Pipeline{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline_client.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline_client.go index 1b7f8d56..da9dfccd 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline_client.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipeline_client.go @@ -19,10 +19,10 @@ limitations under the License. package v1 import ( - "net/http" + http "net/http" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" rest "k8s.io/client-go/rest" ) @@ -100,10 +100,10 @@ func New(c rest.Interface) *TektonV1Client { } func setConfigDefaults(config *rest.Config) error { - gv := v1.SchemeGroupVersion + gv := pipelinev1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipelinerun.go index 0f37e00b..628788e1 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/pipelinerun.go @@ -19,15 +19,14 @@ limitations under the License. package v1 import ( - "context" - "time" + context "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // PipelineRunsGetter has a method to return a PipelineRunInterface. @@ -38,158 +37,34 @@ type PipelineRunsGetter interface { // PipelineRunInterface has methods to work with PipelineRun resources. type PipelineRunInterface interface { - Create(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.CreateOptions) (*v1.PipelineRun, error) - Update(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.UpdateOptions) (*v1.PipelineRun, error) - UpdateStatus(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.UpdateOptions) (*v1.PipelineRun, error) + Create(ctx context.Context, pipelineRun *pipelinev1.PipelineRun, opts metav1.CreateOptions) (*pipelinev1.PipelineRun, error) + Update(ctx context.Context, pipelineRun *pipelinev1.PipelineRun, opts metav1.UpdateOptions) (*pipelinev1.PipelineRun, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, pipelineRun *pipelinev1.PipelineRun, opts metav1.UpdateOptions) (*pipelinev1.PipelineRun, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error - Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.PipelineRun, error) - List(ctx context.Context, opts metav1.ListOptions) (*v1.PipelineRunList, error) + Get(ctx context.Context, name string, opts metav1.GetOptions) (*pipelinev1.PipelineRun, error) + List(ctx context.Context, opts metav1.ListOptions) (*pipelinev1.PipelineRunList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PipelineRun, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *pipelinev1.PipelineRun, err error) PipelineRunExpansion } // pipelineRuns implements PipelineRunInterface type pipelineRuns struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1.PipelineRun, *pipelinev1.PipelineRunList] } // newPipelineRuns returns a PipelineRuns func newPipelineRuns(c *TektonV1Client, namespace string) *pipelineRuns { return &pipelineRuns{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1.PipelineRun, *pipelinev1.PipelineRunList]( + "pipelineruns", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1.PipelineRun { return &pipelinev1.PipelineRun{} }, + func() *pipelinev1.PipelineRunList { return &pipelinev1.PipelineRunList{} }, + ), } } - -// Get takes name of the pipelineRun, and returns the corresponding pipelineRun object, and an error if there is any. -func (c *pipelineRuns) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PipelineRun, err error) { - result = &v1.PipelineRun{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of PipelineRuns that match those selectors. -func (c *pipelineRuns) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PipelineRunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1.PipelineRunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested pipelineRuns. -func (c *pipelineRuns) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a pipelineRun and creates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *pipelineRuns) Create(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.CreateOptions) (result *v1.PipelineRun, err error) { - result = &v1.PipelineRun{} - err = c.client.Post(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a pipelineRun and updates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *pipelineRuns) Update(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.UpdateOptions) (result *v1.PipelineRun, err error) { - result = &v1.PipelineRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(pipelineRun.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *pipelineRuns) UpdateStatus(ctx context.Context, pipelineRun *v1.PipelineRun, opts metav1.UpdateOptions) (result *v1.PipelineRun, err error) { - result = &v1.PipelineRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(pipelineRun.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the pipelineRun and deletes it. Returns an error if one occurs. -func (c *pipelineRuns) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *pipelineRuns) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched pipelineRun. -func (c *pipelineRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PipelineRun, err error) { - result = &v1.PipelineRun{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/task.go index d900e6f6..8e53ba19 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/task.go @@ -19,15 +19,14 @@ limitations under the License. package v1 import ( - "context" - "time" + context "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // TasksGetter has a method to return a TaskInterface. @@ -38,141 +37,32 @@ type TasksGetter interface { // TaskInterface has methods to work with Task resources. type TaskInterface interface { - Create(ctx context.Context, task *v1.Task, opts metav1.CreateOptions) (*v1.Task, error) - Update(ctx context.Context, task *v1.Task, opts metav1.UpdateOptions) (*v1.Task, error) + Create(ctx context.Context, task *pipelinev1.Task, opts metav1.CreateOptions) (*pipelinev1.Task, error) + Update(ctx context.Context, task *pipelinev1.Task, opts metav1.UpdateOptions) (*pipelinev1.Task, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error - Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Task, error) - List(ctx context.Context, opts metav1.ListOptions) (*v1.TaskList, error) + Get(ctx context.Context, name string, opts metav1.GetOptions) (*pipelinev1.Task, error) + List(ctx context.Context, opts metav1.ListOptions) (*pipelinev1.TaskList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Task, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *pipelinev1.Task, err error) TaskExpansion } // tasks implements TaskInterface type tasks struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1.Task, *pipelinev1.TaskList] } // newTasks returns a Tasks func newTasks(c *TektonV1Client, namespace string) *tasks { return &tasks{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1.Task, *pipelinev1.TaskList]( + "tasks", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1.Task { return &pipelinev1.Task{} }, + func() *pipelinev1.TaskList { return &pipelinev1.TaskList{} }, + ), } } - -// Get takes name of the task, and returns the corresponding task object, and an error if there is any. -func (c *tasks) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Task, err error) { - result = &v1.Task{} - err = c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Tasks that match those selectors. -func (c *tasks) List(ctx context.Context, opts metav1.ListOptions) (result *v1.TaskList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1.TaskList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested tasks. -func (c *tasks) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a task and creates it. Returns the server's representation of the task, and an error, if there is any. -func (c *tasks) Create(ctx context.Context, task *v1.Task, opts metav1.CreateOptions) (result *v1.Task, err error) { - result = &v1.Task{} - err = c.client.Post(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(task). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a task and updates it. Returns the server's representation of the task, and an error, if there is any. -func (c *tasks) Update(ctx context.Context, task *v1.Task, opts metav1.UpdateOptions) (result *v1.Task, err error) { - result = &v1.Task{} - err = c.client.Put(). - Namespace(c.ns). - Resource("tasks"). - Name(task.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(task). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the task and deletes it. Returns an error if one occurs. -func (c *tasks) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("tasks"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *tasks) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched task. -func (c *tasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Task, err error) { - result = &v1.Task{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("tasks"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/taskrun.go index 34145a97..78702759 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1/taskrun.go @@ -19,15 +19,14 @@ limitations under the License. package v1 import ( - "context" - "time" + context "context" - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // TaskRunsGetter has a method to return a TaskRunInterface. @@ -38,158 +37,34 @@ type TaskRunsGetter interface { // TaskRunInterface has methods to work with TaskRun resources. type TaskRunInterface interface { - Create(ctx context.Context, taskRun *v1.TaskRun, opts metav1.CreateOptions) (*v1.TaskRun, error) - Update(ctx context.Context, taskRun *v1.TaskRun, opts metav1.UpdateOptions) (*v1.TaskRun, error) - UpdateStatus(ctx context.Context, taskRun *v1.TaskRun, opts metav1.UpdateOptions) (*v1.TaskRun, error) + Create(ctx context.Context, taskRun *pipelinev1.TaskRun, opts metav1.CreateOptions) (*pipelinev1.TaskRun, error) + Update(ctx context.Context, taskRun *pipelinev1.TaskRun, opts metav1.UpdateOptions) (*pipelinev1.TaskRun, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, taskRun *pipelinev1.TaskRun, opts metav1.UpdateOptions) (*pipelinev1.TaskRun, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error - Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.TaskRun, error) - List(ctx context.Context, opts metav1.ListOptions) (*v1.TaskRunList, error) + Get(ctx context.Context, name string, opts metav1.GetOptions) (*pipelinev1.TaskRun, error) + List(ctx context.Context, opts metav1.ListOptions) (*pipelinev1.TaskRunList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.TaskRun, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *pipelinev1.TaskRun, err error) TaskRunExpansion } // taskRuns implements TaskRunInterface type taskRuns struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1.TaskRun, *pipelinev1.TaskRunList] } // newTaskRuns returns a TaskRuns func newTaskRuns(c *TektonV1Client, namespace string) *taskRuns { return &taskRuns{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1.TaskRun, *pipelinev1.TaskRunList]( + "taskruns", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1.TaskRun { return &pipelinev1.TaskRun{} }, + func() *pipelinev1.TaskRunList { return &pipelinev1.TaskRunList{} }, + ), } } - -// Get takes name of the taskRun, and returns the corresponding taskRun object, and an error if there is any. -func (c *taskRuns) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.TaskRun, err error) { - result = &v1.TaskRun{} - err = c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of TaskRuns that match those selectors. -func (c *taskRuns) List(ctx context.Context, opts metav1.ListOptions) (result *v1.TaskRunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1.TaskRunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested taskRuns. -func (c *taskRuns) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a taskRun and creates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *taskRuns) Create(ctx context.Context, taskRun *v1.TaskRun, opts metav1.CreateOptions) (result *v1.TaskRun, err error) { - result = &v1.TaskRun{} - err = c.client.Post(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a taskRun and updates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *taskRuns) Update(ctx context.Context, taskRun *v1.TaskRun, opts metav1.UpdateOptions) (result *v1.TaskRun, err error) { - result = &v1.TaskRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("taskruns"). - Name(taskRun.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *taskRuns) UpdateStatus(ctx context.Context, taskRun *v1.TaskRun, opts metav1.UpdateOptions) (result *v1.TaskRun, err error) { - result = &v1.TaskRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("taskruns"). - Name(taskRun.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the taskRun and deletes it. Returns an error if one occurs. -func (c *taskRuns) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *taskRuns) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched taskRun. -func (c *taskRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.TaskRun, err error) { - result = &v1.TaskRun{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go index c9c219df..4e7e96f0 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go @@ -29,15 +29,15 @@ type FakeTektonV1alpha1 struct { } func (c *FakeTektonV1alpha1) Runs(namespace string) v1alpha1.RunInterface { - return &FakeRuns{c, namespace} + return newFakeRuns(c, namespace) } func (c *FakeTektonV1alpha1) StepActions(namespace string) v1alpha1.StepActionInterface { - return &FakeStepActions{c, namespace} + return newFakeStepActions(c, namespace) } func (c *FakeTektonV1alpha1) VerificationPolicies(namespace string) v1alpha1.VerificationPolicyInterface { - return &FakeVerificationPolicies{c, namespace} + return newFakeVerificationPolicies(c, namespace) } // RESTClient returns a RESTClient that is used to communicate diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_run.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_run.go index 065047ad..88ddd06a 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_run.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_run.go @@ -19,123 +19,30 @@ limitations under the License. package fake import ( - "context" - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1" + gentype "k8s.io/client-go/gentype" ) -// FakeRuns implements RunInterface -type FakeRuns struct { +// fakeRuns implements RunInterface +type fakeRuns struct { + *gentype.FakeClientWithList[*v1alpha1.Run, *v1alpha1.RunList] Fake *FakeTektonV1alpha1 - ns string -} - -var runsResource = v1alpha1.SchemeGroupVersion.WithResource("runs") - -var runsKind = v1alpha1.SchemeGroupVersion.WithKind("Run") - -// Get takes name of the run, and returns the corresponding run object, and an error if there is any. -func (c *FakeRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Run, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(runsResource, c.ns, name), &v1alpha1.Run{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Run), err -} - -// List takes label and field selectors, and returns the list of Runs that match those selectors. -func (c *FakeRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(runsResource, runsKind, c.ns, opts), &v1alpha1.RunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.RunList{ListMeta: obj.(*v1alpha1.RunList).ListMeta} - for _, item := range obj.(*v1alpha1.RunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested runs. -func (c *FakeRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(runsResource, c.ns, opts)) - -} - -// Create takes the representation of a run and creates it. Returns the server's representation of the run, and an error, if there is any. -func (c *FakeRuns) Create(ctx context.Context, run *v1alpha1.Run, opts v1.CreateOptions) (result *v1alpha1.Run, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(runsResource, c.ns, run), &v1alpha1.Run{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Run), err -} - -// Update takes the representation of a run and updates it. Returns the server's representation of the run, and an error, if there is any. -func (c *FakeRuns) Update(ctx context.Context, run *v1alpha1.Run, opts v1.UpdateOptions) (result *v1alpha1.Run, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(runsResource, c.ns, run), &v1alpha1.Run{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Run), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeRuns) UpdateStatus(ctx context.Context, run *v1alpha1.Run, opts v1.UpdateOptions) (*v1alpha1.Run, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(runsResource, "status", c.ns, run), &v1alpha1.Run{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Run), err -} - -// Delete takes name of the run and deletes it. Returns an error if one occurs. -func (c *FakeRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(runsResource, c.ns, name, opts), &v1alpha1.Run{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(runsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.RunList{}) - return err -} - -// Patch applies the patch and returns the patched run. -func (c *FakeRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Run, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(runsResource, c.ns, name, pt, data, subresources...), &v1alpha1.Run{}) - - if obj == nil { - return nil, err +func newFakeRuns(fake *FakeTektonV1alpha1, namespace string) pipelinev1alpha1.RunInterface { + return &fakeRuns{ + gentype.NewFakeClientWithList[*v1alpha1.Run, *v1alpha1.RunList]( + fake.Fake, + namespace, + v1alpha1.SchemeGroupVersion.WithResource("runs"), + v1alpha1.SchemeGroupVersion.WithKind("Run"), + func() *v1alpha1.Run { return &v1alpha1.Run{} }, + func() *v1alpha1.RunList { return &v1alpha1.RunList{} }, + func(dst, src *v1alpha1.RunList) { dst.ListMeta = src.ListMeta }, + func(list *v1alpha1.RunList) []*v1alpha1.Run { return gentype.ToPointerSlice(list.Items) }, + func(list *v1alpha1.RunList, items []*v1alpha1.Run) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, } - return obj.(*v1alpha1.Run), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_stepaction.go index 7e3430c1..21f6a699 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_stepaction.go @@ -19,111 +19,32 @@ limitations under the License. package fake import ( - "context" - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1" + gentype "k8s.io/client-go/gentype" ) -// FakeStepActions implements StepActionInterface -type FakeStepActions struct { +// fakeStepActions implements StepActionInterface +type fakeStepActions struct { + *gentype.FakeClientWithList[*v1alpha1.StepAction, *v1alpha1.StepActionList] Fake *FakeTektonV1alpha1 - ns string -} - -var stepactionsResource = v1alpha1.SchemeGroupVersion.WithResource("stepactions") - -var stepactionsKind = v1alpha1.SchemeGroupVersion.WithKind("StepAction") - -// Get takes name of the stepAction, and returns the corresponding stepAction object, and an error if there is any. -func (c *FakeStepActions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(stepactionsResource, c.ns, name), &v1alpha1.StepAction{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.StepAction), err -} - -// List takes label and field selectors, and returns the list of StepActions that match those selectors. -func (c *FakeStepActions) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.StepActionList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(stepactionsResource, stepactionsKind, c.ns, opts), &v1alpha1.StepActionList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.StepActionList{ListMeta: obj.(*v1alpha1.StepActionList).ListMeta} - for _, item := range obj.(*v1alpha1.StepActionList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested stepActions. -func (c *FakeStepActions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(stepactionsResource, c.ns, opts)) - -} - -// Create takes the representation of a stepAction and creates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *FakeStepActions) Create(ctx context.Context, stepAction *v1alpha1.StepAction, opts v1.CreateOptions) (result *v1alpha1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(stepactionsResource, c.ns, stepAction), &v1alpha1.StepAction{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.StepAction), err -} - -// Update takes the representation of a stepAction and updates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *FakeStepActions) Update(ctx context.Context, stepAction *v1alpha1.StepAction, opts v1.UpdateOptions) (result *v1alpha1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(stepactionsResource, c.ns, stepAction), &v1alpha1.StepAction{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.StepAction), err -} - -// Delete takes name of the stepAction and deletes it. Returns an error if one occurs. -func (c *FakeStepActions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(stepactionsResource, c.ns, name, opts), &v1alpha1.StepAction{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeStepActions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(stepactionsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.StepActionList{}) - return err -} - -// Patch applies the patch and returns the patched stepAction. -func (c *FakeStepActions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(stepactionsResource, c.ns, name, pt, data, subresources...), &v1alpha1.StepAction{}) - - if obj == nil { - return nil, err +func newFakeStepActions(fake *FakeTektonV1alpha1, namespace string) pipelinev1alpha1.StepActionInterface { + return &fakeStepActions{ + gentype.NewFakeClientWithList[*v1alpha1.StepAction, *v1alpha1.StepActionList]( + fake.Fake, + namespace, + v1alpha1.SchemeGroupVersion.WithResource("stepactions"), + v1alpha1.SchemeGroupVersion.WithKind("StepAction"), + func() *v1alpha1.StepAction { return &v1alpha1.StepAction{} }, + func() *v1alpha1.StepActionList { return &v1alpha1.StepActionList{} }, + func(dst, src *v1alpha1.StepActionList) { dst.ListMeta = src.ListMeta }, + func(list *v1alpha1.StepActionList) []*v1alpha1.StepAction { return gentype.ToPointerSlice(list.Items) }, + func(list *v1alpha1.StepActionList, items []*v1alpha1.StepAction) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, } - return obj.(*v1alpha1.StepAction), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_verificationpolicy.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_verificationpolicy.go index 65df77d0..d03bfccf 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_verificationpolicy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_verificationpolicy.go @@ -19,111 +19,34 @@ limitations under the License. package fake import ( - "context" - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1" + gentype "k8s.io/client-go/gentype" ) -// FakeVerificationPolicies implements VerificationPolicyInterface -type FakeVerificationPolicies struct { +// fakeVerificationPolicies implements VerificationPolicyInterface +type fakeVerificationPolicies struct { + *gentype.FakeClientWithList[*v1alpha1.VerificationPolicy, *v1alpha1.VerificationPolicyList] Fake *FakeTektonV1alpha1 - ns string -} - -var verificationpoliciesResource = v1alpha1.SchemeGroupVersion.WithResource("verificationpolicies") - -var verificationpoliciesKind = v1alpha1.SchemeGroupVersion.WithKind("VerificationPolicy") - -// Get takes name of the verificationPolicy, and returns the corresponding verificationPolicy object, and an error if there is any. -func (c *FakeVerificationPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.VerificationPolicy, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(verificationpoliciesResource, c.ns, name), &v1alpha1.VerificationPolicy{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.VerificationPolicy), err -} - -// List takes label and field selectors, and returns the list of VerificationPolicies that match those selectors. -func (c *FakeVerificationPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.VerificationPolicyList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(verificationpoliciesResource, verificationpoliciesKind, c.ns, opts), &v1alpha1.VerificationPolicyList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.VerificationPolicyList{ListMeta: obj.(*v1alpha1.VerificationPolicyList).ListMeta} - for _, item := range obj.(*v1alpha1.VerificationPolicyList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested verificationPolicies. -func (c *FakeVerificationPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(verificationpoliciesResource, c.ns, opts)) - -} - -// Create takes the representation of a verificationPolicy and creates it. Returns the server's representation of the verificationPolicy, and an error, if there is any. -func (c *FakeVerificationPolicies) Create(ctx context.Context, verificationPolicy *v1alpha1.VerificationPolicy, opts v1.CreateOptions) (result *v1alpha1.VerificationPolicy, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(verificationpoliciesResource, c.ns, verificationPolicy), &v1alpha1.VerificationPolicy{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.VerificationPolicy), err -} - -// Update takes the representation of a verificationPolicy and updates it. Returns the server's representation of the verificationPolicy, and an error, if there is any. -func (c *FakeVerificationPolicies) Update(ctx context.Context, verificationPolicy *v1alpha1.VerificationPolicy, opts v1.UpdateOptions) (result *v1alpha1.VerificationPolicy, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(verificationpoliciesResource, c.ns, verificationPolicy), &v1alpha1.VerificationPolicy{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.VerificationPolicy), err -} - -// Delete takes name of the verificationPolicy and deletes it. Returns an error if one occurs. -func (c *FakeVerificationPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(verificationpoliciesResource, c.ns, name, opts), &v1alpha1.VerificationPolicy{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeVerificationPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(verificationpoliciesResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.VerificationPolicyList{}) - return err -} - -// Patch applies the patch and returns the patched verificationPolicy. -func (c *FakeVerificationPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.VerificationPolicy, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(verificationpoliciesResource, c.ns, name, pt, data, subresources...), &v1alpha1.VerificationPolicy{}) - - if obj == nil { - return nil, err +func newFakeVerificationPolicies(fake *FakeTektonV1alpha1, namespace string) pipelinev1alpha1.VerificationPolicyInterface { + return &fakeVerificationPolicies{ + gentype.NewFakeClientWithList[*v1alpha1.VerificationPolicy, *v1alpha1.VerificationPolicyList]( + fake.Fake, + namespace, + v1alpha1.SchemeGroupVersion.WithResource("verificationpolicies"), + v1alpha1.SchemeGroupVersion.WithKind("VerificationPolicy"), + func() *v1alpha1.VerificationPolicy { return &v1alpha1.VerificationPolicy{} }, + func() *v1alpha1.VerificationPolicyList { return &v1alpha1.VerificationPolicyList{} }, + func(dst, src *v1alpha1.VerificationPolicyList) { dst.ListMeta = src.ListMeta }, + func(list *v1alpha1.VerificationPolicyList) []*v1alpha1.VerificationPolicy { + return gentype.ToPointerSlice(list.Items) + }, + func(list *v1alpha1.VerificationPolicyList, items []*v1alpha1.VerificationPolicy) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, } - return obj.(*v1alpha1.VerificationPolicy), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go index 2c9a8a63..e3ced10f 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go @@ -19,10 +19,10 @@ limitations under the License. package v1alpha1 import ( - "net/http" + http "net/http" - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" rest "k8s.io/client-go/rest" ) @@ -95,10 +95,10 @@ func New(c rest.Interface) *TektonV1alpha1Client { } func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion + gv := pipelinev1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/run.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/run.go index 417dd821..83613f83 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/run.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/run.go @@ -19,15 +19,14 @@ limitations under the License. package v1alpha1 import ( - "context" - "time" + context "context" - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // RunsGetter has a method to return a RunInterface. @@ -38,158 +37,34 @@ type RunsGetter interface { // RunInterface has methods to work with Run resources. type RunInterface interface { - Create(ctx context.Context, run *v1alpha1.Run, opts v1.CreateOptions) (*v1alpha1.Run, error) - Update(ctx context.Context, run *v1alpha1.Run, opts v1.UpdateOptions) (*v1alpha1.Run, error) - UpdateStatus(ctx context.Context, run *v1alpha1.Run, opts v1.UpdateOptions) (*v1alpha1.Run, error) + Create(ctx context.Context, run *pipelinev1alpha1.Run, opts v1.CreateOptions) (*pipelinev1alpha1.Run, error) + Update(ctx context.Context, run *pipelinev1alpha1.Run, opts v1.UpdateOptions) (*pipelinev1alpha1.Run, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, run *pipelinev1alpha1.Run, opts v1.UpdateOptions) (*pipelinev1alpha1.Run, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Run, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.RunList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1alpha1.Run, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1alpha1.RunList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Run, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1alpha1.Run, err error) RunExpansion } // runs implements RunInterface type runs struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1alpha1.Run, *pipelinev1alpha1.RunList] } // newRuns returns a Runs func newRuns(c *TektonV1alpha1Client, namespace string) *runs { return &runs{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1alpha1.Run, *pipelinev1alpha1.RunList]( + "runs", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1alpha1.Run { return &pipelinev1alpha1.Run{} }, + func() *pipelinev1alpha1.RunList { return &pipelinev1alpha1.RunList{} }, + ), } } - -// Get takes name of the run, and returns the corresponding run object, and an error if there is any. -func (c *runs) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Run, err error) { - result = &v1alpha1.Run{} - err = c.client.Get(). - Namespace(c.ns). - Resource("runs"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Runs that match those selectors. -func (c *runs) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.RunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("runs"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested runs. -func (c *runs) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("runs"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a run and creates it. Returns the server's representation of the run, and an error, if there is any. -func (c *runs) Create(ctx context.Context, run *v1alpha1.Run, opts v1.CreateOptions) (result *v1alpha1.Run, err error) { - result = &v1alpha1.Run{} - err = c.client.Post(). - Namespace(c.ns). - Resource("runs"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(run). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a run and updates it. Returns the server's representation of the run, and an error, if there is any. -func (c *runs) Update(ctx context.Context, run *v1alpha1.Run, opts v1.UpdateOptions) (result *v1alpha1.Run, err error) { - result = &v1alpha1.Run{} - err = c.client.Put(). - Namespace(c.ns). - Resource("runs"). - Name(run.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(run). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *runs) UpdateStatus(ctx context.Context, run *v1alpha1.Run, opts v1.UpdateOptions) (result *v1alpha1.Run, err error) { - result = &v1alpha1.Run{} - err = c.client.Put(). - Namespace(c.ns). - Resource("runs"). - Name(run.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(run). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the run and deletes it. Returns an error if one occurs. -func (c *runs) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("runs"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *runs) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("runs"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched run. -func (c *runs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Run, err error) { - result = &v1alpha1.Run{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("runs"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/stepaction.go index 5b5e9ebd..ec983660 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/stepaction.go @@ -19,15 +19,14 @@ limitations under the License. package v1alpha1 import ( - "context" - "time" + context "context" - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // StepActionsGetter has a method to return a StepActionInterface. @@ -38,141 +37,32 @@ type StepActionsGetter interface { // StepActionInterface has methods to work with StepAction resources. type StepActionInterface interface { - Create(ctx context.Context, stepAction *v1alpha1.StepAction, opts v1.CreateOptions) (*v1alpha1.StepAction, error) - Update(ctx context.Context, stepAction *v1alpha1.StepAction, opts v1.UpdateOptions) (*v1alpha1.StepAction, error) + Create(ctx context.Context, stepAction *pipelinev1alpha1.StepAction, opts v1.CreateOptions) (*pipelinev1alpha1.StepAction, error) + Update(ctx context.Context, stepAction *pipelinev1alpha1.StepAction, opts v1.UpdateOptions) (*pipelinev1alpha1.StepAction, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.StepAction, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.StepActionList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1alpha1.StepAction, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1alpha1.StepActionList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.StepAction, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1alpha1.StepAction, err error) StepActionExpansion } // stepActions implements StepActionInterface type stepActions struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1alpha1.StepAction, *pipelinev1alpha1.StepActionList] } // newStepActions returns a StepActions func newStepActions(c *TektonV1alpha1Client, namespace string) *stepActions { return &stepActions{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1alpha1.StepAction, *pipelinev1alpha1.StepActionList]( + "stepactions", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1alpha1.StepAction { return &pipelinev1alpha1.StepAction{} }, + func() *pipelinev1alpha1.StepActionList { return &pipelinev1alpha1.StepActionList{} }, + ), } } - -// Get takes name of the stepAction, and returns the corresponding stepAction object, and an error if there is any. -func (c *stepActions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.StepAction, err error) { - result = &v1alpha1.StepAction{} - err = c.client.Get(). - Namespace(c.ns). - Resource("stepactions"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of StepActions that match those selectors. -func (c *stepActions) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.StepActionList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.StepActionList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested stepActions. -func (c *stepActions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a stepAction and creates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *stepActions) Create(ctx context.Context, stepAction *v1alpha1.StepAction, opts v1.CreateOptions) (result *v1alpha1.StepAction, err error) { - result = &v1alpha1.StepAction{} - err = c.client.Post(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(stepAction). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a stepAction and updates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *stepActions) Update(ctx context.Context, stepAction *v1alpha1.StepAction, opts v1.UpdateOptions) (result *v1alpha1.StepAction, err error) { - result = &v1alpha1.StepAction{} - err = c.client.Put(). - Namespace(c.ns). - Resource("stepactions"). - Name(stepAction.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(stepAction). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the stepAction and deletes it. Returns an error if one occurs. -func (c *stepActions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("stepactions"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *stepActions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched stepAction. -func (c *stepActions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.StepAction, err error) { - result = &v1alpha1.StepAction{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("stepactions"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/verificationpolicy.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/verificationpolicy.go index 92f53409..8ac12e4d 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/verificationpolicy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/verificationpolicy.go @@ -19,15 +19,14 @@ limitations under the License. package v1alpha1 import ( - "context" - "time" + context "context" - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // VerificationPoliciesGetter has a method to return a VerificationPolicyInterface. @@ -38,141 +37,32 @@ type VerificationPoliciesGetter interface { // VerificationPolicyInterface has methods to work with VerificationPolicy resources. type VerificationPolicyInterface interface { - Create(ctx context.Context, verificationPolicy *v1alpha1.VerificationPolicy, opts v1.CreateOptions) (*v1alpha1.VerificationPolicy, error) - Update(ctx context.Context, verificationPolicy *v1alpha1.VerificationPolicy, opts v1.UpdateOptions) (*v1alpha1.VerificationPolicy, error) + Create(ctx context.Context, verificationPolicy *pipelinev1alpha1.VerificationPolicy, opts v1.CreateOptions) (*pipelinev1alpha1.VerificationPolicy, error) + Update(ctx context.Context, verificationPolicy *pipelinev1alpha1.VerificationPolicy, opts v1.UpdateOptions) (*pipelinev1alpha1.VerificationPolicy, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.VerificationPolicy, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.VerificationPolicyList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1alpha1.VerificationPolicy, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1alpha1.VerificationPolicyList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.VerificationPolicy, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1alpha1.VerificationPolicy, err error) VerificationPolicyExpansion } // verificationPolicies implements VerificationPolicyInterface type verificationPolicies struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1alpha1.VerificationPolicy, *pipelinev1alpha1.VerificationPolicyList] } // newVerificationPolicies returns a VerificationPolicies func newVerificationPolicies(c *TektonV1alpha1Client, namespace string) *verificationPolicies { return &verificationPolicies{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1alpha1.VerificationPolicy, *pipelinev1alpha1.VerificationPolicyList]( + "verificationpolicies", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1alpha1.VerificationPolicy { return &pipelinev1alpha1.VerificationPolicy{} }, + func() *pipelinev1alpha1.VerificationPolicyList { return &pipelinev1alpha1.VerificationPolicyList{} }, + ), } } - -// Get takes name of the verificationPolicy, and returns the corresponding verificationPolicy object, and an error if there is any. -func (c *verificationPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.VerificationPolicy, err error) { - result = &v1alpha1.VerificationPolicy{} - err = c.client.Get(). - Namespace(c.ns). - Resource("verificationpolicies"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of VerificationPolicies that match those selectors. -func (c *verificationPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.VerificationPolicyList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.VerificationPolicyList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("verificationpolicies"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested verificationPolicies. -func (c *verificationPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("verificationpolicies"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a verificationPolicy and creates it. Returns the server's representation of the verificationPolicy, and an error, if there is any. -func (c *verificationPolicies) Create(ctx context.Context, verificationPolicy *v1alpha1.VerificationPolicy, opts v1.CreateOptions) (result *v1alpha1.VerificationPolicy, err error) { - result = &v1alpha1.VerificationPolicy{} - err = c.client.Post(). - Namespace(c.ns). - Resource("verificationpolicies"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(verificationPolicy). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a verificationPolicy and updates it. Returns the server's representation of the verificationPolicy, and an error, if there is any. -func (c *verificationPolicies) Update(ctx context.Context, verificationPolicy *v1alpha1.VerificationPolicy, opts v1.UpdateOptions) (result *v1alpha1.VerificationPolicy, err error) { - result = &v1alpha1.VerificationPolicy{} - err = c.client.Put(). - Namespace(c.ns). - Resource("verificationpolicies"). - Name(verificationPolicy.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(verificationPolicy). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the verificationPolicy and deletes it. Returns an error if one occurs. -func (c *verificationPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("verificationpolicies"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *verificationPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("verificationpolicies"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched verificationPolicy. -func (c *verificationPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.VerificationPolicy, err error) { - result = &v1alpha1.VerificationPolicy{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("verificationpolicies"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/clustertask.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/clustertask.go deleted file mode 100644 index 80c11ff5..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/clustertask.go +++ /dev/null @@ -1,168 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1beta1 - -import ( - "context" - "time" - - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ClusterTasksGetter has a method to return a ClusterTaskInterface. -// A group's client should implement this interface. -type ClusterTasksGetter interface { - ClusterTasks() ClusterTaskInterface -} - -// ClusterTaskInterface has methods to work with ClusterTask resources. -type ClusterTaskInterface interface { - Create(ctx context.Context, clusterTask *v1beta1.ClusterTask, opts v1.CreateOptions) (*v1beta1.ClusterTask, error) - Update(ctx context.Context, clusterTask *v1beta1.ClusterTask, opts v1.UpdateOptions) (*v1beta1.ClusterTask, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.ClusterTask, error) - List(ctx context.Context, opts v1.ListOptions) (*v1beta1.ClusterTaskList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterTask, err error) - ClusterTaskExpansion -} - -// clusterTasks implements ClusterTaskInterface -type clusterTasks struct { - client rest.Interface -} - -// newClusterTasks returns a ClusterTasks -func newClusterTasks(c *TektonV1beta1Client) *clusterTasks { - return &clusterTasks{ - client: c.RESTClient(), - } -} - -// Get takes name of the clusterTask, and returns the corresponding clusterTask object, and an error if there is any. -func (c *clusterTasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterTask, err error) { - result = &v1beta1.ClusterTask{} - err = c.client.Get(). - Resource("clustertasks"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ClusterTasks that match those selectors. -func (c *clusterTasks) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterTaskList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1beta1.ClusterTaskList{} - err = c.client.Get(). - Resource("clustertasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested clusterTasks. -func (c *clusterTasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Resource("clustertasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a clusterTask and creates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *clusterTasks) Create(ctx context.Context, clusterTask *v1beta1.ClusterTask, opts v1.CreateOptions) (result *v1beta1.ClusterTask, err error) { - result = &v1beta1.ClusterTask{} - err = c.client.Post(). - Resource("clustertasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(clusterTask). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a clusterTask and updates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *clusterTasks) Update(ctx context.Context, clusterTask *v1beta1.ClusterTask, opts v1.UpdateOptions) (result *v1beta1.ClusterTask, err error) { - result = &v1beta1.ClusterTask{} - err = c.client.Put(). - Resource("clustertasks"). - Name(clusterTask.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(clusterTask). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the clusterTask and deletes it. Returns an error if one occurs. -func (c *clusterTasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Resource("clustertasks"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *clusterTasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Resource("clustertasks"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched clusterTask. -func (c *clusterTasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterTask, err error) { - result = &v1beta1.ClusterTask{} - err = c.client.Patch(pt). - Resource("clustertasks"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/customrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/customrun.go index a5755045..0ca86d00 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/customrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/customrun.go @@ -19,15 +19,14 @@ limitations under the License. package v1beta1 import ( - "context" - "time" + context "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // CustomRunsGetter has a method to return a CustomRunInterface. @@ -38,158 +37,34 @@ type CustomRunsGetter interface { // CustomRunInterface has methods to work with CustomRun resources. type CustomRunInterface interface { - Create(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.CreateOptions) (*v1beta1.CustomRun, error) - Update(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.UpdateOptions) (*v1beta1.CustomRun, error) - UpdateStatus(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.UpdateOptions) (*v1beta1.CustomRun, error) + Create(ctx context.Context, customRun *pipelinev1beta1.CustomRun, opts v1.CreateOptions) (*pipelinev1beta1.CustomRun, error) + Update(ctx context.Context, customRun *pipelinev1beta1.CustomRun, opts v1.UpdateOptions) (*pipelinev1beta1.CustomRun, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, customRun *pipelinev1beta1.CustomRun, opts v1.UpdateOptions) (*pipelinev1beta1.CustomRun, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.CustomRun, error) - List(ctx context.Context, opts v1.ListOptions) (*v1beta1.CustomRunList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1beta1.CustomRun, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1beta1.CustomRunList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CustomRun, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1beta1.CustomRun, err error) CustomRunExpansion } // customRuns implements CustomRunInterface type customRuns struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1beta1.CustomRun, *pipelinev1beta1.CustomRunList] } // newCustomRuns returns a CustomRuns func newCustomRuns(c *TektonV1beta1Client, namespace string) *customRuns { return &customRuns{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1beta1.CustomRun, *pipelinev1beta1.CustomRunList]( + "customruns", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1beta1.CustomRun { return &pipelinev1beta1.CustomRun{} }, + func() *pipelinev1beta1.CustomRunList { return &pipelinev1beta1.CustomRunList{} }, + ), } } - -// Get takes name of the customRun, and returns the corresponding customRun object, and an error if there is any. -func (c *customRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CustomRun, err error) { - result = &v1beta1.CustomRun{} - err = c.client.Get(). - Namespace(c.ns). - Resource("customruns"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of CustomRuns that match those selectors. -func (c *customRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CustomRunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1beta1.CustomRunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("customruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested customRuns. -func (c *customRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("customruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a customRun and creates it. Returns the server's representation of the customRun, and an error, if there is any. -func (c *customRuns) Create(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.CreateOptions) (result *v1beta1.CustomRun, err error) { - result = &v1beta1.CustomRun{} - err = c.client.Post(). - Namespace(c.ns). - Resource("customruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(customRun). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a customRun and updates it. Returns the server's representation of the customRun, and an error, if there is any. -func (c *customRuns) Update(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.UpdateOptions) (result *v1beta1.CustomRun, err error) { - result = &v1beta1.CustomRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("customruns"). - Name(customRun.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(customRun). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *customRuns) UpdateStatus(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.UpdateOptions) (result *v1beta1.CustomRun, err error) { - result = &v1beta1.CustomRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("customruns"). - Name(customRun.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(customRun). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the customRun and deletes it. Returns an error if one occurs. -func (c *customRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("customruns"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *customRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("customruns"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched customRun. -func (c *customRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CustomRun, err error) { - result = &v1beta1.CustomRun{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("customruns"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_clustertask.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_clustertask.go deleted file mode 100644 index ef1f26c4..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_clustertask.go +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeClusterTasks implements ClusterTaskInterface -type FakeClusterTasks struct { - Fake *FakeTektonV1beta1 -} - -var clustertasksResource = v1beta1.SchemeGroupVersion.WithResource("clustertasks") - -var clustertasksKind = v1beta1.SchemeGroupVersion.WithKind("ClusterTask") - -// Get takes name of the clusterTask, and returns the corresponding clusterTask object, and an error if there is any. -func (c *FakeClusterTasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(clustertasksResource, name), &v1beta1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1beta1.ClusterTask), err -} - -// List takes label and field selectors, and returns the list of ClusterTasks that match those selectors. -func (c *FakeClusterTasks) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterTaskList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(clustertasksResource, clustertasksKind, opts), &v1beta1.ClusterTaskList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1beta1.ClusterTaskList{ListMeta: obj.(*v1beta1.ClusterTaskList).ListMeta} - for _, item := range obj.(*v1beta1.ClusterTaskList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested clusterTasks. -func (c *FakeClusterTasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(clustertasksResource, opts)) -} - -// Create takes the representation of a clusterTask and creates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *FakeClusterTasks) Create(ctx context.Context, clusterTask *v1beta1.ClusterTask, opts v1.CreateOptions) (result *v1beta1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(clustertasksResource, clusterTask), &v1beta1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1beta1.ClusterTask), err -} - -// Update takes the representation of a clusterTask and updates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *FakeClusterTasks) Update(ctx context.Context, clusterTask *v1beta1.ClusterTask, opts v1.UpdateOptions) (result *v1beta1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(clustertasksResource, clusterTask), &v1beta1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1beta1.ClusterTask), err -} - -// Delete takes name of the clusterTask and deletes it. Returns an error if one occurs. -func (c *FakeClusterTasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteActionWithOptions(clustertasksResource, name, opts), &v1beta1.ClusterTask{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeClusterTasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(clustertasksResource, listOpts) - - _, err := c.Fake.Invokes(action, &v1beta1.ClusterTaskList{}) - return err -} - -// Patch applies the patch and returns the patched clusterTask. -func (c *FakeClusterTasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(clustertasksResource, name, pt, data, subresources...), &v1beta1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1beta1.ClusterTask), err -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_customrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_customrun.go index 593b2d2f..0f8ac71a 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_customrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_customrun.go @@ -19,123 +19,32 @@ limitations under the License. package fake import ( - "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1" + gentype "k8s.io/client-go/gentype" ) -// FakeCustomRuns implements CustomRunInterface -type FakeCustomRuns struct { +// fakeCustomRuns implements CustomRunInterface +type fakeCustomRuns struct { + *gentype.FakeClientWithList[*v1beta1.CustomRun, *v1beta1.CustomRunList] Fake *FakeTektonV1beta1 - ns string -} - -var customrunsResource = v1beta1.SchemeGroupVersion.WithResource("customruns") - -var customrunsKind = v1beta1.SchemeGroupVersion.WithKind("CustomRun") - -// Get takes name of the customRun, and returns the corresponding customRun object, and an error if there is any. -func (c *FakeCustomRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CustomRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(customrunsResource, c.ns, name), &v1beta1.CustomRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.CustomRun), err -} - -// List takes label and field selectors, and returns the list of CustomRuns that match those selectors. -func (c *FakeCustomRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CustomRunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(customrunsResource, customrunsKind, c.ns, opts), &v1beta1.CustomRunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1beta1.CustomRunList{ListMeta: obj.(*v1beta1.CustomRunList).ListMeta} - for _, item := range obj.(*v1beta1.CustomRunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested customRuns. -func (c *FakeCustomRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(customrunsResource, c.ns, opts)) - -} - -// Create takes the representation of a customRun and creates it. Returns the server's representation of the customRun, and an error, if there is any. -func (c *FakeCustomRuns) Create(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.CreateOptions) (result *v1beta1.CustomRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(customrunsResource, c.ns, customRun), &v1beta1.CustomRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.CustomRun), err -} - -// Update takes the representation of a customRun and updates it. Returns the server's representation of the customRun, and an error, if there is any. -func (c *FakeCustomRuns) Update(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.UpdateOptions) (result *v1beta1.CustomRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(customrunsResource, c.ns, customRun), &v1beta1.CustomRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.CustomRun), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeCustomRuns) UpdateStatus(ctx context.Context, customRun *v1beta1.CustomRun, opts v1.UpdateOptions) (*v1beta1.CustomRun, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(customrunsResource, "status", c.ns, customRun), &v1beta1.CustomRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.CustomRun), err -} - -// Delete takes name of the customRun and deletes it. Returns an error if one occurs. -func (c *FakeCustomRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(customrunsResource, c.ns, name, opts), &v1beta1.CustomRun{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeCustomRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(customrunsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1beta1.CustomRunList{}) - return err -} - -// Patch applies the patch and returns the patched customRun. -func (c *FakeCustomRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CustomRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(customrunsResource, c.ns, name, pt, data, subresources...), &v1beta1.CustomRun{}) - - if obj == nil { - return nil, err +func newFakeCustomRuns(fake *FakeTektonV1beta1, namespace string) pipelinev1beta1.CustomRunInterface { + return &fakeCustomRuns{ + gentype.NewFakeClientWithList[*v1beta1.CustomRun, *v1beta1.CustomRunList]( + fake.Fake, + namespace, + v1beta1.SchemeGroupVersion.WithResource("customruns"), + v1beta1.SchemeGroupVersion.WithKind("CustomRun"), + func() *v1beta1.CustomRun { return &v1beta1.CustomRun{} }, + func() *v1beta1.CustomRunList { return &v1beta1.CustomRunList{} }, + func(dst, src *v1beta1.CustomRunList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.CustomRunList) []*v1beta1.CustomRun { return gentype.ToPointerSlice(list.Items) }, + func(list *v1beta1.CustomRunList, items []*v1beta1.CustomRun) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, } - return obj.(*v1beta1.CustomRun), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline.go index 6dc5ec66..cfbed839 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline.go @@ -19,111 +19,32 @@ limitations under the License. package fake import ( - "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1" + gentype "k8s.io/client-go/gentype" ) -// FakePipelines implements PipelineInterface -type FakePipelines struct { +// fakePipelines implements PipelineInterface +type fakePipelines struct { + *gentype.FakeClientWithList[*v1beta1.Pipeline, *v1beta1.PipelineList] Fake *FakeTektonV1beta1 - ns string -} - -var pipelinesResource = v1beta1.SchemeGroupVersion.WithResource("pipelines") - -var pipelinesKind = v1beta1.SchemeGroupVersion.WithKind("Pipeline") - -// Get takes name of the pipeline, and returns the corresponding pipeline object, and an error if there is any. -func (c *FakePipelines) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(pipelinesResource, c.ns, name), &v1beta1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.Pipeline), err -} - -// List takes label and field selectors, and returns the list of Pipelines that match those selectors. -func (c *FakePipelines) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PipelineList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(pipelinesResource, pipelinesKind, c.ns, opts), &v1beta1.PipelineList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1beta1.PipelineList{ListMeta: obj.(*v1beta1.PipelineList).ListMeta} - for _, item := range obj.(*v1beta1.PipelineList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested pipelines. -func (c *FakePipelines) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(pipelinesResource, c.ns, opts)) - -} - -// Create takes the representation of a pipeline and creates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *FakePipelines) Create(ctx context.Context, pipeline *v1beta1.Pipeline, opts v1.CreateOptions) (result *v1beta1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(pipelinesResource, c.ns, pipeline), &v1beta1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.Pipeline), err -} - -// Update takes the representation of a pipeline and updates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *FakePipelines) Update(ctx context.Context, pipeline *v1beta1.Pipeline, opts v1.UpdateOptions) (result *v1beta1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(pipelinesResource, c.ns, pipeline), &v1beta1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.Pipeline), err -} - -// Delete takes name of the pipeline and deletes it. Returns an error if one occurs. -func (c *FakePipelines) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(pipelinesResource, c.ns, name, opts), &v1beta1.Pipeline{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakePipelines) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(pipelinesResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1beta1.PipelineList{}) - return err -} - -// Patch applies the patch and returns the patched pipeline. -func (c *FakePipelines) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(pipelinesResource, c.ns, name, pt, data, subresources...), &v1beta1.Pipeline{}) - - if obj == nil { - return nil, err +func newFakePipelines(fake *FakeTektonV1beta1, namespace string) pipelinev1beta1.PipelineInterface { + return &fakePipelines{ + gentype.NewFakeClientWithList[*v1beta1.Pipeline, *v1beta1.PipelineList]( + fake.Fake, + namespace, + v1beta1.SchemeGroupVersion.WithResource("pipelines"), + v1beta1.SchemeGroupVersion.WithKind("Pipeline"), + func() *v1beta1.Pipeline { return &v1beta1.Pipeline{} }, + func() *v1beta1.PipelineList { return &v1beta1.PipelineList{} }, + func(dst, src *v1beta1.PipelineList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.PipelineList) []*v1beta1.Pipeline { return gentype.ToPointerSlice(list.Items) }, + func(list *v1beta1.PipelineList, items []*v1beta1.Pipeline) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, } - return obj.(*v1beta1.Pipeline), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline_client.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline_client.go index 326e2fbb..ce16bafc 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline_client.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipeline_client.go @@ -28,32 +28,28 @@ type FakeTektonV1beta1 struct { *testing.Fake } -func (c *FakeTektonV1beta1) ClusterTasks() v1beta1.ClusterTaskInterface { - return &FakeClusterTasks{c} -} - func (c *FakeTektonV1beta1) CustomRuns(namespace string) v1beta1.CustomRunInterface { - return &FakeCustomRuns{c, namespace} + return newFakeCustomRuns(c, namespace) } func (c *FakeTektonV1beta1) Pipelines(namespace string) v1beta1.PipelineInterface { - return &FakePipelines{c, namespace} + return newFakePipelines(c, namespace) } func (c *FakeTektonV1beta1) PipelineRuns(namespace string) v1beta1.PipelineRunInterface { - return &FakePipelineRuns{c, namespace} + return newFakePipelineRuns(c, namespace) } func (c *FakeTektonV1beta1) StepActions(namespace string) v1beta1.StepActionInterface { - return &FakeStepActions{c, namespace} + return newFakeStepActions(c, namespace) } func (c *FakeTektonV1beta1) Tasks(namespace string) v1beta1.TaskInterface { - return &FakeTasks{c, namespace} + return newFakeTasks(c, namespace) } func (c *FakeTektonV1beta1) TaskRuns(namespace string) v1beta1.TaskRunInterface { - return &FakeTaskRuns{c, namespace} + return newFakeTaskRuns(c, namespace) } // RESTClient returns a RESTClient that is used to communicate diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipelinerun.go index c7eb52ee..03a9491f 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_pipelinerun.go @@ -19,123 +19,32 @@ limitations under the License. package fake import ( - "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1" + gentype "k8s.io/client-go/gentype" ) -// FakePipelineRuns implements PipelineRunInterface -type FakePipelineRuns struct { +// fakePipelineRuns implements PipelineRunInterface +type fakePipelineRuns struct { + *gentype.FakeClientWithList[*v1beta1.PipelineRun, *v1beta1.PipelineRunList] Fake *FakeTektonV1beta1 - ns string -} - -var pipelinerunsResource = v1beta1.SchemeGroupVersion.WithResource("pipelineruns") - -var pipelinerunsKind = v1beta1.SchemeGroupVersion.WithKind("PipelineRun") - -// Get takes name of the pipelineRun, and returns the corresponding pipelineRun object, and an error if there is any. -func (c *FakePipelineRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(pipelinerunsResource, c.ns, name), &v1beta1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.PipelineRun), err -} - -// List takes label and field selectors, and returns the list of PipelineRuns that match those selectors. -func (c *FakePipelineRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PipelineRunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(pipelinerunsResource, pipelinerunsKind, c.ns, opts), &v1beta1.PipelineRunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1beta1.PipelineRunList{ListMeta: obj.(*v1beta1.PipelineRunList).ListMeta} - for _, item := range obj.(*v1beta1.PipelineRunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested pipelineRuns. -func (c *FakePipelineRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(pipelinerunsResource, c.ns, opts)) - -} - -// Create takes the representation of a pipelineRun and creates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *FakePipelineRuns) Create(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.CreateOptions) (result *v1beta1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(pipelinerunsResource, c.ns, pipelineRun), &v1beta1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.PipelineRun), err -} - -// Update takes the representation of a pipelineRun and updates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *FakePipelineRuns) Update(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.UpdateOptions) (result *v1beta1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(pipelinerunsResource, c.ns, pipelineRun), &v1beta1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.PipelineRun), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakePipelineRuns) UpdateStatus(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.UpdateOptions) (*v1beta1.PipelineRun, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(pipelinerunsResource, "status", c.ns, pipelineRun), &v1beta1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.PipelineRun), err -} - -// Delete takes name of the pipelineRun and deletes it. Returns an error if one occurs. -func (c *FakePipelineRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(pipelinerunsResource, c.ns, name, opts), &v1beta1.PipelineRun{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakePipelineRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(pipelinerunsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1beta1.PipelineRunList{}) - return err -} - -// Patch applies the patch and returns the patched pipelineRun. -func (c *FakePipelineRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(pipelinerunsResource, c.ns, name, pt, data, subresources...), &v1beta1.PipelineRun{}) - - if obj == nil { - return nil, err +func newFakePipelineRuns(fake *FakeTektonV1beta1, namespace string) pipelinev1beta1.PipelineRunInterface { + return &fakePipelineRuns{ + gentype.NewFakeClientWithList[*v1beta1.PipelineRun, *v1beta1.PipelineRunList]( + fake.Fake, + namespace, + v1beta1.SchemeGroupVersion.WithResource("pipelineruns"), + v1beta1.SchemeGroupVersion.WithKind("PipelineRun"), + func() *v1beta1.PipelineRun { return &v1beta1.PipelineRun{} }, + func() *v1beta1.PipelineRunList { return &v1beta1.PipelineRunList{} }, + func(dst, src *v1beta1.PipelineRunList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.PipelineRunList) []*v1beta1.PipelineRun { return gentype.ToPointerSlice(list.Items) }, + func(list *v1beta1.PipelineRunList, items []*v1beta1.PipelineRun) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, } - return obj.(*v1beta1.PipelineRun), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_stepaction.go index 048c9e56..1fade2e3 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_stepaction.go @@ -19,111 +19,32 @@ limitations under the License. package fake import ( - "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1" + gentype "k8s.io/client-go/gentype" ) -// FakeStepActions implements StepActionInterface -type FakeStepActions struct { +// fakeStepActions implements StepActionInterface +type fakeStepActions struct { + *gentype.FakeClientWithList[*v1beta1.StepAction, *v1beta1.StepActionList] Fake *FakeTektonV1beta1 - ns string -} - -var stepactionsResource = v1beta1.SchemeGroupVersion.WithResource("stepactions") - -var stepactionsKind = v1beta1.SchemeGroupVersion.WithKind("StepAction") - -// Get takes name of the stepAction, and returns the corresponding stepAction object, and an error if there is any. -func (c *FakeStepActions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(stepactionsResource, c.ns, name), &v1beta1.StepAction{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.StepAction), err -} - -// List takes label and field selectors, and returns the list of StepActions that match those selectors. -func (c *FakeStepActions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.StepActionList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(stepactionsResource, stepactionsKind, c.ns, opts), &v1beta1.StepActionList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1beta1.StepActionList{ListMeta: obj.(*v1beta1.StepActionList).ListMeta} - for _, item := range obj.(*v1beta1.StepActionList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested stepActions. -func (c *FakeStepActions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(stepactionsResource, c.ns, opts)) - -} - -// Create takes the representation of a stepAction and creates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *FakeStepActions) Create(ctx context.Context, stepAction *v1beta1.StepAction, opts v1.CreateOptions) (result *v1beta1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(stepactionsResource, c.ns, stepAction), &v1beta1.StepAction{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.StepAction), err -} - -// Update takes the representation of a stepAction and updates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *FakeStepActions) Update(ctx context.Context, stepAction *v1beta1.StepAction, opts v1.UpdateOptions) (result *v1beta1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(stepactionsResource, c.ns, stepAction), &v1beta1.StepAction{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.StepAction), err -} - -// Delete takes name of the stepAction and deletes it. Returns an error if one occurs. -func (c *FakeStepActions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(stepactionsResource, c.ns, name, opts), &v1beta1.StepAction{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeStepActions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(stepactionsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1beta1.StepActionList{}) - return err -} - -// Patch applies the patch and returns the patched stepAction. -func (c *FakeStepActions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.StepAction, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(stepactionsResource, c.ns, name, pt, data, subresources...), &v1beta1.StepAction{}) - - if obj == nil { - return nil, err +func newFakeStepActions(fake *FakeTektonV1beta1, namespace string) pipelinev1beta1.StepActionInterface { + return &fakeStepActions{ + gentype.NewFakeClientWithList[*v1beta1.StepAction, *v1beta1.StepActionList]( + fake.Fake, + namespace, + v1beta1.SchemeGroupVersion.WithResource("stepactions"), + v1beta1.SchemeGroupVersion.WithKind("StepAction"), + func() *v1beta1.StepAction { return &v1beta1.StepAction{} }, + func() *v1beta1.StepActionList { return &v1beta1.StepActionList{} }, + func(dst, src *v1beta1.StepActionList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.StepActionList) []*v1beta1.StepAction { return gentype.ToPointerSlice(list.Items) }, + func(list *v1beta1.StepActionList, items []*v1beta1.StepAction) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, } - return obj.(*v1beta1.StepAction), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_task.go index a98ccdad..f148e14a 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_task.go @@ -19,111 +19,30 @@ limitations under the License. package fake import ( - "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1" + gentype "k8s.io/client-go/gentype" ) -// FakeTasks implements TaskInterface -type FakeTasks struct { +// fakeTasks implements TaskInterface +type fakeTasks struct { + *gentype.FakeClientWithList[*v1beta1.Task, *v1beta1.TaskList] Fake *FakeTektonV1beta1 - ns string -} - -var tasksResource = v1beta1.SchemeGroupVersion.WithResource("tasks") - -var tasksKind = v1beta1.SchemeGroupVersion.WithKind("Task") - -// Get takes name of the task, and returns the corresponding task object, and an error if there is any. -func (c *FakeTasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(tasksResource, c.ns, name), &v1beta1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.Task), err -} - -// List takes label and field selectors, and returns the list of Tasks that match those selectors. -func (c *FakeTasks) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.TaskList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(tasksResource, tasksKind, c.ns, opts), &v1beta1.TaskList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1beta1.TaskList{ListMeta: obj.(*v1beta1.TaskList).ListMeta} - for _, item := range obj.(*v1beta1.TaskList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested tasks. -func (c *FakeTasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(tasksResource, c.ns, opts)) - -} - -// Create takes the representation of a task and creates it. Returns the server's representation of the task, and an error, if there is any. -func (c *FakeTasks) Create(ctx context.Context, task *v1beta1.Task, opts v1.CreateOptions) (result *v1beta1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(tasksResource, c.ns, task), &v1beta1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.Task), err -} - -// Update takes the representation of a task and updates it. Returns the server's representation of the task, and an error, if there is any. -func (c *FakeTasks) Update(ctx context.Context, task *v1beta1.Task, opts v1.UpdateOptions) (result *v1beta1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(tasksResource, c.ns, task), &v1beta1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.Task), err -} - -// Delete takes name of the task and deletes it. Returns an error if one occurs. -func (c *FakeTasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(tasksResource, c.ns, name, opts), &v1beta1.Task{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeTasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(tasksResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1beta1.TaskList{}) - return err -} - -// Patch applies the patch and returns the patched task. -func (c *FakeTasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(tasksResource, c.ns, name, pt, data, subresources...), &v1beta1.Task{}) - - if obj == nil { - return nil, err +func newFakeTasks(fake *FakeTektonV1beta1, namespace string) pipelinev1beta1.TaskInterface { + return &fakeTasks{ + gentype.NewFakeClientWithList[*v1beta1.Task, *v1beta1.TaskList]( + fake.Fake, + namespace, + v1beta1.SchemeGroupVersion.WithResource("tasks"), + v1beta1.SchemeGroupVersion.WithKind("Task"), + func() *v1beta1.Task { return &v1beta1.Task{} }, + func() *v1beta1.TaskList { return &v1beta1.TaskList{} }, + func(dst, src *v1beta1.TaskList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.TaskList) []*v1beta1.Task { return gentype.ToPointerSlice(list.Items) }, + func(list *v1beta1.TaskList, items []*v1beta1.Task) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, } - return obj.(*v1beta1.Task), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_taskrun.go index 68b3b40e..2a838d2e 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/fake/fake_taskrun.go @@ -19,123 +19,32 @@ limitations under the License. package fake import ( - "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1" + gentype "k8s.io/client-go/gentype" ) -// FakeTaskRuns implements TaskRunInterface -type FakeTaskRuns struct { +// fakeTaskRuns implements TaskRunInterface +type fakeTaskRuns struct { + *gentype.FakeClientWithList[*v1beta1.TaskRun, *v1beta1.TaskRunList] Fake *FakeTektonV1beta1 - ns string -} - -var taskrunsResource = v1beta1.SchemeGroupVersion.WithResource("taskruns") - -var taskrunsKind = v1beta1.SchemeGroupVersion.WithKind("TaskRun") - -// Get takes name of the taskRun, and returns the corresponding taskRun object, and an error if there is any. -func (c *FakeTaskRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(taskrunsResource, c.ns, name), &v1beta1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.TaskRun), err -} - -// List takes label and field selectors, and returns the list of TaskRuns that match those selectors. -func (c *FakeTaskRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.TaskRunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(taskrunsResource, taskrunsKind, c.ns, opts), &v1beta1.TaskRunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1beta1.TaskRunList{ListMeta: obj.(*v1beta1.TaskRunList).ListMeta} - for _, item := range obj.(*v1beta1.TaskRunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested taskRuns. -func (c *FakeTaskRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(taskrunsResource, c.ns, opts)) - -} - -// Create takes the representation of a taskRun and creates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *FakeTaskRuns) Create(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.CreateOptions) (result *v1beta1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(taskrunsResource, c.ns, taskRun), &v1beta1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.TaskRun), err -} - -// Update takes the representation of a taskRun and updates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *FakeTaskRuns) Update(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.UpdateOptions) (result *v1beta1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(taskrunsResource, c.ns, taskRun), &v1beta1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.TaskRun), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeTaskRuns) UpdateStatus(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.UpdateOptions) (*v1beta1.TaskRun, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(taskrunsResource, "status", c.ns, taskRun), &v1beta1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1beta1.TaskRun), err -} - -// Delete takes name of the taskRun and deletes it. Returns an error if one occurs. -func (c *FakeTaskRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(taskrunsResource, c.ns, name, opts), &v1beta1.TaskRun{}) - - return err } -// DeleteCollection deletes a collection of objects. -func (c *FakeTaskRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(taskrunsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1beta1.TaskRunList{}) - return err -} - -// Patch applies the patch and returns the patched taskRun. -func (c *FakeTaskRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(taskrunsResource, c.ns, name, pt, data, subresources...), &v1beta1.TaskRun{}) - - if obj == nil { - return nil, err +func newFakeTaskRuns(fake *FakeTektonV1beta1, namespace string) pipelinev1beta1.TaskRunInterface { + return &fakeTaskRuns{ + gentype.NewFakeClientWithList[*v1beta1.TaskRun, *v1beta1.TaskRunList]( + fake.Fake, + namespace, + v1beta1.SchemeGroupVersion.WithResource("taskruns"), + v1beta1.SchemeGroupVersion.WithKind("TaskRun"), + func() *v1beta1.TaskRun { return &v1beta1.TaskRun{} }, + func() *v1beta1.TaskRunList { return &v1beta1.TaskRunList{} }, + func(dst, src *v1beta1.TaskRunList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.TaskRunList) []*v1beta1.TaskRun { return gentype.ToPointerSlice(list.Items) }, + func(list *v1beta1.TaskRunList, items []*v1beta1.TaskRun) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, } - return obj.(*v1beta1.TaskRun), err } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/generated_expansion.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/generated_expansion.go index 87f277c5..14e3f6b8 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/generated_expansion.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/generated_expansion.go @@ -18,8 +18,6 @@ limitations under the License. package v1beta1 -type ClusterTaskExpansion interface{} - type CustomRunExpansion interface{} type PipelineExpansion interface{} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline.go index 1bfe8d58..0ca4f99a 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline.go @@ -19,15 +19,14 @@ limitations under the License. package v1beta1 import ( - "context" - "time" + context "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // PipelinesGetter has a method to return a PipelineInterface. @@ -38,141 +37,32 @@ type PipelinesGetter interface { // PipelineInterface has methods to work with Pipeline resources. type PipelineInterface interface { - Create(ctx context.Context, pipeline *v1beta1.Pipeline, opts v1.CreateOptions) (*v1beta1.Pipeline, error) - Update(ctx context.Context, pipeline *v1beta1.Pipeline, opts v1.UpdateOptions) (*v1beta1.Pipeline, error) + Create(ctx context.Context, pipeline *pipelinev1beta1.Pipeline, opts v1.CreateOptions) (*pipelinev1beta1.Pipeline, error) + Update(ctx context.Context, pipeline *pipelinev1beta1.Pipeline, opts v1.UpdateOptions) (*pipelinev1beta1.Pipeline, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.Pipeline, error) - List(ctx context.Context, opts v1.ListOptions) (*v1beta1.PipelineList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1beta1.Pipeline, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1beta1.PipelineList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Pipeline, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1beta1.Pipeline, err error) PipelineExpansion } // pipelines implements PipelineInterface type pipelines struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1beta1.Pipeline, *pipelinev1beta1.PipelineList] } // newPipelines returns a Pipelines func newPipelines(c *TektonV1beta1Client, namespace string) *pipelines { return &pipelines{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1beta1.Pipeline, *pipelinev1beta1.PipelineList]( + "pipelines", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1beta1.Pipeline { return &pipelinev1beta1.Pipeline{} }, + func() *pipelinev1beta1.PipelineList { return &pipelinev1beta1.PipelineList{} }, + ), } } - -// Get takes name of the pipeline, and returns the corresponding pipeline object, and an error if there is any. -func (c *pipelines) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Pipeline, err error) { - result = &v1beta1.Pipeline{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Pipelines that match those selectors. -func (c *pipelines) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PipelineList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1beta1.PipelineList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested pipelines. -func (c *pipelines) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a pipeline and creates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *pipelines) Create(ctx context.Context, pipeline *v1beta1.Pipeline, opts v1.CreateOptions) (result *v1beta1.Pipeline, err error) { - result = &v1beta1.Pipeline{} - err = c.client.Post(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipeline). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a pipeline and updates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *pipelines) Update(ctx context.Context, pipeline *v1beta1.Pipeline, opts v1.UpdateOptions) (result *v1beta1.Pipeline, err error) { - result = &v1beta1.Pipeline{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelines"). - Name(pipeline.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipeline). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the pipeline and deletes it. Returns an error if one occurs. -func (c *pipelines) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *pipelines) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched pipeline. -func (c *pipelines) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Pipeline, err error) { - result = &v1beta1.Pipeline{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline_client.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline_client.go index fcd65e7c..c0e098f6 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline_client.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipeline_client.go @@ -19,16 +19,15 @@ limitations under the License. package v1beta1 import ( - "net/http" + http "net/http" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" rest "k8s.io/client-go/rest" ) type TektonV1beta1Interface interface { RESTClient() rest.Interface - ClusterTasksGetter CustomRunsGetter PipelinesGetter PipelineRunsGetter @@ -42,10 +41,6 @@ type TektonV1beta1Client struct { restClient rest.Interface } -func (c *TektonV1beta1Client) ClusterTasks() ClusterTaskInterface { - return newClusterTasks(c) -} - func (c *TektonV1beta1Client) CustomRuns(namespace string) CustomRunInterface { return newCustomRuns(c, namespace) } @@ -115,10 +110,10 @@ func New(c rest.Interface) *TektonV1beta1Client { } func setConfigDefaults(config *rest.Config) error { - gv := v1beta1.SchemeGroupVersion + gv := pipelinev1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipelinerun.go index 5399858f..c9678f47 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/pipelinerun.go @@ -19,15 +19,14 @@ limitations under the License. package v1beta1 import ( - "context" - "time" + context "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // PipelineRunsGetter has a method to return a PipelineRunInterface. @@ -38,158 +37,34 @@ type PipelineRunsGetter interface { // PipelineRunInterface has methods to work with PipelineRun resources. type PipelineRunInterface interface { - Create(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.CreateOptions) (*v1beta1.PipelineRun, error) - Update(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.UpdateOptions) (*v1beta1.PipelineRun, error) - UpdateStatus(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.UpdateOptions) (*v1beta1.PipelineRun, error) + Create(ctx context.Context, pipelineRun *pipelinev1beta1.PipelineRun, opts v1.CreateOptions) (*pipelinev1beta1.PipelineRun, error) + Update(ctx context.Context, pipelineRun *pipelinev1beta1.PipelineRun, opts v1.UpdateOptions) (*pipelinev1beta1.PipelineRun, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, pipelineRun *pipelinev1beta1.PipelineRun, opts v1.UpdateOptions) (*pipelinev1beta1.PipelineRun, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.PipelineRun, error) - List(ctx context.Context, opts v1.ListOptions) (*v1beta1.PipelineRunList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1beta1.PipelineRun, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1beta1.PipelineRunList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PipelineRun, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1beta1.PipelineRun, err error) PipelineRunExpansion } // pipelineRuns implements PipelineRunInterface type pipelineRuns struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1beta1.PipelineRun, *pipelinev1beta1.PipelineRunList] } // newPipelineRuns returns a PipelineRuns func newPipelineRuns(c *TektonV1beta1Client, namespace string) *pipelineRuns { return &pipelineRuns{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1beta1.PipelineRun, *pipelinev1beta1.PipelineRunList]( + "pipelineruns", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1beta1.PipelineRun { return &pipelinev1beta1.PipelineRun{} }, + func() *pipelinev1beta1.PipelineRunList { return &pipelinev1beta1.PipelineRunList{} }, + ), } } - -// Get takes name of the pipelineRun, and returns the corresponding pipelineRun object, and an error if there is any. -func (c *pipelineRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PipelineRun, err error) { - result = &v1beta1.PipelineRun{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of PipelineRuns that match those selectors. -func (c *pipelineRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PipelineRunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1beta1.PipelineRunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested pipelineRuns. -func (c *pipelineRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a pipelineRun and creates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *pipelineRuns) Create(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.CreateOptions) (result *v1beta1.PipelineRun, err error) { - result = &v1beta1.PipelineRun{} - err = c.client.Post(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a pipelineRun and updates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *pipelineRuns) Update(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.UpdateOptions) (result *v1beta1.PipelineRun, err error) { - result = &v1beta1.PipelineRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(pipelineRun.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *pipelineRuns) UpdateStatus(ctx context.Context, pipelineRun *v1beta1.PipelineRun, opts v1.UpdateOptions) (result *v1beta1.PipelineRun, err error) { - result = &v1beta1.PipelineRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(pipelineRun.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the pipelineRun and deletes it. Returns an error if one occurs. -func (c *pipelineRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *pipelineRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched pipelineRun. -func (c *pipelineRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PipelineRun, err error) { - result = &v1beta1.PipelineRun{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/stepaction.go index 388f0629..61e76208 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/stepaction.go @@ -19,15 +19,14 @@ limitations under the License. package v1beta1 import ( - "context" - "time" + context "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // StepActionsGetter has a method to return a StepActionInterface. @@ -38,141 +37,32 @@ type StepActionsGetter interface { // StepActionInterface has methods to work with StepAction resources. type StepActionInterface interface { - Create(ctx context.Context, stepAction *v1beta1.StepAction, opts v1.CreateOptions) (*v1beta1.StepAction, error) - Update(ctx context.Context, stepAction *v1beta1.StepAction, opts v1.UpdateOptions) (*v1beta1.StepAction, error) + Create(ctx context.Context, stepAction *pipelinev1beta1.StepAction, opts v1.CreateOptions) (*pipelinev1beta1.StepAction, error) + Update(ctx context.Context, stepAction *pipelinev1beta1.StepAction, opts v1.UpdateOptions) (*pipelinev1beta1.StepAction, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.StepAction, error) - List(ctx context.Context, opts v1.ListOptions) (*v1beta1.StepActionList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1beta1.StepAction, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1beta1.StepActionList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.StepAction, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1beta1.StepAction, err error) StepActionExpansion } // stepActions implements StepActionInterface type stepActions struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1beta1.StepAction, *pipelinev1beta1.StepActionList] } // newStepActions returns a StepActions func newStepActions(c *TektonV1beta1Client, namespace string) *stepActions { return &stepActions{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1beta1.StepAction, *pipelinev1beta1.StepActionList]( + "stepactions", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1beta1.StepAction { return &pipelinev1beta1.StepAction{} }, + func() *pipelinev1beta1.StepActionList { return &pipelinev1beta1.StepActionList{} }, + ), } } - -// Get takes name of the stepAction, and returns the corresponding stepAction object, and an error if there is any. -func (c *stepActions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.StepAction, err error) { - result = &v1beta1.StepAction{} - err = c.client.Get(). - Namespace(c.ns). - Resource("stepactions"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of StepActions that match those selectors. -func (c *stepActions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.StepActionList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1beta1.StepActionList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested stepActions. -func (c *stepActions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a stepAction and creates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *stepActions) Create(ctx context.Context, stepAction *v1beta1.StepAction, opts v1.CreateOptions) (result *v1beta1.StepAction, err error) { - result = &v1beta1.StepAction{} - err = c.client.Post(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(stepAction). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a stepAction and updates it. Returns the server's representation of the stepAction, and an error, if there is any. -func (c *stepActions) Update(ctx context.Context, stepAction *v1beta1.StepAction, opts v1.UpdateOptions) (result *v1beta1.StepAction, err error) { - result = &v1beta1.StepAction{} - err = c.client.Put(). - Namespace(c.ns). - Resource("stepactions"). - Name(stepAction.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(stepAction). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the stepAction and deletes it. Returns an error if one occurs. -func (c *stepActions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("stepactions"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *stepActions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("stepactions"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched stepAction. -func (c *stepActions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.StepAction, err error) { - result = &v1beta1.StepAction{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("stepactions"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/task.go index a024ed71..18cfe697 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/task.go @@ -19,15 +19,14 @@ limitations under the License. package v1beta1 import ( - "context" - "time" + context "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // TasksGetter has a method to return a TaskInterface. @@ -38,141 +37,32 @@ type TasksGetter interface { // TaskInterface has methods to work with Task resources. type TaskInterface interface { - Create(ctx context.Context, task *v1beta1.Task, opts v1.CreateOptions) (*v1beta1.Task, error) - Update(ctx context.Context, task *v1beta1.Task, opts v1.UpdateOptions) (*v1beta1.Task, error) + Create(ctx context.Context, task *pipelinev1beta1.Task, opts v1.CreateOptions) (*pipelinev1beta1.Task, error) + Update(ctx context.Context, task *pipelinev1beta1.Task, opts v1.UpdateOptions) (*pipelinev1beta1.Task, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.Task, error) - List(ctx context.Context, opts v1.ListOptions) (*v1beta1.TaskList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1beta1.Task, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1beta1.TaskList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Task, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1beta1.Task, err error) TaskExpansion } // tasks implements TaskInterface type tasks struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1beta1.Task, *pipelinev1beta1.TaskList] } // newTasks returns a Tasks func newTasks(c *TektonV1beta1Client, namespace string) *tasks { return &tasks{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1beta1.Task, *pipelinev1beta1.TaskList]( + "tasks", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1beta1.Task { return &pipelinev1beta1.Task{} }, + func() *pipelinev1beta1.TaskList { return &pipelinev1beta1.TaskList{} }, + ), } } - -// Get takes name of the task, and returns the corresponding task object, and an error if there is any. -func (c *tasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Task, err error) { - result = &v1beta1.Task{} - err = c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Tasks that match those selectors. -func (c *tasks) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.TaskList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1beta1.TaskList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested tasks. -func (c *tasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a task and creates it. Returns the server's representation of the task, and an error, if there is any. -func (c *tasks) Create(ctx context.Context, task *v1beta1.Task, opts v1.CreateOptions) (result *v1beta1.Task, err error) { - result = &v1beta1.Task{} - err = c.client.Post(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(task). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a task and updates it. Returns the server's representation of the task, and an error, if there is any. -func (c *tasks) Update(ctx context.Context, task *v1beta1.Task, opts v1.UpdateOptions) (result *v1beta1.Task, err error) { - result = &v1beta1.Task{} - err = c.client.Put(). - Namespace(c.ns). - Resource("tasks"). - Name(task.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(task). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the task and deletes it. Returns an error if one occurs. -func (c *tasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("tasks"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *tasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched task. -func (c *tasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Task, err error) { - result = &v1beta1.Task{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("tasks"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/taskrun.go index 5611be7d..a9209e51 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/taskrun.go @@ -19,15 +19,14 @@ limitations under the License. package v1beta1 import ( - "context" - "time" + context "context" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" + gentype "k8s.io/client-go/gentype" ) // TaskRunsGetter has a method to return a TaskRunInterface. @@ -38,158 +37,34 @@ type TaskRunsGetter interface { // TaskRunInterface has methods to work with TaskRun resources. type TaskRunInterface interface { - Create(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.CreateOptions) (*v1beta1.TaskRun, error) - Update(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.UpdateOptions) (*v1beta1.TaskRun, error) - UpdateStatus(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.UpdateOptions) (*v1beta1.TaskRun, error) + Create(ctx context.Context, taskRun *pipelinev1beta1.TaskRun, opts v1.CreateOptions) (*pipelinev1beta1.TaskRun, error) + Update(ctx context.Context, taskRun *pipelinev1beta1.TaskRun, opts v1.UpdateOptions) (*pipelinev1beta1.TaskRun, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, taskRun *pipelinev1beta1.TaskRun, opts v1.UpdateOptions) (*pipelinev1beta1.TaskRun, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.TaskRun, error) - List(ctx context.Context, opts v1.ListOptions) (*v1beta1.TaskRunList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*pipelinev1beta1.TaskRun, error) + List(ctx context.Context, opts v1.ListOptions) (*pipelinev1beta1.TaskRunList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.TaskRun, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *pipelinev1beta1.TaskRun, err error) TaskRunExpansion } // taskRuns implements TaskRunInterface type taskRuns struct { - client rest.Interface - ns string + *gentype.ClientWithList[*pipelinev1beta1.TaskRun, *pipelinev1beta1.TaskRunList] } // newTaskRuns returns a TaskRuns func newTaskRuns(c *TektonV1beta1Client, namespace string) *taskRuns { return &taskRuns{ - client: c.RESTClient(), - ns: namespace, + gentype.NewClientWithList[*pipelinev1beta1.TaskRun, *pipelinev1beta1.TaskRunList]( + "taskruns", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *pipelinev1beta1.TaskRun { return &pipelinev1beta1.TaskRun{} }, + func() *pipelinev1beta1.TaskRunList { return &pipelinev1beta1.TaskRunList{} }, + ), } } - -// Get takes name of the taskRun, and returns the corresponding taskRun object, and an error if there is any. -func (c *taskRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.TaskRun, err error) { - result = &v1beta1.TaskRun{} - err = c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of TaskRuns that match those selectors. -func (c *taskRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.TaskRunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1beta1.TaskRunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested taskRuns. -func (c *taskRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a taskRun and creates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *taskRuns) Create(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.CreateOptions) (result *v1beta1.TaskRun, err error) { - result = &v1beta1.TaskRun{} - err = c.client.Post(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a taskRun and updates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *taskRuns) Update(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.UpdateOptions) (result *v1beta1.TaskRun, err error) { - result = &v1beta1.TaskRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("taskruns"). - Name(taskRun.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *taskRuns) UpdateStatus(ctx context.Context, taskRun *v1beta1.TaskRun, opts v1.UpdateOptions) (result *v1beta1.TaskRun, err error) { - result = &v1beta1.TaskRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("taskruns"). - Name(taskRun.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the taskRun and deletes it. Returns an error if one occurs. -func (c *taskRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *taskRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched taskRun. -func (c *taskRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.TaskRun, err error) { - result = &v1beta1.TaskRun{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/factory.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/factory.go index 839585d5..79e8d60f 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/factory.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/factory.go @@ -228,6 +228,7 @@ type SharedInformerFactory interface { // Start initializes all requested informers. They are handled in goroutines // which run until the stop channel gets closed. + // Warning: Start does not block. When run in a go-routine, it will race with a later WaitForCacheSync. Start(stopCh <-chan struct{}) // Shutdown marks a factory as shutting down. At that point no new diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/generic.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/generic.go index fe44a25a..7d6f3fe1 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/generic.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/generic.go @@ -19,7 +19,7 @@ limitations under the License. package externalversions import ( - "fmt" + fmt "fmt" v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" @@ -73,8 +73,6 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1alpha1().VerificationPolicies().Informer()}, nil // Group=tekton.dev, Version=v1beta1 - case v1beta1.SchemeGroupVersion.WithResource("clustertasks"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1beta1().ClusterTasks().Informer()}, nil case v1beta1.SchemeGroupVersion.WithResource("customruns"): return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1beta1().CustomRuns().Informer()}, nil case v1beta1.SchemeGroupVersion.WithResource("pipelines"): diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/interface.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/interface.go index 71e38c57..a3872118 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/interface.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/interface.go @@ -27,12 +27,12 @@ import ( // Interface provides access to each of this group's versions. type Interface interface { + // V1 provides access to shared informers for resources in V1. + V1() v1.Interface // V1alpha1 provides access to shared informers for resources in V1alpha1. V1alpha1() v1alpha1.Interface // V1beta1 provides access to shared informers for resources in V1beta1. V1beta1() v1beta1.Interface - // V1 provides access to shared informers for resources in V1. - V1() v1.Interface } type group struct { @@ -46,6 +46,11 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } +// V1 returns a new v1.Interface. +func (g *group) V1() v1.Interface { + return v1.New(g.factory, g.namespace, g.tweakListOptions) +} + // V1alpha1 returns a new v1alpha1.Interface. func (g *group) V1alpha1() v1alpha1.Interface { return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) @@ -55,8 +60,3 @@ func (g *group) V1alpha1() v1alpha1.Interface { func (g *group) V1beta1() v1beta1.Interface { return v1beta1.New(g.factory, g.namespace, g.tweakListOptions) } - -// V1 returns a new v1.Interface. -func (g *group) V1() v1.Interface { - return v1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipeline.go index 6340cee7..e6a493e3 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipeline.go @@ -19,13 +19,13 @@ limitations under the License. package v1 import ( - "context" + context "context" time "time" - pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + apispipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // Pipelines. type PipelineInformer interface { Informer() cache.SharedIndexInformer - Lister() v1.PipelineLister + Lister() pipelinev1.PipelineLister } type pipelineInformer struct { @@ -71,7 +71,7 @@ func NewFilteredPipelineInformer(client versioned.Interface, namespace string, r return client.TektonV1().Pipelines(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1.Pipeline{}, + &apispipelinev1.Pipeline{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *pipelineInformer) defaultInformer(client versioned.Interface, resyncPer } func (f *pipelineInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1.Pipeline{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1.Pipeline{}, f.defaultInformer) } -func (f *pipelineInformer) Lister() v1.PipelineLister { - return v1.NewPipelineLister(f.Informer().GetIndexer()) +func (f *pipelineInformer) Lister() pipelinev1.PipelineLister { + return pipelinev1.NewPipelineLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipelinerun.go index 4e02db3c..9dea64f5 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/pipelinerun.go @@ -19,13 +19,13 @@ limitations under the License. package v1 import ( - "context" + context "context" time "time" - pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + apispipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // PipelineRuns. type PipelineRunInformer interface { Informer() cache.SharedIndexInformer - Lister() v1.PipelineRunLister + Lister() pipelinev1.PipelineRunLister } type pipelineRunInformer struct { @@ -71,7 +71,7 @@ func NewFilteredPipelineRunInformer(client versioned.Interface, namespace string return client.TektonV1().PipelineRuns(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1.PipelineRun{}, + &apispipelinev1.PipelineRun{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *pipelineRunInformer) defaultInformer(client versioned.Interface, resync } func (f *pipelineRunInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1.PipelineRun{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1.PipelineRun{}, f.defaultInformer) } -func (f *pipelineRunInformer) Lister() v1.PipelineRunLister { - return v1.NewPipelineRunLister(f.Informer().GetIndexer()) +func (f *pipelineRunInformer) Lister() pipelinev1.PipelineRunLister { + return pipelinev1.NewPipelineRunLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/task.go index 2e6f539e..431324e6 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/task.go @@ -19,13 +19,13 @@ limitations under the License. package v1 import ( - "context" + context "context" time "time" - pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + apispipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // Tasks. type TaskInformer interface { Informer() cache.SharedIndexInformer - Lister() v1.TaskLister + Lister() pipelinev1.TaskLister } type taskInformer struct { @@ -71,7 +71,7 @@ func NewFilteredTaskInformer(client versioned.Interface, namespace string, resyn return client.TektonV1().Tasks(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1.Task{}, + &apispipelinev1.Task{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *taskInformer) defaultInformer(client versioned.Interface, resyncPeriod } func (f *taskInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1.Task{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1.Task{}, f.defaultInformer) } -func (f *taskInformer) Lister() v1.TaskLister { - return v1.NewTaskLister(f.Informer().GetIndexer()) +func (f *taskInformer) Lister() pipelinev1.TaskLister { + return pipelinev1.NewTaskLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/taskrun.go index d8ef20c0..7289ca02 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1/taskrun.go @@ -19,13 +19,13 @@ limitations under the License. package v1 import ( - "context" + context "context" time "time" - pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + apispipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" + pipelinev1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // TaskRuns. type TaskRunInformer interface { Informer() cache.SharedIndexInformer - Lister() v1.TaskRunLister + Lister() pipelinev1.TaskRunLister } type taskRunInformer struct { @@ -71,7 +71,7 @@ func NewFilteredTaskRunInformer(client versioned.Interface, namespace string, re return client.TektonV1().TaskRuns(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1.TaskRun{}, + &apispipelinev1.TaskRun{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *taskRunInformer) defaultInformer(client versioned.Interface, resyncPeri } func (f *taskRunInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1.TaskRun{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1.TaskRun{}, f.defaultInformer) } -func (f *taskRunInformer) Lister() v1.TaskRunLister { - return v1.NewTaskRunLister(f.Informer().GetIndexer()) +func (f *taskRunInformer) Lister() pipelinev1.TaskRunLister { + return pipelinev1.NewTaskRunLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/run.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/run.go index a89050ce..80aa5762 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/run.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/run.go @@ -19,13 +19,13 @@ limitations under the License. package v1alpha1 import ( - "context" + context "context" time "time" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // Runs. type RunInformer interface { Informer() cache.SharedIndexInformer - Lister() v1alpha1.RunLister + Lister() pipelinev1alpha1.RunLister } type runInformer struct { @@ -71,7 +71,7 @@ func NewFilteredRunInformer(client versioned.Interface, namespace string, resync return client.TektonV1alpha1().Runs(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1alpha1.Run{}, + &apispipelinev1alpha1.Run{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *runInformer) defaultInformer(client versioned.Interface, resyncPeriod t } func (f *runInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.Run{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1alpha1.Run{}, f.defaultInformer) } -func (f *runInformer) Lister() v1alpha1.RunLister { - return v1alpha1.NewRunLister(f.Informer().GetIndexer()) +func (f *runInformer) Lister() pipelinev1alpha1.RunLister { + return pipelinev1alpha1.NewRunLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/stepaction.go index d381c8b8..348136f2 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/stepaction.go @@ -19,13 +19,13 @@ limitations under the License. package v1alpha1 import ( - "context" + context "context" time "time" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // StepActions. type StepActionInformer interface { Informer() cache.SharedIndexInformer - Lister() v1alpha1.StepActionLister + Lister() pipelinev1alpha1.StepActionLister } type stepActionInformer struct { @@ -71,7 +71,7 @@ func NewFilteredStepActionInformer(client versioned.Interface, namespace string, return client.TektonV1alpha1().StepActions(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1alpha1.StepAction{}, + &apispipelinev1alpha1.StepAction{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *stepActionInformer) defaultInformer(client versioned.Interface, resyncP } func (f *stepActionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.StepAction{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1alpha1.StepAction{}, f.defaultInformer) } -func (f *stepActionInformer) Lister() v1alpha1.StepActionLister { - return v1alpha1.NewStepActionLister(f.Informer().GetIndexer()) +func (f *stepActionInformer) Lister() pipelinev1alpha1.StepActionLister { + return pipelinev1alpha1.NewStepActionLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/verificationpolicy.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/verificationpolicy.go index 622a6a03..7a1bf1ce 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/verificationpolicy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1/verificationpolicy.go @@ -19,13 +19,13 @@ limitations under the License. package v1alpha1 import ( - "context" + context "context" time "time" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // VerificationPolicies. type VerificationPolicyInformer interface { Informer() cache.SharedIndexInformer - Lister() v1alpha1.VerificationPolicyLister + Lister() pipelinev1alpha1.VerificationPolicyLister } type verificationPolicyInformer struct { @@ -71,7 +71,7 @@ func NewFilteredVerificationPolicyInformer(client versioned.Interface, namespace return client.TektonV1alpha1().VerificationPolicies(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1alpha1.VerificationPolicy{}, + &apispipelinev1alpha1.VerificationPolicy{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *verificationPolicyInformer) defaultInformer(client versioned.Interface, } func (f *verificationPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.VerificationPolicy{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1alpha1.VerificationPolicy{}, f.defaultInformer) } -func (f *verificationPolicyInformer) Lister() v1alpha1.VerificationPolicyLister { - return v1alpha1.NewVerificationPolicyLister(f.Informer().GetIndexer()) +func (f *verificationPolicyInformer) Lister() pipelinev1alpha1.VerificationPolicyLister { + return pipelinev1alpha1.NewVerificationPolicyLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/clustertask.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/clustertask.go deleted file mode 100644 index 8c006c47..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/clustertask.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1beta1 - -import ( - "context" - time "time" - - pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterTaskInformer provides access to a shared informer and lister for -// ClusterTasks. -type ClusterTaskInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1beta1.ClusterTaskLister -} - -type clusterTaskInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewClusterTaskInformer constructs a new informer for ClusterTask type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterTaskInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterTaskInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterTaskInformer constructs a new informer for ClusterTask type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterTaskInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1beta1().ClusterTasks().List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1beta1().ClusterTasks().Watch(context.TODO(), options) - }, - }, - &pipelinev1beta1.ClusterTask{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterTaskInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterTaskInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterTaskInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1beta1.ClusterTask{}, f.defaultInformer) -} - -func (f *clusterTaskInformer) Lister() v1beta1.ClusterTaskLister { - return v1beta1.NewClusterTaskLister(f.Informer().GetIndexer()) -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/customrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/customrun.go index 532a61c8..18a7e384 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/customrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/customrun.go @@ -19,13 +19,13 @@ limitations under the License. package v1beta1 import ( - "context" + context "context" time "time" - pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + apispipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // CustomRuns. type CustomRunInformer interface { Informer() cache.SharedIndexInformer - Lister() v1beta1.CustomRunLister + Lister() pipelinev1beta1.CustomRunLister } type customRunInformer struct { @@ -71,7 +71,7 @@ func NewFilteredCustomRunInformer(client versioned.Interface, namespace string, return client.TektonV1beta1().CustomRuns(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1beta1.CustomRun{}, + &apispipelinev1beta1.CustomRun{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *customRunInformer) defaultInformer(client versioned.Interface, resyncPe } func (f *customRunInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1beta1.CustomRun{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1beta1.CustomRun{}, f.defaultInformer) } -func (f *customRunInformer) Lister() v1beta1.CustomRunLister { - return v1beta1.NewCustomRunLister(f.Informer().GetIndexer()) +func (f *customRunInformer) Lister() pipelinev1beta1.CustomRunLister { + return pipelinev1beta1.NewCustomRunLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/interface.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/interface.go index 2821b942..4256abd2 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/interface.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/interface.go @@ -24,8 +24,6 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { - // ClusterTasks returns a ClusterTaskInformer. - ClusterTasks() ClusterTaskInformer // CustomRuns returns a CustomRunInformer. CustomRuns() CustomRunInformer // Pipelines returns a PipelineInformer. @@ -51,11 +49,6 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ClusterTasks returns a ClusterTaskInformer. -func (v *version) ClusterTasks() ClusterTaskInformer { - return &clusterTaskInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - // CustomRuns returns a CustomRunInformer. func (v *version) CustomRuns() CustomRunInformer { return &customRunInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipeline.go index 1223fe0d..8fd2ea75 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipeline.go @@ -19,13 +19,13 @@ limitations under the License. package v1beta1 import ( - "context" + context "context" time "time" - pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + apispipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // Pipelines. type PipelineInformer interface { Informer() cache.SharedIndexInformer - Lister() v1beta1.PipelineLister + Lister() pipelinev1beta1.PipelineLister } type pipelineInformer struct { @@ -71,7 +71,7 @@ func NewFilteredPipelineInformer(client versioned.Interface, namespace string, r return client.TektonV1beta1().Pipelines(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1beta1.Pipeline{}, + &apispipelinev1beta1.Pipeline{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *pipelineInformer) defaultInformer(client versioned.Interface, resyncPer } func (f *pipelineInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1beta1.Pipeline{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1beta1.Pipeline{}, f.defaultInformer) } -func (f *pipelineInformer) Lister() v1beta1.PipelineLister { - return v1beta1.NewPipelineLister(f.Informer().GetIndexer()) +func (f *pipelineInformer) Lister() pipelinev1beta1.PipelineLister { + return pipelinev1beta1.NewPipelineLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipelinerun.go index e0c03cc0..9c443bb1 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/pipelinerun.go @@ -19,13 +19,13 @@ limitations under the License. package v1beta1 import ( - "context" + context "context" time "time" - pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + apispipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // PipelineRuns. type PipelineRunInformer interface { Informer() cache.SharedIndexInformer - Lister() v1beta1.PipelineRunLister + Lister() pipelinev1beta1.PipelineRunLister } type pipelineRunInformer struct { @@ -71,7 +71,7 @@ func NewFilteredPipelineRunInformer(client versioned.Interface, namespace string return client.TektonV1beta1().PipelineRuns(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1beta1.PipelineRun{}, + &apispipelinev1beta1.PipelineRun{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *pipelineRunInformer) defaultInformer(client versioned.Interface, resync } func (f *pipelineRunInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1beta1.PipelineRun{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1beta1.PipelineRun{}, f.defaultInformer) } -func (f *pipelineRunInformer) Lister() v1beta1.PipelineRunLister { - return v1beta1.NewPipelineRunLister(f.Informer().GetIndexer()) +func (f *pipelineRunInformer) Lister() pipelinev1beta1.PipelineRunLister { + return pipelinev1beta1.NewPipelineRunLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/stepaction.go index 4ec85781..76f5c5dc 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/stepaction.go @@ -19,13 +19,13 @@ limitations under the License. package v1beta1 import ( - "context" + context "context" time "time" - pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + apispipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // StepActions. type StepActionInformer interface { Informer() cache.SharedIndexInformer - Lister() v1beta1.StepActionLister + Lister() pipelinev1beta1.StepActionLister } type stepActionInformer struct { @@ -71,7 +71,7 @@ func NewFilteredStepActionInformer(client versioned.Interface, namespace string, return client.TektonV1beta1().StepActions(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1beta1.StepAction{}, + &apispipelinev1beta1.StepAction{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *stepActionInformer) defaultInformer(client versioned.Interface, resyncP } func (f *stepActionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1beta1.StepAction{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1beta1.StepAction{}, f.defaultInformer) } -func (f *stepActionInformer) Lister() v1beta1.StepActionLister { - return v1beta1.NewStepActionLister(f.Informer().GetIndexer()) +func (f *stepActionInformer) Lister() pipelinev1beta1.StepActionLister { + return pipelinev1beta1.NewStepActionLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/task.go index 33c52576..d1681559 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/task.go @@ -19,13 +19,13 @@ limitations under the License. package v1beta1 import ( - "context" + context "context" time "time" - pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + apispipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // Tasks. type TaskInformer interface { Informer() cache.SharedIndexInformer - Lister() v1beta1.TaskLister + Lister() pipelinev1beta1.TaskLister } type taskInformer struct { @@ -71,7 +71,7 @@ func NewFilteredTaskInformer(client versioned.Interface, namespace string, resyn return client.TektonV1beta1().Tasks(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1beta1.Task{}, + &apispipelinev1beta1.Task{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *taskInformer) defaultInformer(client versioned.Interface, resyncPeriod } func (f *taskInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1beta1.Task{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1beta1.Task{}, f.defaultInformer) } -func (f *taskInformer) Lister() v1beta1.TaskLister { - return v1beta1.NewTaskLister(f.Informer().GetIndexer()) +func (f *taskInformer) Lister() pipelinev1beta1.TaskLister { + return pipelinev1beta1.NewTaskLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/taskrun.go index 8a026d76..a37aa19b 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1/taskrun.go @@ -19,13 +19,13 @@ limitations under the License. package v1beta1 import ( - "context" + context "context" time "time" - pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + apispipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" @@ -36,7 +36,7 @@ import ( // TaskRuns. type TaskRunInformer interface { Informer() cache.SharedIndexInformer - Lister() v1beta1.TaskRunLister + Lister() pipelinev1beta1.TaskRunLister } type taskRunInformer struct { @@ -71,7 +71,7 @@ func NewFilteredTaskRunInformer(client versioned.Interface, namespace string, re return client.TektonV1beta1().TaskRuns(namespace).Watch(context.TODO(), options) }, }, - &pipelinev1beta1.TaskRun{}, + &apispipelinev1beta1.TaskRun{}, resyncPeriod, indexers, ) @@ -82,9 +82,9 @@ func (f *taskRunInformer) defaultInformer(client versioned.Interface, resyncPeri } func (f *taskRunInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1beta1.TaskRun{}, f.defaultInformer) + return f.factory.InformerFor(&apispipelinev1beta1.TaskRun{}, f.defaultInformer) } -func (f *taskRunInformer) Lister() v1beta1.TaskRunLister { - return v1beta1.NewTaskRunLister(f.Informer().GetIndexer()) +func (f *taskRunInformer) Lister() pipelinev1beta1.TaskRunLister { + return pipelinev1beta1.NewTaskRunLister(f.Informer().GetIndexer()) } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/pipelinerun/reconciler.go b/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/pipelinerun/reconciler.go index 4c822765..96c558d9 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/pipelinerun/reconciler.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/pipelinerun/reconciler.go @@ -27,7 +27,7 @@ import ( versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" pipelinev1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" zap "go.uber.org/zap" - "go.uber.org/zap/zapcore" + zapcore "go.uber.org/zap/zapcore" corev1 "k8s.io/api/core/v1" equality "k8s.io/apimachinery/pkg/api/equality" errors "k8s.io/apimachinery/pkg/api/errors" diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/taskrun/reconciler.go b/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/taskrun/reconciler.go index 71cd223e..0b7b9a59 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/taskrun/reconciler.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1/taskrun/reconciler.go @@ -27,7 +27,7 @@ import ( versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" pipelinev1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1" zap "go.uber.org/zap" - "go.uber.org/zap/zapcore" + zapcore "go.uber.org/zap/zapcore" corev1 "k8s.io/api/core/v1" equality "k8s.io/apimachinery/pkg/api/equality" errors "k8s.io/apimachinery/pkg/api/errors" diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipeline.go index 4319ad27..aa8d5101 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipeline.go @@ -19,10 +19,10 @@ limitations under the License. package v1 import ( - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // PipelineLister helps list Pipelines. @@ -30,7 +30,7 @@ import ( type PipelineLister interface { // List lists all Pipelines in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.Pipeline, err error) + List(selector labels.Selector) (ret []*pipelinev1.Pipeline, err error) // Pipelines returns an object that can list and get Pipelines. Pipelines(namespace string) PipelineNamespaceLister PipelineListerExpansion @@ -38,25 +38,17 @@ type PipelineLister interface { // pipelineLister implements the PipelineLister interface. type pipelineLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1.Pipeline] } // NewPipelineLister returns a new PipelineLister. func NewPipelineLister(indexer cache.Indexer) PipelineLister { - return &pipelineLister{indexer: indexer} -} - -// List lists all Pipelines in the indexer. -func (s *pipelineLister) List(selector labels.Selector) (ret []*v1.Pipeline, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Pipeline)) - }) - return ret, err + return &pipelineLister{listers.New[*pipelinev1.Pipeline](indexer, pipelinev1.Resource("pipeline"))} } // Pipelines returns an object that can list and get Pipelines. func (s *pipelineLister) Pipelines(namespace string) PipelineNamespaceLister { - return pipelineNamespaceLister{indexer: s.indexer, namespace: namespace} + return pipelineNamespaceLister{listers.NewNamespaced[*pipelinev1.Pipeline](s.ResourceIndexer, namespace)} } // PipelineNamespaceLister helps list and get Pipelines. @@ -64,36 +56,15 @@ func (s *pipelineLister) Pipelines(namespace string) PipelineNamespaceLister { type PipelineNamespaceLister interface { // List lists all Pipelines in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.Pipeline, err error) + List(selector labels.Selector) (ret []*pipelinev1.Pipeline, err error) // Get retrieves the Pipeline from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1.Pipeline, error) + Get(name string) (*pipelinev1.Pipeline, error) PipelineNamespaceListerExpansion } // pipelineNamespaceLister implements the PipelineNamespaceLister // interface. type pipelineNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Pipelines in the indexer for a given namespace. -func (s pipelineNamespaceLister) List(selector labels.Selector) (ret []*v1.Pipeline, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Pipeline)) - }) - return ret, err -} - -// Get retrieves the Pipeline from the indexer for a given namespace and name. -func (s pipelineNamespaceLister) Get(name string) (*v1.Pipeline, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1.Resource("pipeline"), name) - } - return obj.(*v1.Pipeline), nil + listers.ResourceIndexer[*pipelinev1.Pipeline] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipelinerun.go index 4a16673d..c3e38e00 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/pipelinerun.go @@ -19,10 +19,10 @@ limitations under the License. package v1 import ( - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // PipelineRunLister helps list PipelineRuns. @@ -30,7 +30,7 @@ import ( type PipelineRunLister interface { // List lists all PipelineRuns in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.PipelineRun, err error) + List(selector labels.Selector) (ret []*pipelinev1.PipelineRun, err error) // PipelineRuns returns an object that can list and get PipelineRuns. PipelineRuns(namespace string) PipelineRunNamespaceLister PipelineRunListerExpansion @@ -38,25 +38,17 @@ type PipelineRunLister interface { // pipelineRunLister implements the PipelineRunLister interface. type pipelineRunLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1.PipelineRun] } // NewPipelineRunLister returns a new PipelineRunLister. func NewPipelineRunLister(indexer cache.Indexer) PipelineRunLister { - return &pipelineRunLister{indexer: indexer} -} - -// List lists all PipelineRuns in the indexer. -func (s *pipelineRunLister) List(selector labels.Selector) (ret []*v1.PipelineRun, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.PipelineRun)) - }) - return ret, err + return &pipelineRunLister{listers.New[*pipelinev1.PipelineRun](indexer, pipelinev1.Resource("pipelinerun"))} } // PipelineRuns returns an object that can list and get PipelineRuns. func (s *pipelineRunLister) PipelineRuns(namespace string) PipelineRunNamespaceLister { - return pipelineRunNamespaceLister{indexer: s.indexer, namespace: namespace} + return pipelineRunNamespaceLister{listers.NewNamespaced[*pipelinev1.PipelineRun](s.ResourceIndexer, namespace)} } // PipelineRunNamespaceLister helps list and get PipelineRuns. @@ -64,36 +56,15 @@ func (s *pipelineRunLister) PipelineRuns(namespace string) PipelineRunNamespaceL type PipelineRunNamespaceLister interface { // List lists all PipelineRuns in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.PipelineRun, err error) + List(selector labels.Selector) (ret []*pipelinev1.PipelineRun, err error) // Get retrieves the PipelineRun from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1.PipelineRun, error) + Get(name string) (*pipelinev1.PipelineRun, error) PipelineRunNamespaceListerExpansion } // pipelineRunNamespaceLister implements the PipelineRunNamespaceLister // interface. type pipelineRunNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all PipelineRuns in the indexer for a given namespace. -func (s pipelineRunNamespaceLister) List(selector labels.Selector) (ret []*v1.PipelineRun, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.PipelineRun)) - }) - return ret, err -} - -// Get retrieves the PipelineRun from the indexer for a given namespace and name. -func (s pipelineRunNamespaceLister) Get(name string) (*v1.PipelineRun, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1.Resource("pipelinerun"), name) - } - return obj.(*v1.PipelineRun), nil + listers.ResourceIndexer[*pipelinev1.PipelineRun] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/task.go index e918f2f8..18eb191f 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/task.go @@ -19,10 +19,10 @@ limitations under the License. package v1 import ( - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // TaskLister helps list Tasks. @@ -30,7 +30,7 @@ import ( type TaskLister interface { // List lists all Tasks in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.Task, err error) + List(selector labels.Selector) (ret []*pipelinev1.Task, err error) // Tasks returns an object that can list and get Tasks. Tasks(namespace string) TaskNamespaceLister TaskListerExpansion @@ -38,25 +38,17 @@ type TaskLister interface { // taskLister implements the TaskLister interface. type taskLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1.Task] } // NewTaskLister returns a new TaskLister. func NewTaskLister(indexer cache.Indexer) TaskLister { - return &taskLister{indexer: indexer} -} - -// List lists all Tasks in the indexer. -func (s *taskLister) List(selector labels.Selector) (ret []*v1.Task, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Task)) - }) - return ret, err + return &taskLister{listers.New[*pipelinev1.Task](indexer, pipelinev1.Resource("task"))} } // Tasks returns an object that can list and get Tasks. func (s *taskLister) Tasks(namespace string) TaskNamespaceLister { - return taskNamespaceLister{indexer: s.indexer, namespace: namespace} + return taskNamespaceLister{listers.NewNamespaced[*pipelinev1.Task](s.ResourceIndexer, namespace)} } // TaskNamespaceLister helps list and get Tasks. @@ -64,36 +56,15 @@ func (s *taskLister) Tasks(namespace string) TaskNamespaceLister { type TaskNamespaceLister interface { // List lists all Tasks in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.Task, err error) + List(selector labels.Selector) (ret []*pipelinev1.Task, err error) // Get retrieves the Task from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1.Task, error) + Get(name string) (*pipelinev1.Task, error) TaskNamespaceListerExpansion } // taskNamespaceLister implements the TaskNamespaceLister // interface. type taskNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Tasks in the indexer for a given namespace. -func (s taskNamespaceLister) List(selector labels.Selector) (ret []*v1.Task, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Task)) - }) - return ret, err -} - -// Get retrieves the Task from the indexer for a given namespace and name. -func (s taskNamespaceLister) Get(name string) (*v1.Task, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1.Resource("task"), name) - } - return obj.(*v1.Task), nil + listers.ResourceIndexer[*pipelinev1.Task] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/taskrun.go index 7f5e2c02..f1117526 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1/taskrun.go @@ -19,10 +19,10 @@ limitations under the License. package v1 import ( - v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // TaskRunLister helps list TaskRuns. @@ -30,7 +30,7 @@ import ( type TaskRunLister interface { // List lists all TaskRuns in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.TaskRun, err error) + List(selector labels.Selector) (ret []*pipelinev1.TaskRun, err error) // TaskRuns returns an object that can list and get TaskRuns. TaskRuns(namespace string) TaskRunNamespaceLister TaskRunListerExpansion @@ -38,25 +38,17 @@ type TaskRunLister interface { // taskRunLister implements the TaskRunLister interface. type taskRunLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1.TaskRun] } // NewTaskRunLister returns a new TaskRunLister. func NewTaskRunLister(indexer cache.Indexer) TaskRunLister { - return &taskRunLister{indexer: indexer} -} - -// List lists all TaskRuns in the indexer. -func (s *taskRunLister) List(selector labels.Selector) (ret []*v1.TaskRun, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.TaskRun)) - }) - return ret, err + return &taskRunLister{listers.New[*pipelinev1.TaskRun](indexer, pipelinev1.Resource("taskrun"))} } // TaskRuns returns an object that can list and get TaskRuns. func (s *taskRunLister) TaskRuns(namespace string) TaskRunNamespaceLister { - return taskRunNamespaceLister{indexer: s.indexer, namespace: namespace} + return taskRunNamespaceLister{listers.NewNamespaced[*pipelinev1.TaskRun](s.ResourceIndexer, namespace)} } // TaskRunNamespaceLister helps list and get TaskRuns. @@ -64,36 +56,15 @@ func (s *taskRunLister) TaskRuns(namespace string) TaskRunNamespaceLister { type TaskRunNamespaceLister interface { // List lists all TaskRuns in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.TaskRun, err error) + List(selector labels.Selector) (ret []*pipelinev1.TaskRun, err error) // Get retrieves the TaskRun from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1.TaskRun, error) + Get(name string) (*pipelinev1.TaskRun, error) TaskRunNamespaceListerExpansion } // taskRunNamespaceLister implements the TaskRunNamespaceLister // interface. type taskRunNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all TaskRuns in the indexer for a given namespace. -func (s taskRunNamespaceLister) List(selector labels.Selector) (ret []*v1.TaskRun, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.TaskRun)) - }) - return ret, err -} - -// Get retrieves the TaskRun from the indexer for a given namespace and name. -func (s taskRunNamespaceLister) Get(name string) (*v1.TaskRun, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1.Resource("taskrun"), name) - } - return obj.(*v1.TaskRun), nil + listers.ResourceIndexer[*pipelinev1.TaskRun] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/run.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/run.go index 3ce91c00..e57f9297 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/run.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/run.go @@ -19,10 +19,10 @@ limitations under the License. package v1alpha1 import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // RunLister helps list Runs. @@ -30,7 +30,7 @@ import ( type RunLister interface { // List lists all Runs in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Run, err error) + List(selector labels.Selector) (ret []*pipelinev1alpha1.Run, err error) // Runs returns an object that can list and get Runs. Runs(namespace string) RunNamespaceLister RunListerExpansion @@ -38,25 +38,17 @@ type RunLister interface { // runLister implements the RunLister interface. type runLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1alpha1.Run] } // NewRunLister returns a new RunLister. func NewRunLister(indexer cache.Indexer) RunLister { - return &runLister{indexer: indexer} -} - -// List lists all Runs in the indexer. -func (s *runLister) List(selector labels.Selector) (ret []*v1alpha1.Run, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Run)) - }) - return ret, err + return &runLister{listers.New[*pipelinev1alpha1.Run](indexer, pipelinev1alpha1.Resource("run"))} } // Runs returns an object that can list and get Runs. func (s *runLister) Runs(namespace string) RunNamespaceLister { - return runNamespaceLister{indexer: s.indexer, namespace: namespace} + return runNamespaceLister{listers.NewNamespaced[*pipelinev1alpha1.Run](s.ResourceIndexer, namespace)} } // RunNamespaceLister helps list and get Runs. @@ -64,36 +56,15 @@ func (s *runLister) Runs(namespace string) RunNamespaceLister { type RunNamespaceLister interface { // List lists all Runs in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Run, err error) + List(selector labels.Selector) (ret []*pipelinev1alpha1.Run, err error) // Get retrieves the Run from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.Run, error) + Get(name string) (*pipelinev1alpha1.Run, error) RunNamespaceListerExpansion } // runNamespaceLister implements the RunNamespaceLister // interface. type runNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Runs in the indexer for a given namespace. -func (s runNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Run, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Run)) - }) - return ret, err -} - -// Get retrieves the Run from the indexer for a given namespace and name. -func (s runNamespaceLister) Get(name string) (*v1alpha1.Run, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("run"), name) - } - return obj.(*v1alpha1.Run), nil + listers.ResourceIndexer[*pipelinev1alpha1.Run] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/stepaction.go index 50aebdf8..a6e63e90 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/stepaction.go @@ -19,10 +19,10 @@ limitations under the License. package v1alpha1 import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // StepActionLister helps list StepActions. @@ -30,7 +30,7 @@ import ( type StepActionLister interface { // List lists all StepActions in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.StepAction, err error) + List(selector labels.Selector) (ret []*pipelinev1alpha1.StepAction, err error) // StepActions returns an object that can list and get StepActions. StepActions(namespace string) StepActionNamespaceLister StepActionListerExpansion @@ -38,25 +38,17 @@ type StepActionLister interface { // stepActionLister implements the StepActionLister interface. type stepActionLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1alpha1.StepAction] } // NewStepActionLister returns a new StepActionLister. func NewStepActionLister(indexer cache.Indexer) StepActionLister { - return &stepActionLister{indexer: indexer} -} - -// List lists all StepActions in the indexer. -func (s *stepActionLister) List(selector labels.Selector) (ret []*v1alpha1.StepAction, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.StepAction)) - }) - return ret, err + return &stepActionLister{listers.New[*pipelinev1alpha1.StepAction](indexer, pipelinev1alpha1.Resource("stepaction"))} } // StepActions returns an object that can list and get StepActions. func (s *stepActionLister) StepActions(namespace string) StepActionNamespaceLister { - return stepActionNamespaceLister{indexer: s.indexer, namespace: namespace} + return stepActionNamespaceLister{listers.NewNamespaced[*pipelinev1alpha1.StepAction](s.ResourceIndexer, namespace)} } // StepActionNamespaceLister helps list and get StepActions. @@ -64,36 +56,15 @@ func (s *stepActionLister) StepActions(namespace string) StepActionNamespaceList type StepActionNamespaceLister interface { // List lists all StepActions in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.StepAction, err error) + List(selector labels.Selector) (ret []*pipelinev1alpha1.StepAction, err error) // Get retrieves the StepAction from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.StepAction, error) + Get(name string) (*pipelinev1alpha1.StepAction, error) StepActionNamespaceListerExpansion } // stepActionNamespaceLister implements the StepActionNamespaceLister // interface. type stepActionNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all StepActions in the indexer for a given namespace. -func (s stepActionNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.StepAction, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.StepAction)) - }) - return ret, err -} - -// Get retrieves the StepAction from the indexer for a given namespace and name. -func (s stepActionNamespaceLister) Get(name string) (*v1alpha1.StepAction, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("stepaction"), name) - } - return obj.(*v1alpha1.StepAction), nil + listers.ResourceIndexer[*pipelinev1alpha1.StepAction] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/verificationpolicy.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/verificationpolicy.go index 7682fa51..989ebfe2 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/verificationpolicy.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1/verificationpolicy.go @@ -19,10 +19,10 @@ limitations under the License. package v1alpha1 import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // VerificationPolicyLister helps list VerificationPolicies. @@ -30,7 +30,7 @@ import ( type VerificationPolicyLister interface { // List lists all VerificationPolicies in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.VerificationPolicy, err error) + List(selector labels.Selector) (ret []*pipelinev1alpha1.VerificationPolicy, err error) // VerificationPolicies returns an object that can list and get VerificationPolicies. VerificationPolicies(namespace string) VerificationPolicyNamespaceLister VerificationPolicyListerExpansion @@ -38,25 +38,17 @@ type VerificationPolicyLister interface { // verificationPolicyLister implements the VerificationPolicyLister interface. type verificationPolicyLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1alpha1.VerificationPolicy] } // NewVerificationPolicyLister returns a new VerificationPolicyLister. func NewVerificationPolicyLister(indexer cache.Indexer) VerificationPolicyLister { - return &verificationPolicyLister{indexer: indexer} -} - -// List lists all VerificationPolicies in the indexer. -func (s *verificationPolicyLister) List(selector labels.Selector) (ret []*v1alpha1.VerificationPolicy, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.VerificationPolicy)) - }) - return ret, err + return &verificationPolicyLister{listers.New[*pipelinev1alpha1.VerificationPolicy](indexer, pipelinev1alpha1.Resource("verificationpolicy"))} } // VerificationPolicies returns an object that can list and get VerificationPolicies. func (s *verificationPolicyLister) VerificationPolicies(namespace string) VerificationPolicyNamespaceLister { - return verificationPolicyNamespaceLister{indexer: s.indexer, namespace: namespace} + return verificationPolicyNamespaceLister{listers.NewNamespaced[*pipelinev1alpha1.VerificationPolicy](s.ResourceIndexer, namespace)} } // VerificationPolicyNamespaceLister helps list and get VerificationPolicies. @@ -64,36 +56,15 @@ func (s *verificationPolicyLister) VerificationPolicies(namespace string) Verifi type VerificationPolicyNamespaceLister interface { // List lists all VerificationPolicies in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.VerificationPolicy, err error) + List(selector labels.Selector) (ret []*pipelinev1alpha1.VerificationPolicy, err error) // Get retrieves the VerificationPolicy from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.VerificationPolicy, error) + Get(name string) (*pipelinev1alpha1.VerificationPolicy, error) VerificationPolicyNamespaceListerExpansion } // verificationPolicyNamespaceLister implements the VerificationPolicyNamespaceLister // interface. type verificationPolicyNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all VerificationPolicies in the indexer for a given namespace. -func (s verificationPolicyNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.VerificationPolicy, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.VerificationPolicy)) - }) - return ret, err -} - -// Get retrieves the VerificationPolicy from the indexer for a given namespace and name. -func (s verificationPolicyNamespaceLister) Get(name string) (*v1alpha1.VerificationPolicy, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("verificationpolicy"), name) - } - return obj.(*v1alpha1.VerificationPolicy), nil + listers.ResourceIndexer[*pipelinev1alpha1.VerificationPolicy] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/clustertask.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/clustertask.go deleted file mode 100644 index bc88cfb6..00000000 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/clustertask.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2020 The Tekton Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1beta1 - -import ( - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ClusterTaskLister helps list ClusterTasks. -// All objects returned here must be treated as read-only. -type ClusterTaskLister interface { - // List lists all ClusterTasks in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.ClusterTask, err error) - // Get retrieves the ClusterTask from the index for a given name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1beta1.ClusterTask, error) - ClusterTaskListerExpansion -} - -// clusterTaskLister implements the ClusterTaskLister interface. -type clusterTaskLister struct { - indexer cache.Indexer -} - -// NewClusterTaskLister returns a new ClusterTaskLister. -func NewClusterTaskLister(indexer cache.Indexer) ClusterTaskLister { - return &clusterTaskLister{indexer: indexer} -} - -// List lists all ClusterTasks in the indexer. -func (s *clusterTaskLister) List(selector labels.Selector) (ret []*v1beta1.ClusterTask, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.ClusterTask)) - }) - return ret, err -} - -// Get retrieves the ClusterTask from the index for a given name. -func (s *clusterTaskLister) Get(name string) (*v1beta1.ClusterTask, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1beta1.Resource("clustertask"), name) - } - return obj.(*v1beta1.ClusterTask), nil -} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/customrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/customrun.go index 546668a1..eec93672 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/customrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/customrun.go @@ -19,10 +19,10 @@ limitations under the License. package v1beta1 import ( - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // CustomRunLister helps list CustomRuns. @@ -30,7 +30,7 @@ import ( type CustomRunLister interface { // List lists all CustomRuns in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.CustomRun, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.CustomRun, err error) // CustomRuns returns an object that can list and get CustomRuns. CustomRuns(namespace string) CustomRunNamespaceLister CustomRunListerExpansion @@ -38,25 +38,17 @@ type CustomRunLister interface { // customRunLister implements the CustomRunLister interface. type customRunLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1beta1.CustomRun] } // NewCustomRunLister returns a new CustomRunLister. func NewCustomRunLister(indexer cache.Indexer) CustomRunLister { - return &customRunLister{indexer: indexer} -} - -// List lists all CustomRuns in the indexer. -func (s *customRunLister) List(selector labels.Selector) (ret []*v1beta1.CustomRun, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.CustomRun)) - }) - return ret, err + return &customRunLister{listers.New[*pipelinev1beta1.CustomRun](indexer, pipelinev1beta1.Resource("customrun"))} } // CustomRuns returns an object that can list and get CustomRuns. func (s *customRunLister) CustomRuns(namespace string) CustomRunNamespaceLister { - return customRunNamespaceLister{indexer: s.indexer, namespace: namespace} + return customRunNamespaceLister{listers.NewNamespaced[*pipelinev1beta1.CustomRun](s.ResourceIndexer, namespace)} } // CustomRunNamespaceLister helps list and get CustomRuns. @@ -64,36 +56,15 @@ func (s *customRunLister) CustomRuns(namespace string) CustomRunNamespaceLister type CustomRunNamespaceLister interface { // List lists all CustomRuns in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.CustomRun, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.CustomRun, err error) // Get retrieves the CustomRun from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1beta1.CustomRun, error) + Get(name string) (*pipelinev1beta1.CustomRun, error) CustomRunNamespaceListerExpansion } // customRunNamespaceLister implements the CustomRunNamespaceLister // interface. type customRunNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all CustomRuns in the indexer for a given namespace. -func (s customRunNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.CustomRun, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.CustomRun)) - }) - return ret, err -} - -// Get retrieves the CustomRun from the indexer for a given namespace and name. -func (s customRunNamespaceLister) Get(name string) (*v1beta1.CustomRun, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1beta1.Resource("customrun"), name) - } - return obj.(*v1beta1.CustomRun), nil + listers.ResourceIndexer[*pipelinev1beta1.CustomRun] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/expansion_generated.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/expansion_generated.go index 0fe1994d..a48910c9 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/expansion_generated.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/expansion_generated.go @@ -18,10 +18,6 @@ limitations under the License. package v1beta1 -// ClusterTaskListerExpansion allows custom methods to be added to -// ClusterTaskLister. -type ClusterTaskListerExpansion interface{} - // CustomRunListerExpansion allows custom methods to be added to // CustomRunLister. type CustomRunListerExpansion interface{} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipeline.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipeline.go index cd85d324..5231808b 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipeline.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipeline.go @@ -19,10 +19,10 @@ limitations under the License. package v1beta1 import ( - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // PipelineLister helps list Pipelines. @@ -30,7 +30,7 @@ import ( type PipelineLister interface { // List lists all Pipelines in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.Pipeline, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.Pipeline, err error) // Pipelines returns an object that can list and get Pipelines. Pipelines(namespace string) PipelineNamespaceLister PipelineListerExpansion @@ -38,25 +38,17 @@ type PipelineLister interface { // pipelineLister implements the PipelineLister interface. type pipelineLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1beta1.Pipeline] } // NewPipelineLister returns a new PipelineLister. func NewPipelineLister(indexer cache.Indexer) PipelineLister { - return &pipelineLister{indexer: indexer} -} - -// List lists all Pipelines in the indexer. -func (s *pipelineLister) List(selector labels.Selector) (ret []*v1beta1.Pipeline, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.Pipeline)) - }) - return ret, err + return &pipelineLister{listers.New[*pipelinev1beta1.Pipeline](indexer, pipelinev1beta1.Resource("pipeline"))} } // Pipelines returns an object that can list and get Pipelines. func (s *pipelineLister) Pipelines(namespace string) PipelineNamespaceLister { - return pipelineNamespaceLister{indexer: s.indexer, namespace: namespace} + return pipelineNamespaceLister{listers.NewNamespaced[*pipelinev1beta1.Pipeline](s.ResourceIndexer, namespace)} } // PipelineNamespaceLister helps list and get Pipelines. @@ -64,36 +56,15 @@ func (s *pipelineLister) Pipelines(namespace string) PipelineNamespaceLister { type PipelineNamespaceLister interface { // List lists all Pipelines in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.Pipeline, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.Pipeline, err error) // Get retrieves the Pipeline from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1beta1.Pipeline, error) + Get(name string) (*pipelinev1beta1.Pipeline, error) PipelineNamespaceListerExpansion } // pipelineNamespaceLister implements the PipelineNamespaceLister // interface. type pipelineNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Pipelines in the indexer for a given namespace. -func (s pipelineNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Pipeline, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.Pipeline)) - }) - return ret, err -} - -// Get retrieves the Pipeline from the indexer for a given namespace and name. -func (s pipelineNamespaceLister) Get(name string) (*v1beta1.Pipeline, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1beta1.Resource("pipeline"), name) - } - return obj.(*v1beta1.Pipeline), nil + listers.ResourceIndexer[*pipelinev1beta1.Pipeline] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipelinerun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipelinerun.go index 31b7ebb9..8c14cb07 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipelinerun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/pipelinerun.go @@ -19,10 +19,10 @@ limitations under the License. package v1beta1 import ( - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // PipelineRunLister helps list PipelineRuns. @@ -30,7 +30,7 @@ import ( type PipelineRunLister interface { // List lists all PipelineRuns in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.PipelineRun, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.PipelineRun, err error) // PipelineRuns returns an object that can list and get PipelineRuns. PipelineRuns(namespace string) PipelineRunNamespaceLister PipelineRunListerExpansion @@ -38,25 +38,17 @@ type PipelineRunLister interface { // pipelineRunLister implements the PipelineRunLister interface. type pipelineRunLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1beta1.PipelineRun] } // NewPipelineRunLister returns a new PipelineRunLister. func NewPipelineRunLister(indexer cache.Indexer) PipelineRunLister { - return &pipelineRunLister{indexer: indexer} -} - -// List lists all PipelineRuns in the indexer. -func (s *pipelineRunLister) List(selector labels.Selector) (ret []*v1beta1.PipelineRun, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.PipelineRun)) - }) - return ret, err + return &pipelineRunLister{listers.New[*pipelinev1beta1.PipelineRun](indexer, pipelinev1beta1.Resource("pipelinerun"))} } // PipelineRuns returns an object that can list and get PipelineRuns. func (s *pipelineRunLister) PipelineRuns(namespace string) PipelineRunNamespaceLister { - return pipelineRunNamespaceLister{indexer: s.indexer, namespace: namespace} + return pipelineRunNamespaceLister{listers.NewNamespaced[*pipelinev1beta1.PipelineRun](s.ResourceIndexer, namespace)} } // PipelineRunNamespaceLister helps list and get PipelineRuns. @@ -64,36 +56,15 @@ func (s *pipelineRunLister) PipelineRuns(namespace string) PipelineRunNamespaceL type PipelineRunNamespaceLister interface { // List lists all PipelineRuns in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.PipelineRun, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.PipelineRun, err error) // Get retrieves the PipelineRun from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1beta1.PipelineRun, error) + Get(name string) (*pipelinev1beta1.PipelineRun, error) PipelineRunNamespaceListerExpansion } // pipelineRunNamespaceLister implements the PipelineRunNamespaceLister // interface. type pipelineRunNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all PipelineRuns in the indexer for a given namespace. -func (s pipelineRunNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.PipelineRun, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.PipelineRun)) - }) - return ret, err -} - -// Get retrieves the PipelineRun from the indexer for a given namespace and name. -func (s pipelineRunNamespaceLister) Get(name string) (*v1beta1.PipelineRun, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1beta1.Resource("pipelinerun"), name) - } - return obj.(*v1beta1.PipelineRun), nil + listers.ResourceIndexer[*pipelinev1beta1.PipelineRun] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/stepaction.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/stepaction.go index 19257382..ed88bd2b 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/stepaction.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/stepaction.go @@ -19,10 +19,10 @@ limitations under the License. package v1beta1 import ( - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // StepActionLister helps list StepActions. @@ -30,7 +30,7 @@ import ( type StepActionLister interface { // List lists all StepActions in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.StepAction, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.StepAction, err error) // StepActions returns an object that can list and get StepActions. StepActions(namespace string) StepActionNamespaceLister StepActionListerExpansion @@ -38,25 +38,17 @@ type StepActionLister interface { // stepActionLister implements the StepActionLister interface. type stepActionLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1beta1.StepAction] } // NewStepActionLister returns a new StepActionLister. func NewStepActionLister(indexer cache.Indexer) StepActionLister { - return &stepActionLister{indexer: indexer} -} - -// List lists all StepActions in the indexer. -func (s *stepActionLister) List(selector labels.Selector) (ret []*v1beta1.StepAction, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.StepAction)) - }) - return ret, err + return &stepActionLister{listers.New[*pipelinev1beta1.StepAction](indexer, pipelinev1beta1.Resource("stepaction"))} } // StepActions returns an object that can list and get StepActions. func (s *stepActionLister) StepActions(namespace string) StepActionNamespaceLister { - return stepActionNamespaceLister{indexer: s.indexer, namespace: namespace} + return stepActionNamespaceLister{listers.NewNamespaced[*pipelinev1beta1.StepAction](s.ResourceIndexer, namespace)} } // StepActionNamespaceLister helps list and get StepActions. @@ -64,36 +56,15 @@ func (s *stepActionLister) StepActions(namespace string) StepActionNamespaceList type StepActionNamespaceLister interface { // List lists all StepActions in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.StepAction, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.StepAction, err error) // Get retrieves the StepAction from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1beta1.StepAction, error) + Get(name string) (*pipelinev1beta1.StepAction, error) StepActionNamespaceListerExpansion } // stepActionNamespaceLister implements the StepActionNamespaceLister // interface. type stepActionNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all StepActions in the indexer for a given namespace. -func (s stepActionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.StepAction, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.StepAction)) - }) - return ret, err -} - -// Get retrieves the StepAction from the indexer for a given namespace and name. -func (s stepActionNamespaceLister) Get(name string) (*v1beta1.StepAction, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1beta1.Resource("stepaction"), name) - } - return obj.(*v1beta1.StepAction), nil + listers.ResourceIndexer[*pipelinev1beta1.StepAction] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/task.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/task.go index b13ba17e..766b74f0 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/task.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/task.go @@ -19,10 +19,10 @@ limitations under the License. package v1beta1 import ( - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // TaskLister helps list Tasks. @@ -30,7 +30,7 @@ import ( type TaskLister interface { // List lists all Tasks in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.Task, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.Task, err error) // Tasks returns an object that can list and get Tasks. Tasks(namespace string) TaskNamespaceLister TaskListerExpansion @@ -38,25 +38,17 @@ type TaskLister interface { // taskLister implements the TaskLister interface. type taskLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1beta1.Task] } // NewTaskLister returns a new TaskLister. func NewTaskLister(indexer cache.Indexer) TaskLister { - return &taskLister{indexer: indexer} -} - -// List lists all Tasks in the indexer. -func (s *taskLister) List(selector labels.Selector) (ret []*v1beta1.Task, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.Task)) - }) - return ret, err + return &taskLister{listers.New[*pipelinev1beta1.Task](indexer, pipelinev1beta1.Resource("task"))} } // Tasks returns an object that can list and get Tasks. func (s *taskLister) Tasks(namespace string) TaskNamespaceLister { - return taskNamespaceLister{indexer: s.indexer, namespace: namespace} + return taskNamespaceLister{listers.NewNamespaced[*pipelinev1beta1.Task](s.ResourceIndexer, namespace)} } // TaskNamespaceLister helps list and get Tasks. @@ -64,36 +56,15 @@ func (s *taskLister) Tasks(namespace string) TaskNamespaceLister { type TaskNamespaceLister interface { // List lists all Tasks in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.Task, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.Task, err error) // Get retrieves the Task from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1beta1.Task, error) + Get(name string) (*pipelinev1beta1.Task, error) TaskNamespaceListerExpansion } // taskNamespaceLister implements the TaskNamespaceLister // interface. type taskNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Tasks in the indexer for a given namespace. -func (s taskNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Task, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.Task)) - }) - return ret, err -} - -// Get retrieves the Task from the indexer for a given namespace and name. -func (s taskNamespaceLister) Get(name string) (*v1beta1.Task, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1beta1.Resource("task"), name) - } - return obj.(*v1beta1.Task), nil + listers.ResourceIndexer[*pipelinev1beta1.Task] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/taskrun.go b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/taskrun.go index 310c3700..24b534d3 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/taskrun.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1/taskrun.go @@ -19,10 +19,10 @@ limitations under the License. package v1beta1 import ( - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" + pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" ) // TaskRunLister helps list TaskRuns. @@ -30,7 +30,7 @@ import ( type TaskRunLister interface { // List lists all TaskRuns in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.TaskRun, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.TaskRun, err error) // TaskRuns returns an object that can list and get TaskRuns. TaskRuns(namespace string) TaskRunNamespaceLister TaskRunListerExpansion @@ -38,25 +38,17 @@ type TaskRunLister interface { // taskRunLister implements the TaskRunLister interface. type taskRunLister struct { - indexer cache.Indexer + listers.ResourceIndexer[*pipelinev1beta1.TaskRun] } // NewTaskRunLister returns a new TaskRunLister. func NewTaskRunLister(indexer cache.Indexer) TaskRunLister { - return &taskRunLister{indexer: indexer} -} - -// List lists all TaskRuns in the indexer. -func (s *taskRunLister) List(selector labels.Selector) (ret []*v1beta1.TaskRun, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.TaskRun)) - }) - return ret, err + return &taskRunLister{listers.New[*pipelinev1beta1.TaskRun](indexer, pipelinev1beta1.Resource("taskrun"))} } // TaskRuns returns an object that can list and get TaskRuns. func (s *taskRunLister) TaskRuns(namespace string) TaskRunNamespaceLister { - return taskRunNamespaceLister{indexer: s.indexer, namespace: namespace} + return taskRunNamespaceLister{listers.NewNamespaced[*pipelinev1beta1.TaskRun](s.ResourceIndexer, namespace)} } // TaskRunNamespaceLister helps list and get TaskRuns. @@ -64,36 +56,15 @@ func (s *taskRunLister) TaskRuns(namespace string) TaskRunNamespaceLister { type TaskRunNamespaceLister interface { // List lists all TaskRuns in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1beta1.TaskRun, err error) + List(selector labels.Selector) (ret []*pipelinev1beta1.TaskRun, err error) // Get retrieves the TaskRun from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1beta1.TaskRun, error) + Get(name string) (*pipelinev1beta1.TaskRun, error) TaskRunNamespaceListerExpansion } // taskRunNamespaceLister implements the TaskRunNamespaceLister // interface. type taskRunNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all TaskRuns in the indexer for a given namespace. -func (s taskRunNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.TaskRun, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.TaskRun)) - }) - return ret, err -} - -// Get retrieves the TaskRun from the indexer for a given namespace and name. -func (s taskRunNamespaceLister) Get(name string) (*v1beta1.TaskRun, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1beta1.Resource("taskrun"), name) - } - return obj.(*v1beta1.TaskRun), nil + listers.ResourceIndexer[*pipelinev1beta1.TaskRun] } diff --git a/vendor/github.com/tektoncd/pipeline/pkg/result/result.go b/vendor/github.com/tektoncd/pipeline/pkg/result/result.go index 6506074f..2857ccf2 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/result/result.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/result/result.go @@ -18,9 +18,8 @@ package result import ( "encoding/json" + "errors" "fmt" - - "github.com/hashicorp/go-multierror" ) const ( @@ -84,7 +83,7 @@ func (r *ResultType) UnmarshalJSON(data []byte) error { var asString string if err := json.Unmarshal(data, &asString); err != nil { - return fmt.Errorf("unsupported value type, neither int nor string: %w", multierror.Append(intErr, err).ErrorOrNil()) + return fmt.Errorf("unsupported value type, neither int nor string: %w", errors.Join(intErr, err)) } switch asString { diff --git a/vendor/github.com/tektoncd/pipeline/pkg/substitution/replacements.go b/vendor/github.com/tektoncd/pipeline/pkg/substitution/replacements.go new file mode 100644 index 00000000..ace13376 --- /dev/null +++ b/vendor/github.com/tektoncd/pipeline/pkg/substitution/replacements.go @@ -0,0 +1,61 @@ +/* +Copyright 2025 The Tekton Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package substitution + +import ( + "fmt" + "strings" +) + +// ApplyReplacements returns a string with references to parameters replaced, +// based on the mapping provided in replacements. +// For example, if the input string is "foo: $(params.foo)", and replacements maps "params.foo" to "bar", +// the output would be "foo: bar". +func ApplyReplacements(in string, replacements map[string]string) string { + replacementsList := []string{} + for k, v := range replacements { + replacementsList = append(replacementsList, fmt.Sprintf("$(%s)", k), v) + } + // strings.Replacer does all replacements in one pass, preventing multiple replacements + // See #2093 for an explanation on why we need to do this. + replacer := strings.NewReplacer(replacementsList...) + return replacer.Replace(in) +} + +// ApplyArrayReplacements takes an input string, and output an array of strings related to possible arrayReplacements. If there aren't any +// areas where the input can be split up via arrayReplacements, then just return an array with a single element, +// which is ApplyReplacements(in, replacements). +func ApplyArrayReplacements(in string, stringReplacements map[string]string, arrayReplacements map[string][]string) []string { + for k, v := range arrayReplacements { + stringToReplace := fmt.Sprintf("$(%s)", k) + + // If the input string matches a replacement's key (without padding characters), return the corresponding array. + // Note that the webhook should prevent all instances where this could evaluate to false. + if (strings.Count(in, stringToReplace) == 1) && len(in) == len(stringToReplace) { + return v + } + + // same replace logic for star array expressions + starStringtoReplace := fmt.Sprintf("$(%s[*])", k) + if (strings.Count(in, starStringtoReplace) == 1) && len(in) == len(starStringtoReplace) { + return v + } + } + + // Otherwise return a size-1 array containing the input string with standard stringReplacements applied. + return []string{ApplyReplacements(in, stringReplacements)} +} diff --git a/vendor/github.com/tektoncd/pipeline/pkg/substitution/substitution.go b/vendor/github.com/tektoncd/pipeline/pkg/substitution/substitution.go index 8e1acab2..78a17b8f 100644 --- a/vendor/github.com/tektoncd/pipeline/pkg/substitution/substitution.go +++ b/vendor/github.com/tektoncd/pipeline/pkg/substitution/substitution.go @@ -1,3 +1,5 @@ +//go:build !disable_tls + /* Copyright 2019 The Tekton Authors @@ -54,6 +56,16 @@ var intIndexRegex = regexp.MustCompile(intIndex) // - prefix: the prefix of the substitutable variable, e.g. "params" or "context.pipeline" // - vars: names of known variables func ValidateNoReferencesToUnknownVariables(value, prefix string, vars sets.String) *apis.FieldError { + return validateNoReferencesToUnknownVariables(value, prefix, vars, false) +} + +// ValidateNoReferencesToUnknownVariablesWithDetail same as ValidateNoReferencesToUnknownVariables +// but with more prefix detailed error message +func ValidateNoReferencesToUnknownVariablesWithDetail(value, prefix string, vars sets.String) *apis.FieldError { + return validateNoReferencesToUnknownVariables(value, prefix, vars, true) +} + +func validateNoReferencesToUnknownVariables(value, prefix string, vars sets.String, withDetail bool) *apis.FieldError { if vs, present, errString := ExtractVariablesFromString(value, prefix); present { if errString != "" { return &apis.FieldError{ @@ -64,8 +76,14 @@ func ValidateNoReferencesToUnknownVariables(value, prefix string, vars sets.Stri for _, v := range vs { v = TrimArrayIndex(v) if !vars.Has(v) { + var msg string + if withDetail { + msg = fmt.Sprintf("non-existent variable `%s` in %q", v, value) + } else { + msg = fmt.Sprintf("non-existent variable in %q", value) + } return &apis.FieldError{ - Message: fmt.Sprintf("non-existent variable in %q", value), + Message: msg, // Empty path is required to make the `ViaField`, … work Paths: []string{""}, } @@ -290,45 +308,6 @@ func matchGroups(matches []string, pattern *regexp.Regexp) map[string]string { return groups } -// ApplyReplacements returns a string with references to parameters replaced, -// based on the mapping provided in replacements. -// For example, if the input string is "foo: $(params.foo)", and replacements maps "params.foo" to "bar", -// the output would be "foo: bar". -func ApplyReplacements(in string, replacements map[string]string) string { - replacementsList := []string{} - for k, v := range replacements { - replacementsList = append(replacementsList, fmt.Sprintf("$(%s)", k), v) - } - // strings.Replacer does all replacements in one pass, preventing multiple replacements - // See #2093 for an explanation on why we need to do this. - replacer := strings.NewReplacer(replacementsList...) - return replacer.Replace(in) -} - -// ApplyArrayReplacements takes an input string, and output an array of strings related to possible arrayReplacements. If there aren't any -// areas where the input can be split up via arrayReplacements, then just return an array with a single element, -// which is ApplyReplacements(in, replacements). -func ApplyArrayReplacements(in string, stringReplacements map[string]string, arrayReplacements map[string][]string) []string { - for k, v := range arrayReplacements { - stringToReplace := fmt.Sprintf("$(%s)", k) - - // If the input string matches a replacement's key (without padding characters), return the corresponding array. - // Note that the webhook should prevent all instances where this could evaluate to false. - if (strings.Count(in, stringToReplace) == 1) && len(in) == len(stringToReplace) { - return v - } - - // same replace logic for star array expressions - starStringtoReplace := fmt.Sprintf("$(%s[*])", k) - if (strings.Count(in, starStringtoReplace) == 1) && len(in) == len(starStringtoReplace) { - return v - } - } - - // Otherwise return a size-1 array containing the input string with standard stringReplacements applied. - return []string{ApplyReplacements(in, stringReplacements)} -} - // TrimArrayIndex replaces all `[i]` and `[*]` to "". func TrimArrayIndex(s string) string { return arrayIndexingRegex.ReplaceAllString(s, "") diff --git a/vendor/golang.org/x/exp/maps/maps.go b/vendor/golang.org/x/exp/maps/maps.go deleted file mode 100644 index 4a9747ef..00000000 --- a/vendor/golang.org/x/exp/maps/maps.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package maps defines various functions useful with maps of any type. -package maps - -import "maps" - -// Keys returns the keys of the map m. -// The keys will be in an indeterminate order. -// -// The simplest true equivalent using the standard library is: -// -// slices.AppendSeq(make([]K, 0, len(m)), maps.Keys(m)) -func Keys[M ~map[K]V, K comparable, V any](m M) []K { - - r := make([]K, 0, len(m)) - for k := range m { - r = append(r, k) - } - return r -} - -// Values returns the values of the map m. -// The values will be in an indeterminate order. -// -// The simplest true equivalent using the standard library is: -// -// slices.AppendSeq(make([]V, 0, len(m)), maps.Values(m)) -func Values[M ~map[K]V, K comparable, V any](m M) []V { - - r := make([]V, 0, len(m)) - for _, v := range m { - r = append(r, v) - } - return r -} - -// Equal reports whether two maps contain the same key/value pairs. -// Values are compared using ==. -// -//go:fix inline -func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool { - return maps.Equal(m1, m2) -} - -// EqualFunc is like Equal, but compares values using eq. -// Keys are still compared with ==. -// -//go:fix inline -func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool { - return maps.EqualFunc(m1, m2, eq) -} - -// Clear removes all entries from m, leaving it empty. -// -//go:fix inline -func Clear[M ~map[K]V, K comparable, V any](m M) { - clear(m) -} - -// Clone returns a copy of m. This is a shallow clone: -// the new keys and values are set using ordinary assignment. -// -//go:fix inline -func Clone[M ~map[K]V, K comparable, V any](m M) M { - return maps.Clone(m) -} - -// Copy copies all key/value pairs in src adding them to dst. -// When a key in src is already present in dst, -// the value in dst will be overwritten by the value associated -// with the key in src. -// -//go:fix inline -func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) { - maps.Copy(dst, src) -} - -// DeleteFunc deletes any key/value pairs from m for which del returns true. -// -//go:fix inline -func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) { - maps.DeleteFunc(m, del) -} diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go index ec5f0cdd..794b2e32 100644 --- a/vendor/golang.org/x/time/rate/rate.go +++ b/vendor/golang.org/x/time/rate/rate.go @@ -85,7 +85,7 @@ func (lim *Limiter) Burst() int { // TokensAt returns the number of tokens available at time t. func (lim *Limiter) TokensAt(t time.Time) float64 { lim.mu.Lock() - _, tokens := lim.advance(t) // does not mutate lim + tokens := lim.advance(t) // does not mutate lim lim.mu.Unlock() return tokens } @@ -186,7 +186,7 @@ func (r *Reservation) CancelAt(t time.Time) { return } // advance time to now - t, tokens := r.lim.advance(t) + tokens := r.lim.advance(t) // calculate new number of tokens tokens += restoreTokens if burst := float64(r.lim.burst); tokens > burst { @@ -307,7 +307,7 @@ func (lim *Limiter) SetLimitAt(t time.Time, newLimit Limit) { lim.mu.Lock() defer lim.mu.Unlock() - t, tokens := lim.advance(t) + tokens := lim.advance(t) lim.last = t lim.tokens = tokens @@ -324,7 +324,7 @@ func (lim *Limiter) SetBurstAt(t time.Time, newBurst int) { lim.mu.Lock() defer lim.mu.Unlock() - t, tokens := lim.advance(t) + tokens := lim.advance(t) lim.last = t lim.tokens = tokens @@ -347,7 +347,7 @@ func (lim *Limiter) reserveN(t time.Time, n int, maxFutureReserve time.Duration) } } - t, tokens := lim.advance(t) + tokens := lim.advance(t) // Calculate the remaining number of tokens resulting from the request. tokens -= float64(n) @@ -380,10 +380,11 @@ func (lim *Limiter) reserveN(t time.Time, n int, maxFutureReserve time.Duration) return r } -// advance calculates and returns an updated state for lim resulting from the passage of time. +// advance calculates and returns an updated number of tokens for lim +// resulting from the passage of time. // lim is not changed. // advance requires that lim.mu is held. -func (lim *Limiter) advance(t time.Time) (newT time.Time, newTokens float64) { +func (lim *Limiter) advance(t time.Time) (newTokens float64) { last := lim.last if t.Before(last) { last = t @@ -396,7 +397,7 @@ func (lim *Limiter) advance(t time.Time) (newT time.Time, newTokens float64) { if burst := float64(lim.burst); tokens > burst { tokens = burst } - return t, tokens + return tokens } // durationFromTokens is a unit conversion function from the number of tokens to the duration diff --git a/vendor/golang.org/x/time/rate/sometimes.go b/vendor/golang.org/x/time/rate/sometimes.go index 6ba99ddb..9b839326 100644 --- a/vendor/golang.org/x/time/rate/sometimes.go +++ b/vendor/golang.org/x/time/rate/sometimes.go @@ -61,7 +61,9 @@ func (s *Sometimes) Do(f func()) { (s.Every > 0 && s.count%s.Every == 0) || (s.Interval > 0 && time.Since(s.last) >= s.Interval) { f() - s.last = time.Now() + if s.Interval > 0 { + s.last = time.Now() + } } s.count++ } diff --git a/vendor/modules.txt b/vendor/modules.txt index 31cf7b5b..4230a317 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -105,8 +105,8 @@ github.com/golang/groupcache/lru # github.com/golang/protobuf v1.5.4 ## explicit; go 1.17 github.com/golang/protobuf/ptypes/timestamp -# github.com/google/cel-go v0.23.2 -## explicit; go 1.21.1 +# github.com/google/cel-go v0.26.0 +## explicit; go 1.22.0 github.com/google/cel-go/cel github.com/google/cel-go/checker github.com/google/cel-go/checker/decls @@ -115,6 +115,7 @@ github.com/google/cel-go/common/ast github.com/google/cel-go/common/containers github.com/google/cel-go/common/debug github.com/google/cel-go/common/decls +github.com/google/cel-go/common/env github.com/google/cel-go/common/functions github.com/google/cel-go/common/operators github.com/google/cel-go/common/overloads @@ -177,12 +178,6 @@ github.com/grafana/regexp github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/runtime github.com/grpc-ecosystem/grpc-gateway/v2/utilities -# github.com/hashicorp/errwrap v1.1.0 -## explicit -github.com/hashicorp/errwrap -# github.com/hashicorp/go-multierror v1.1.1 -## explicit; go 1.13 -github.com/hashicorp/go-multierror # github.com/hashicorp/golang-lru v1.0.2 ## explicit; go 1.12 github.com/hashicorp/golang-lru @@ -233,7 +228,7 @@ github.com/opencontainers/image-spec/specs-go/v1 # github.com/pkg/errors v0.9.1 ## explicit github.com/pkg/errors -# github.com/pmezard/go-difflib v1.0.0 +# github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 ## explicit github.com/pmezard/go-difflib/difflib # github.com/prometheus/client_golang v1.23.0 @@ -277,8 +272,8 @@ github.com/stoewer/go-strcase ## explicit; go 1.17 github.com/stretchr/testify/assert github.com/stretchr/testify/assert/yaml -# github.com/tektoncd/pipeline v0.66.0 -## explicit; go 1.22 +# github.com/tektoncd/pipeline v1.3.1 +## explicit; go 1.24.0 github.com/tektoncd/pipeline/internal/artifactref github.com/tektoncd/pipeline/pkg/apis/config github.com/tektoncd/pipeline/pkg/apis/pipeline @@ -485,7 +480,6 @@ go.uber.org/zap/zaptest go.yaml.in/yaml/v2 # golang.org/x/exp v0.0.0-20250808145144-a408d31f581a ## explicit; go 1.23.0 -golang.org/x/exp/maps golang.org/x/exp/slices # golang.org/x/mod v0.27.0 ## explicit; go 1.23.0 @@ -531,8 +525,8 @@ golang.org/x/text/secure/bidirule golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -# golang.org/x/time v0.10.0 -## explicit; go 1.18 +# golang.org/x/time v0.12.0 +## explicit; go 1.23.0 golang.org/x/time/rate # golang.org/x/tools v0.36.0 ## explicit; go 1.23.0 @@ -561,8 +555,8 @@ golang.org/x/tools/internal/versions # gomodules.xyz/jsonpatch/v2 v2.5.0 ## explicit; go 1.20 gomodules.xyz/jsonpatch/v2 -# google.golang.org/api v0.183.0 -## explicit; go 1.20 +# google.golang.org/api v0.233.0 +## explicit; go 1.23.0 google.golang.org/api/support/bundler # google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b ## explicit; go 1.23.0