diff --git a/.codecov.yaml b/.codecov.yaml index 5dedc7d44b..4d3483522a 100644 --- a/.codecov.yaml +++ b/.codecov.yaml @@ -21,5 +21,3 @@ ignore: - "hack" - "pkg/client" - "test" - - "third_party" - - "vendor" diff --git a/.ko.yaml b/.ko.yaml index ddbf8102f3..999fbeadff 100644 --- a/.ko.yaml +++ b/.ko.yaml @@ -5,6 +5,6 @@ builds: - id: knative.dev/client/cmd/kn main: ./cmd/kn ldflags: - - -X knative.dev/client/pkg/kn/commands/version.Version={{.Env.KN_BUILD_VERSION}} - - -X knative.dev/client/pkg/kn/commands/version.GitRevision={{.Env.KN_BUILD_GITREV}} - - -X 'knative.dev/client/pkg/kn/commands/version.BuildDate={{.Env.KN_BUILD_DATE}}' + - -X knative.dev/client/pkg/commands/version.Version={{.Env.KN_BUILD_VERSION}} + - -X knative.dev/client/pkg/commands/version.GitRevision={{.Env.KN_BUILD_GITREV}} + - -X 'knative.dev/client/pkg/commands/version.BuildDate={{.Env.KN_BUILD_DATE}}' diff --git a/cmd/kn/main.go b/cmd/kn/main.go index c88980fba7..e8b93f5211 100644 --- a/cmd/kn/main.go +++ b/cmd/kn/main.go @@ -22,9 +22,9 @@ import ( "strings" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/config" - pluginpkg "knative.dev/client/pkg/kn/plugin" - "knative.dev/client/pkg/kn/root" + "knative.dev/client/pkg/config" + pluginpkg "knative.dev/client/pkg/plugin" + "knative.dev/client/pkg/root" ) func main() { diff --git a/cmd/kn/main_test.go b/cmd/kn/main_test.go index 3b016fc79b..2cdf7252f7 100644 --- a/cmd/kn/main_test.go +++ b/cmd/kn/main_test.go @@ -21,15 +21,15 @@ import ( "strings" "testing" - pluginpkg "knative.dev/client/pkg/kn/plugin" + pluginpkg "knative.dev/client/pkg/plugin" "github.com/spf13/cobra" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/kn/config" - "knative.dev/client/pkg/kn/root" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" + "knative.dev/client/pkg/config" + "knative.dev/client/pkg/root" ) func TestValidatePlugin(t *testing.T) { diff --git a/docs/dev/developer-guide.md b/docs/dev/developer-guide.md index 872ed13d1a..98e895a64b 100644 --- a/docs/dev/developer-guide.md +++ b/docs/dev/developer-guide.md @@ -23,7 +23,7 @@ Let's talk now about the three phases separately. ### Bootstrap -The bootstrap performed by [config.BootstrapConfig()](https://github.com/knative/client/blob/0063a263d121702432c1ee71cef30df375a40e76/pkg/kn/config/config.go#L94) extracts all the options relevant for config file detection and plugin configuration. +The bootstrap performed by [config.BootstrapConfig()](https://github.com/knative/client/blob/0063a263d121702432c1ee71cef30df375a40e76/pkg/config/config.go#L94) extracts all the options relevant for config file detection and plugin configuration. The bootstrap process does not fully parse all arguments but only those that are relevant for starting up and for looking up any plugin. The configuration can be either provided via a `--config` flag or is picked up from a default location. The default configuration location conforms to the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) and is different for Unix systems and Windows systems. @@ -33,7 +33,7 @@ The default configuration location conforms to the [XDG Base Directory Specifica ### Plugin Lookup In the next step, a `PluginManager` checks whether the given command-line arguments are pointing to a plugin. -All non-flag arguments are extracted and then used to lookup via [plugin.PluginManager.FindPlugin()](https://github.com/knative/client/blob/0063a263d121702432c1ee71cef30df375a40e76/pkg/kn/plugin/manager.go#L94) in the plugin directory (and the execution `$PATH` if configured) calculated in the _Bootstrap_ phase. +All non-flag arguments are extracted and then used to lookup via [plugin.PluginManager.FindPlugin()](https://github.com/knative/client/blob/0063a263d121702432c1ee71cef30df375a40e76/pkg/plugin/manager.go#L94) in the plugin directory (and the execution `$PATH` if configured) calculated in the _Bootstrap_ phase. ### Execution @@ -127,7 +127,7 @@ Some of them might end up in the public API, too. ## Plugins -You can find the central plugin handling in the package `pkg/kn/plugin`. +You can find the central plugin handling in the package `pkg/plugin`. The entry point here is the `PluginManager`, which is responsible for finding plugins by name and for listing all visible plugins. An interface `Plugin` describes a plugin. This interface has currently a single implementation that uses an `exec` system call to run an external plugin command following a naming convention. diff --git a/docs/plugins/README.md b/docs/plugins/README.md index e70c812757..93713903a7 100644 --- a/docs/plugins/README.md +++ b/docs/plugins/README.md @@ -34,7 +34,7 @@ The following steps are required: package plugin import ( - "knative.dev/client/pkg/kn/plugin" + "knative.dev/client/pkg/plugin" ) func init() { diff --git a/go.mod b/go.mod index d27efa9c9d..46a52c38cc 100644 --- a/go.mod +++ b/go.mod @@ -2,8 +2,12 @@ module knative.dev/client go 1.21 +// TODO: remove when https://github.com/knative/client-pkg/pull/177 is merged +replace knative.dev/client-pkg => github.com/cardil/knative-client-pkg v0.0.0-20240416181347-fe59266c904d +//replace knative.dev/client-pkg => ../knative-client-pkg + require ( - github.com/google/go-cmp v0.6.0 + github.com/google/go-cmp v0.6.0 // indirect github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/mitchellh/go-homedir v1.1.0 @@ -15,11 +19,12 @@ require ( golang.org/x/term v0.18.0 gotest.tools/v3 v3.3.0 k8s.io/api v0.29.2 - k8s.io/apiextensions-apiserver v0.29.2 + k8s.io/apiextensions-apiserver v0.29.2 // indirect k8s.io/apimachinery v0.29.2 k8s.io/cli-runtime v0.29.2 k8s.io/client-go v0.29.2 k8s.io/code-generator v0.29.2 + k8s.io/utils v0.0.0-20240102154912-e7106e64919e knative.dev/client-pkg v0.0.0-20240327121233-6984d81a90ec knative.dev/eventing v0.40.1-0.20240327131403-47543259ceba knative.dev/hack v0.0.0-20240327150553-47368d631660 @@ -29,8 +34,6 @@ require ( sigs.k8s.io/yaml v1.4.0 ) -require k8s.io/utils v0.0.0-20240102154912-e7106e64919e - require ( contrib.go.opencensus.io/exporter/ocagent v0.7.1-0.20200907061046-05415f1de66d // indirect contrib.go.opencensus.io/exporter/prometheus v0.4.2 // indirect diff --git a/go.sum b/go.sum index 2e5d331c6d..93c78c1a6a 100644 --- a/go.sum +++ b/go.sum @@ -59,6 +59,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/blendle/zapdriver v1.3.1 h1:C3dydBOWYRiOk+B8X9IVZ5IOe+7cl+tGOexN4QqHfpE= github.com/blendle/zapdriver v1.3.1/go.mod h1:mdXfREi6u5MArG4j9fewC+FGnXaBR+T4Ox4J2u4eHCc= +github.com/cardil/knative-client-pkg v0.0.0-20240416181347-fe59266c904d h1:WCIfRrazum2AB/ggmNJ3gJAs76c/oO7lQQlQPStx7uQ= +github.com/cardil/knative-client-pkg v0.0.0-20240416181347-fe59266c904d/go.mod h1:dV9nC/iTPeSv8dl3wI2sunXgZJu32A3vlEimNzaEsr0= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.4.1 h1:iKLQ0xPNFxR/2hzXZMrBo8f1j86j5WHzznCCQxV/b8g= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= @@ -839,8 +841,6 @@ k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 h1:aVUu9fTY98ivBPKR9Y5w/A k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00/go.mod h1:AsvuZPBlUDVuCdzJ87iajxtXuR9oktsTctW/R9wwouA= k8s.io/utils v0.0.0-20240102154912-e7106e64919e h1:eQ/4ljkx21sObifjzXwlPKpdGLrCfRziVtos3ofG/sQ= k8s.io/utils v0.0.0-20240102154912-e7106e64919e/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -knative.dev/client-pkg v0.0.0-20240327121233-6984d81a90ec h1:gG8AzUJDHrYONInTv0wm1gSPzWp3n8tooewl+yGpe/I= -knative.dev/client-pkg v0.0.0-20240327121233-6984d81a90ec/go.mod h1:PYodo1bmKTrxnNCfLJa6a8wdg3QQH0XTOPlZJwrY64A= knative.dev/eventing v0.40.1-0.20240327131403-47543259ceba h1:uX9UsYNHJQDpqVSMVijhSljmCSLZm5ocPdQJ4jrkyig= knative.dev/eventing v0.40.1-0.20240327131403-47543259ceba/go.mod h1:19sfPiy4dK2jBIHgszOTk43qOvfCXz1GTIncRY3trB8= knative.dev/hack v0.0.0-20240327150553-47368d631660 h1:tW6NgyjMnSXBS75+k+Xh5uNiLhJ9TFswS9hrkC3OQOc= diff --git a/hack/build-flags.sh b/hack/build-flags.sh index e34d4859b5..d08bfc575d 100644 --- a/hack/build-flags.sh +++ b/hack/build-flags.sh @@ -16,7 +16,7 @@ function build_flags() { local now rev now="$(date -u '+%Y-%m-%d %H:%M:%S')" rev="$(git rev-parse --short HEAD)" - local pkg="knative.dev/client/pkg/kn/commands/version" + local pkg="knative.dev/client/pkg/commands/version" local version="${TAG:-}" # Use vYYYYMMDD-local- for the version string, if not passed. if [[ -z "${version}" ]]; then diff --git a/hack/build.sh b/hack/build.sh index 6c2bead889..c6c02fe774 100755 --- a/hack/build.sh +++ b/hack/build.sh @@ -139,7 +139,7 @@ source_lint() { go_build() { echo "🚧 Compile" # Env var exported by hack/build-flags.sh - go build -mod=vendor -ldflags "${KN_BUILD_LD_FLAGS:-}" -o kn ./cmd/... + go build -ldflags "${KN_BUILD_LD_FLAGS:-}" -o kn ./cmd/... if file kn | grep -q -i "Windows"; then mv kn kn.exe @@ -287,19 +287,19 @@ cross_build() { export CGO_ENABLED=0 echo " 🐧 kn-linux-amd64" - GOOS=linux GOARCH=amd64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-amd64 ./cmd/... || failed=1 + GOOS=linux GOARCH=amd64 go build -ldflags "${ld_flags}" -o ./kn-linux-amd64 ./cmd/... || failed=1 echo " 💪 kn-linux-arm64" - GOOS=linux GOARCH=arm64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-arm64 ./cmd/... || failed=1 + GOOS=linux GOARCH=arm64 go build -ldflags "${ld_flags}" -o ./kn-linux-arm64 ./cmd/... || failed=1 echo " 🍏 kn-darwin-amd64" - GOOS=darwin GOARCH=amd64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-darwin-amd64 ./cmd/... || failed=1 + GOOS=darwin GOARCH=amd64 go build -ldflags "${ld_flags}" -o ./kn-darwin-amd64 ./cmd/... || failed=1 echo " 🍎 kn-darwin-arm64" - GOOS=darwin GOARCH=arm64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-darwin-arm64 ./cmd/... || failed=1 + GOOS=darwin GOARCH=arm64 go build -ldflags "${ld_flags}" -o ./kn-darwin-arm64 ./cmd/... || failed=1 echo " 🎠 kn-windows-amd64.exe" - GOOS=windows GOARCH=amd64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-windows-amd64.exe ./cmd/... || failed=1 + GOOS=windows GOARCH=amd64 go build -ldflags "${ld_flags}" -o ./kn-windows-amd64.exe ./cmd/... || failed=1 echo " Z kn-linux-s390x" - GOOS=linux GOARCH=s390x go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-s390x ./cmd/... || failed=1 + GOOS=linux GOARCH=s390x go build -ldflags "${ld_flags}" -o ./kn-linux-s390x ./cmd/... || failed=1 echo " P kn-linux-ppc64le" - GOOS=linux GOARCH=ppc64le go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-ppc64le ./cmd/... || failed=1 + GOOS=linux GOARCH=ppc64le go build -ldflags "${ld_flags}" -o ./kn-linux-ppc64le ./cmd/... || failed=1 return ${failed} } @@ -368,7 +368,8 @@ if has_flag --debug; then fi # Shared funcs from hack repo -source "$(basedir)"/vendor/knative.dev/hack/library.sh +# shellcheck disable=SC1090 +source "$(go run knative.dev/hack/cmd/script library.sh)" # Shared funcs with CI while IFS= read -r -d '' file; do diff --git a/hack/generate-docs.go b/hack/generate-docs.go index ffa2f37b0d..2d8a4e99de 100644 --- a/hack/generate-docs.go +++ b/hack/generate-docs.go @@ -20,7 +20,7 @@ import ( "os" "github.com/spf13/cobra/doc" - "knative.dev/client/pkg/kn/root" + "knative.dev/client/pkg/root" ) func main() { diff --git a/hack/release.sh b/hack/release.sh index ff7be9aac2..70d100b704 100755 --- a/hack/release.sh +++ b/hack/release.sh @@ -17,7 +17,8 @@ # Documentation about this script and how to use it can be found # at https://github.com/knative/hack -source $(dirname $0)/../vendor/knative.dev/hack/release.sh +# shellcheck disable=SC1090 +source "$(go run knative.dev/hack/cmd/script release.sh)" function build_release() { # Env var exported by hack/build-flags.sh @@ -26,19 +27,19 @@ function build_release() { export CGO_ENABLED=0 echo "🚧 🐧 Building for Linux (amd64)" - GOOS=linux GOARCH=amd64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-amd64 ./cmd/... + GOOS=linux GOARCH=amd64 go build -ldflags "${ld_flags}" -o ./kn-linux-amd64 ./cmd/... echo "🚧 💪 Building for Linux (arm64)" - GOOS=linux GOARCH=arm64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-arm64 ./cmd/... + GOOS=linux GOARCH=arm64 go build -ldflags "${ld_flags}" -o ./kn-linux-arm64 ./cmd/... echo "🚧 🍏 Building for macOS" - GOOS=darwin GOARCH=amd64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-darwin-amd64 ./cmd/... + GOOS=darwin GOARCH=amd64 go build -ldflags "${ld_flags}" -o ./kn-darwin-amd64 ./cmd/... echo "🚧 🍎 Building for macOS (arm64)" - GOOS=darwin GOARCH=arm64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-darwin-arm64 ./cmd/... + GOOS=darwin GOARCH=arm64 go build -ldflags "${ld_flags}" -o ./kn-darwin-arm64 ./cmd/... echo "🚧 🎠 Building for Windows" - GOOS=windows GOARCH=amd64 go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-windows-amd64.exe ./cmd/... + GOOS=windows GOARCH=amd64 go build -ldflags "${ld_flags}" -o ./kn-windows-amd64.exe ./cmd/... echo "🚧 Z Building for Linux(s390x)" - GOOS=linux GOARCH=s390x go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-s390x ./cmd/... + GOOS=linux GOARCH=s390x go build -ldflags "${ld_flags}" -o ./kn-linux-s390x ./cmd/... echo "🚧 P Building for Linux (ppc64le)" - GOOS=linux GOARCH=ppc64le go build -mod=vendor -ldflags "${ld_flags}" -o ./kn-linux-ppc64le ./cmd/... + GOOS=linux GOARCH=ppc64le go build -ldflags "${ld_flags}" -o ./kn-linux-ppc64le ./cmd/... echo "🚧 🐳 Building the container image" # Handle latest default tag in `ko` to be present only for latest releases. diff --git a/hack/tools.go b/hack/tools.go index 857650f832..2a4f4f706f 100644 --- a/hack/tools.go +++ b/hack/tools.go @@ -18,7 +18,7 @@ package tools // This package imports things required by this repository, to force `go mod` to see them as dependencies import ( - _ "knative.dev/hack" + _ "knative.dev/hack/cmd/script" _ "knative.dev/pkg/hack" _ "k8s.io/code-generator" diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index 68374b7ea0..71c872d898 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -18,25 +18,7 @@ set -o errexit set -o nounset set -o pipefail -source $(dirname $0)/../vendor/knative.dev/hack/codegen-library.sh +# shellcheck disable=SC1090 +source "$(go run knative.dev/hack/cmd/script codegen-library.sh)" -# If we run with -mod=vendor here, then generate-groups.sh looks for vendor files in the wrong place. -export GOFLAGS=-mod= - -echo "=== Update Codegen for $MODULE_NAME" - -group "Kubernetes Codegen" - -# generate the code with: -# --output-base because this script should also be able to run inside the vendor dir of -# k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir -# instead of the $GOPATH directly. For normal projects this can be dropped. -"${CODEGEN_PKG}"/generate-groups.sh "deepcopy" \ - knative.dev/client/pkg/apis/client/v1alpha1/generated knative.dev/client/pkg/apis \ - client:v1alpha1 \ - --go-header-file "${REPO_ROOT_DIR}"/hack/boilerplate.go.txt - -group "Update deps post-codegen" - -# Make sure our dependencies are up-to-date -${REPO_ROOT_DIR}/hack/update-deps.sh +echo "=== Noop codegen for $MODULE_NAME" diff --git a/hack/update-deps.sh b/hack/update-deps.sh index 1cf6086ca8..ed9413fac3 100755 --- a/hack/update-deps.sh +++ b/hack/update-deps.sh @@ -18,6 +18,7 @@ set -o errexit set -o nounset set -o pipefail -source $(dirname $0)/../vendor/knative.dev/hack/library.sh +# shellcheck disable=SC1090 +source "$(go run knative.dev/hack/cmd/script library.sh)" go_update_deps "$@" diff --git a/hack/verify-codegen.sh b/hack/verify-codegen.sh index dd6a6e7009..a0a6777c49 100755 --- a/hack/verify-codegen.sh +++ b/hack/verify-codegen.sh @@ -18,7 +18,8 @@ set -o errexit set -o nounset set -o pipefail -source $(dirname $0)/../vendor/knative.dev/hack/library.sh +# shellcheck disable=SC1090 +source "$(go run knative.dev/hack/cmd/script library.sh)" "${REPO_ROOT_DIR}"/hack/build.sh --codegen if output="$(git status --porcelain)" && [ -z "$output" ]; then diff --git a/pkg/kn/commands/broker/broker.go b/pkg/commands/broker/broker.go similarity index 96% rename from pkg/kn/commands/broker/broker.go rename to pkg/commands/broker/broker.go index 52e45478a3..c642f757df 100644 --- a/pkg/kn/commands/broker/broker.go +++ b/pkg/commands/broker/broker.go @@ -19,7 +19,7 @@ package broker import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewBrokerCommand represents broker management commands diff --git a/pkg/kn/commands/broker/broker_test.go b/pkg/commands/broker/broker_test.go similarity index 96% rename from pkg/kn/commands/broker/broker_test.go rename to pkg/commands/broker/broker_test.go index aaae5aa44e..4708aa69b6 100644 --- a/pkg/kn/commands/broker/broker_test.go +++ b/pkg/commands/broker/broker_test.go @@ -20,14 +20,14 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/clientcmd" - "knative.dev/client/pkg/dynamic" - dynamicfake "knative.dev/client/pkg/dynamic/fake" + "knative.dev/client-pkg/pkg/dynamic" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" v1 "knative.dev/eventing/pkg/apis/duck/v1" duckv1 "knative.dev/pkg/apis/duck/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - clientv1beta1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/kn/commands" + clientv1beta1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client/pkg/commands" v1beta1 "knative.dev/eventing/pkg/apis/eventing/v1" ) diff --git a/pkg/kn/commands/broker/config_flags.go b/pkg/commands/broker/config_flags.go similarity index 100% rename from pkg/kn/commands/broker/config_flags.go rename to pkg/commands/broker/config_flags.go diff --git a/pkg/kn/commands/broker/config_flags_test.go b/pkg/commands/broker/config_flags_test.go similarity index 100% rename from pkg/kn/commands/broker/config_flags_test.go rename to pkg/commands/broker/config_flags_test.go diff --git a/pkg/kn/commands/broker/create.go b/pkg/commands/broker/create.go similarity index 97% rename from pkg/kn/commands/broker/create.go rename to pkg/commands/broker/create.go index eeca1cb109..25c7b7d6fc 100644 --- a/pkg/kn/commands/broker/create.go +++ b/pkg/commands/broker/create.go @@ -24,8 +24,8 @@ import ( v1 "knative.dev/eventing/pkg/apis/duck/v1" duckv1 "knative.dev/pkg/apis/duck/v1" - clientv1beta1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/kn/commands" + clientv1beta1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client/pkg/commands" ) var createExample = ` diff --git a/pkg/kn/commands/broker/create_test.go b/pkg/commands/broker/create_test.go similarity index 98% rename from pkg/kn/commands/broker/create_test.go rename to pkg/commands/broker/create_test.go index dc55b03ef6..9f2bd078af 100644 --- a/pkg/kn/commands/broker/create_test.go +++ b/pkg/commands/broker/create_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" v1 "knative.dev/pkg/apis/duck/v1" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" ) var ( diff --git a/pkg/kn/commands/broker/delete.go b/pkg/commands/broker/delete.go similarity index 98% rename from pkg/kn/commands/broker/delete.go rename to pkg/commands/broker/delete.go index c62d6323cd..ce015d7f05 100644 --- a/pkg/kn/commands/broker/delete.go +++ b/pkg/commands/broker/delete.go @@ -23,7 +23,7 @@ import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) var deleteExample = ` diff --git a/pkg/kn/commands/broker/delete_test.go b/pkg/commands/broker/delete_test.go similarity index 92% rename from pkg/kn/commands/broker/delete_test.go rename to pkg/commands/broker/delete_test.go index d5319f7e74..825b008d7a 100644 --- a/pkg/kn/commands/broker/delete_test.go +++ b/pkg/commands/broker/delete_test.go @@ -22,9 +22,9 @@ import ( "gotest.tools/v3/assert" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/util/mock" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/mock" ) func TestBrokerDelete(t *testing.T) { diff --git a/pkg/kn/commands/broker/delivery_option_flags.go b/pkg/commands/broker/delivery_option_flags.go similarity index 94% rename from pkg/kn/commands/broker/delivery_option_flags.go rename to pkg/commands/broker/delivery_option_flags.go index e9c21dea3f..ef309923bc 100644 --- a/pkg/kn/commands/broker/delivery_option_flags.go +++ b/pkg/commands/broker/delivery_option_flags.go @@ -18,13 +18,13 @@ import ( "reflect" "github.com/spf13/cobra" - "knative.dev/client/pkg/dynamic" - "knative.dev/client/pkg/kn/commands/flags" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + "knative.dev/client-pkg/pkg/dynamic" duckv1 "knative.dev/pkg/apis/duck/v1" ) type DeliveryOptionFlags struct { - SinkFlags flags.SinkFlags + SinkFlags sinkfl.Flag RetryCount int32 Timeout string BackoffPolicy string @@ -49,7 +49,7 @@ func (d *DeliveryOptionFlags) Add(cmd *cobra.Command) { } func (d *DeliveryOptionFlags) GetDlSink(cmd *cobra.Command, dynamicClient dynamic.KnDynamicClient, namespace string) (*duckv1.Destination, error) { - var empty = flags.SinkFlags{} + var empty = sinkfl.Flag{} var destination *duckv1.Destination var err error if !reflect.DeepEqual(d.SinkFlags, empty) { diff --git a/pkg/kn/commands/broker/describe.go b/pkg/commands/broker/describe.go similarity index 97% rename from pkg/kn/commands/broker/describe.go rename to pkg/commands/broker/describe.go index 31b2d7273f..904d0404ab 100644 --- a/pkg/kn/commands/broker/describe.go +++ b/pkg/commands/broker/describe.go @@ -28,8 +28,8 @@ import ( v1beta1 "knative.dev/eventing/pkg/apis/eventing/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) var describeExample = ` diff --git a/pkg/kn/commands/broker/describe_test.go b/pkg/commands/broker/describe_test.go similarity index 97% rename from pkg/kn/commands/broker/describe_test.go rename to pkg/commands/broker/describe_test.go index b57389d06a..ad663f88bc 100644 --- a/pkg/kn/commands/broker/describe_test.go +++ b/pkg/commands/broker/describe_test.go @@ -30,8 +30,8 @@ import ( "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" - clientv1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + clientv1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" ) func TestBrokerDescribe(t *testing.T) { diff --git a/pkg/kn/commands/broker/list.go b/pkg/commands/broker/list.go similarity index 95% rename from pkg/kn/commands/broker/list.go rename to pkg/commands/broker/list.go index 438829be88..3b49c7f56d 100644 --- a/pkg/kn/commands/broker/list.go +++ b/pkg/commands/broker/list.go @@ -26,9 +26,9 @@ import ( metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - hprinters "knative.dev/client/pkg/printers" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" ) @@ -41,7 +41,7 @@ var listExample = ` // NewBrokerListCommand represents command to list all brokers func NewBrokerListCommand(p *commands.KnParams) *cobra.Command { - brokerListFlags := flags.NewListPrintFlags(ListHandlers) + brokerListFlags := listfl.NewPrintFlags(ListHandlers) cmd := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/broker/list_test.go b/pkg/commands/broker/list_test.go similarity index 97% rename from pkg/kn/commands/broker/list_test.go rename to pkg/commands/broker/list_test.go index 5c7518539a..3a06afa54d 100644 --- a/pkg/kn/commands/broker/list_test.go +++ b/pkg/commands/broker/list_test.go @@ -25,8 +25,8 @@ import ( "gotest.tools/v3/assert" - clientv1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + clientv1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" ) diff --git a/pkg/kn/commands/broker/update.go b/pkg/commands/broker/update.go similarity index 96% rename from pkg/kn/commands/broker/update.go rename to pkg/commands/broker/update.go index d81ae25cdf..dde0b46039 100644 --- a/pkg/kn/commands/broker/update.go +++ b/pkg/commands/broker/update.go @@ -21,11 +21,11 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/config" - v1 "knative.dev/client/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/config" + v1 "knative.dev/client-pkg/pkg/eventing/v1" duckv1 "knative.dev/eventing/pkg/apis/duck/v1" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" ) diff --git a/pkg/kn/commands/broker/update_test.go b/pkg/commands/broker/update_test.go similarity index 98% rename from pkg/kn/commands/broker/update_test.go rename to pkg/commands/broker/update_test.go index d7adc31b9b..2106d88cdc 100644 --- a/pkg/kn/commands/broker/update_test.go +++ b/pkg/commands/broker/update_test.go @@ -20,8 +20,8 @@ import ( "testing" "gotest.tools/v3/assert" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" ) func TestBrokerUpdateWithDlSink(t *testing.T) { diff --git a/pkg/kn/commands/channel/channel.go b/pkg/commands/channel/channel.go similarity index 95% rename from pkg/kn/commands/channel/channel.go rename to pkg/commands/channel/channel.go index 0a412d3618..325113c5cb 100644 --- a/pkg/kn/commands/channel/channel.go +++ b/pkg/commands/channel/channel.go @@ -18,8 +18,8 @@ import ( "github.com/spf13/cobra" "k8s.io/client-go/tools/clientcmd" - "knative.dev/client/pkg/kn/commands" - messagingv1 "knative.dev/client/pkg/messaging/v1" + messagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" clientv1beta1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" ) diff --git a/pkg/kn/commands/channel/channel_test.go b/pkg/commands/channel/channel_test.go similarity index 96% rename from pkg/kn/commands/channel/channel_test.go rename to pkg/commands/channel/channel_test.go index faefb3608a..7dc99f6093 100644 --- a/pkg/kn/commands/channel/channel_test.go +++ b/pkg/commands/channel/channel_test.go @@ -24,8 +24,8 @@ import ( "k8s.io/client-go/tools/clientcmd" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - "knative.dev/client/pkg/kn/commands" - clientv1beta1 "knative.dev/client/pkg/messaging/v1" + clientv1beta1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" eventingduck "knative.dev/eventing/pkg/apis/duck/v1" ) diff --git a/pkg/kn/commands/channel/create.go b/pkg/commands/channel/create.go similarity index 92% rename from pkg/kn/commands/channel/create.go rename to pkg/commands/channel/create.go index 0489588951..8af9433870 100644 --- a/pkg/kn/commands/channel/create.go +++ b/pkg/commands/channel/create.go @@ -20,10 +20,10 @@ import ( "github.com/spf13/cobra" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - knflags "knative.dev/client/pkg/kn/flags" - knmessagingv1 "knative.dev/client/pkg/messaging/v1" + knerrors "knative.dev/client-pkg/pkg/errors" + knmessagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" + knflags "knative.dev/client/pkg/flags" ) // NewChannelCreateCommand to create event channels diff --git a/pkg/kn/commands/channel/create_test.go b/pkg/commands/channel/create_test.go similarity index 96% rename from pkg/kn/commands/channel/create_test.go rename to pkg/commands/channel/create_test.go index 7579945354..c402bcc628 100644 --- a/pkg/kn/commands/channel/create_test.go +++ b/pkg/commands/channel/create_test.go @@ -20,8 +20,8 @@ import ( "gotest.tools/v3/assert" "k8s.io/apimachinery/pkg/runtime/schema" - v1beta1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + v1beta1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" ) func TestCreateChannelErrorCase(t *testing.T) { diff --git a/pkg/kn/commands/channel/delete.go b/pkg/commands/channel/delete.go similarity index 97% rename from pkg/kn/commands/channel/delete.go rename to pkg/commands/channel/delete.go index ebb3eb5d28..11cfda4230 100644 --- a/pkg/kn/commands/channel/delete.go +++ b/pkg/commands/channel/delete.go @@ -19,7 +19,7 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewChannelDeleteCommand is for deleting a Channel diff --git a/pkg/kn/commands/channel/delete_test.go b/pkg/commands/channel/delete_test.go similarity index 95% rename from pkg/kn/commands/channel/delete_test.go rename to pkg/commands/channel/delete_test.go index 71b06f8d5a..b28468634f 100644 --- a/pkg/kn/commands/channel/delete_test.go +++ b/pkg/commands/channel/delete_test.go @@ -20,8 +20,8 @@ import ( "gotest.tools/v3/assert" - v1beta1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + v1beta1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" ) func TestDeleteChannelErrorCase(t *testing.T) { diff --git a/pkg/kn/commands/channel/describe.go b/pkg/commands/channel/describe.go similarity index 96% rename from pkg/kn/commands/channel/describe.go rename to pkg/commands/channel/describe.go index 38e03cdaba..daca1dbfe8 100644 --- a/pkg/kn/commands/channel/describe.go +++ b/pkg/commands/channel/describe.go @@ -24,9 +24,9 @@ import ( "k8s.io/cli-runtime/pkg/genericclioptions" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) var describeExample = ` diff --git a/pkg/kn/commands/channel/describe_test.go b/pkg/commands/channel/describe_test.go similarity index 97% rename from pkg/kn/commands/channel/describe_test.go rename to pkg/commands/channel/describe_test.go index 77135dd490..084d5d3730 100644 --- a/pkg/kn/commands/channel/describe_test.go +++ b/pkg/commands/channel/describe_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" "k8s.io/apimachinery/pkg/runtime/schema" - clientv1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + clientv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" ) diff --git a/pkg/kn/commands/channel/flags.go b/pkg/commands/channel/flags.go similarity index 98% rename from pkg/kn/commands/channel/flags.go rename to pkg/commands/channel/flags.go index d5673ee601..5b6ce59f3b 100644 --- a/pkg/kn/commands/channel/flags.go +++ b/pkg/commands/channel/flags.go @@ -22,9 +22,9 @@ import ( metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" - hprinters "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" ) diff --git a/pkg/kn/commands/channel/list.go b/pkg/commands/channel/list.go similarity index 92% rename from pkg/kn/commands/channel/list.go rename to pkg/commands/channel/list.go index ab81371791..be5b36caa5 100644 --- a/pkg/kn/commands/channel/list.go +++ b/pkg/commands/channel/list.go @@ -17,18 +17,18 @@ package channel import ( "fmt" - "knative.dev/client/pkg/util" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + "knative.dev/client-pkg/pkg/util" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" ) // NewChannelListCommand is for listing channel objects func NewChannelListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(ListHandlers) + listFlags := listfl.NewPrintFlags(ListHandlers) listCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/channel/list_test.go b/pkg/commands/channel/list_test.go similarity index 97% rename from pkg/kn/commands/channel/list_test.go rename to pkg/commands/channel/list_test.go index 4d8a96a859..1882f17ce2 100644 --- a/pkg/kn/commands/channel/list_test.go +++ b/pkg/commands/channel/list_test.go @@ -23,10 +23,10 @@ import ( "gotest.tools/v3/assert" "k8s.io/apimachinery/pkg/runtime/schema" - clientv1 "knative.dev/client/pkg/messaging/v1" + clientv1 "knative.dev/client-pkg/pkg/messaging/v1" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestChannelListNoChannelsFound(t *testing.T) { diff --git a/pkg/kn/commands/channel/list_types.go b/pkg/commands/channel/list_types.go similarity index 91% rename from pkg/kn/commands/channel/list_types.go rename to pkg/commands/channel/list_types.go index 944504224c..11e1c6cf2e 100644 --- a/pkg/kn/commands/channel/list_types.go +++ b/pkg/commands/channel/list_types.go @@ -13,6 +13,7 @@ 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 channel import ( @@ -21,16 +22,16 @@ import ( "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/client/pkg/dynamic" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - messagingv1 "knative.dev/client/pkg/messaging/v1" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + "knative.dev/client-pkg/pkg/dynamic" + knerrors "knative.dev/client-pkg/pkg/errors" + messagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" ) // NewChannelListTypesCommand defines and processes `kn channel list-types` func NewChannelListTypesCommand(p *commands.KnParams) *cobra.Command { - listTypesFlags := flags.NewListPrintFlags(ListTypesHandlers) + listTypesFlags := listfl.NewPrintFlags(ListTypesHandlers) listTypesCommand := &cobra.Command{ Use: "list-types", Short: "List channel types", diff --git a/pkg/kn/commands/channel/list_types_test.go b/pkg/commands/channel/list_types_test.go similarity index 97% rename from pkg/kn/commands/channel/list_types_test.go rename to pkg/commands/channel/list_types_test.go index 49d4e055d4..6c0d90b650 100644 --- a/pkg/kn/commands/channel/list_types_test.go +++ b/pkg/commands/channel/list_types_test.go @@ -27,11 +27,11 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" - dynamicfakeClient "knative.dev/client/pkg/dynamic/fake" + dynamicfakeClient "knative.dev/client-pkg/pkg/dynamic/fake" - clientdynamic "knative.dev/client/pkg/dynamic" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + clientdynamic "knative.dev/client-pkg/pkg/dynamic" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" "knative.dev/eventing/pkg/apis/messaging" ) diff --git a/pkg/kn/commands/completion/completion.go b/pkg/commands/completion/completion.go similarity index 98% rename from pkg/kn/commands/completion/completion.go rename to pkg/commands/completion/completion.go index 39b6b18c4c..a731eb0c90 100644 --- a/pkg/kn/commands/completion/completion.go +++ b/pkg/commands/completion/completion.go @@ -18,7 +18,7 @@ import ( "errors" "os" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" "github.com/spf13/cobra" ) diff --git a/pkg/kn/commands/completion/completion_test.go b/pkg/commands/completion/completion_test.go similarity index 94% rename from pkg/kn/commands/completion/completion_test.go rename to pkg/commands/completion/completion_test.go index 495f75d991..50a552d199 100644 --- a/pkg/kn/commands/completion/completion_test.go +++ b/pkg/commands/completion/completion_test.go @@ -17,9 +17,9 @@ package completion import ( "testing" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" + "knative.dev/client/pkg/commands" "github.com/spf13/cobra" "gotest.tools/v3/assert" diff --git a/pkg/kn/commands/completion_helper.go b/pkg/commands/completion_helper.go similarity index 100% rename from pkg/kn/commands/completion_helper.go rename to pkg/commands/completion_helper.go diff --git a/pkg/kn/commands/completion_helper_test.go b/pkg/commands/completion_helper_test.go similarity index 99% rename from pkg/kn/commands/completion_helper_test.go rename to pkg/commands/completion_helper_test.go index ec96faabbd..5d7bbe3d2e 100644 --- a/pkg/kn/commands/completion_helper_test.go +++ b/pkg/commands/completion_helper_test.go @@ -25,11 +25,11 @@ import ( "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/clientcmd" - clienteventingv1beta2 "knative.dev/client/pkg/eventing/v1beta2" - v1beta1 "knative.dev/client/pkg/messaging/v1" - clientv1beta1 "knative.dev/client/pkg/serving/v1beta1" - clientsourcesv1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/sources/v1beta2" + clienteventingv1beta2 "knative.dev/client-pkg/pkg/eventing/v1beta2" + v1beta1 "knative.dev/client-pkg/pkg/messaging/v1" + clientv1beta1 "knative.dev/client-pkg/pkg/serving/v1beta1" + clientsourcesv1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/sources/v1beta2" eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" @@ -40,8 +40,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/cli-runtime/pkg/genericclioptions" clienttesting "k8s.io/client-go/testing" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - v1 "knative.dev/client/pkg/serving/v1" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + v1 "knative.dev/client-pkg/pkg/serving/v1" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1/fake" diff --git a/pkg/kn/commands/container/add.go b/pkg/commands/container/add.go similarity index 97% rename from pkg/kn/commands/container/add.go rename to pkg/commands/container/add.go index 06a05f5c17..eb7a7bb3c2 100644 --- a/pkg/kn/commands/container/add.go +++ b/pkg/commands/container/add.go @@ -21,8 +21,8 @@ import ( "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" - "knative.dev/client/pkg/kn/commands" - knflags "knative.dev/client/pkg/kn/flags" + "knative.dev/client/pkg/commands" + knflags "knative.dev/client/pkg/flags" sigyaml "sigs.k8s.io/yaml" ) diff --git a/pkg/kn/commands/container/add_test.go b/pkg/commands/container/add_test.go similarity index 98% rename from pkg/kn/commands/container/add_test.go rename to pkg/commands/container/add_test.go index ed2cbd8dfa..08d95f2f01 100644 --- a/pkg/kn/commands/container/add_test.go +++ b/pkg/commands/container/add_test.go @@ -18,7 +18,7 @@ import ( "os" "testing" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "gotest.tools/v3/assert" ) diff --git a/pkg/kn/commands/container/container.go b/pkg/commands/container/container.go similarity index 96% rename from pkg/kn/commands/container/container.go rename to pkg/commands/container/container.go index 4745ddab78..ca38a6caa0 100644 --- a/pkg/kn/commands/container/container.go +++ b/pkg/commands/container/container.go @@ -16,7 +16,7 @@ package container import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewContainerCommand to manage containers diff --git a/pkg/kn/commands/container/container_test.go b/pkg/commands/container/container_test.go similarity index 97% rename from pkg/kn/commands/container/container_test.go rename to pkg/commands/container/container_test.go index fd79c8ef10..f22ef8706a 100644 --- a/pkg/kn/commands/container/container_test.go +++ b/pkg/commands/container/container_test.go @@ -19,7 +19,7 @@ import ( "testing" "gotest.tools/v3/assert" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) func TestContainerCommand(t *testing.T) { diff --git a/pkg/kn/commands/describe.go b/pkg/commands/describe.go similarity index 99% rename from pkg/kn/commands/describe.go rename to pkg/commands/describe.go index 2fd7538054..89bfdeaf2c 100644 --- a/pkg/kn/commands/describe.go +++ b/pkg/commands/describe.go @@ -24,7 +24,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/duration" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" "knative.dev/pkg/apis" ) diff --git a/pkg/kn/commands/describe_test.go b/pkg/commands/describe_test.go similarity index 99% rename from pkg/kn/commands/describe_test.go rename to pkg/commands/describe_test.go index 49a5470e74..face235c25 100644 --- a/pkg/kn/commands/describe_test.go +++ b/pkg/commands/describe_test.go @@ -25,7 +25,7 @@ import ( "gotest.tools/v3/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" "knative.dev/pkg/apis" ) diff --git a/pkg/kn/commands/domain/create.go b/pkg/commands/domain/create.go similarity index 94% rename from pkg/kn/commands/domain/create.go rename to pkg/commands/domain/create.go index 181775e76b..6d0a232dbf 100644 --- a/pkg/kn/commands/domain/create.go +++ b/pkg/commands/domain/create.go @@ -21,9 +21,9 @@ import ( "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/util/validation" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - clientv1beta1 "knative.dev/client/pkg/serving/v1beta1" + knerrors "knative.dev/client-pkg/pkg/errors" + clientv1beta1 "knative.dev/client-pkg/pkg/serving/v1beta1" + "knative.dev/client/pkg/commands" ) // NewDomainMappingCreateCommand to create event channels diff --git a/pkg/kn/commands/domain/create_test.go b/pkg/commands/domain/create_test.go similarity index 95% rename from pkg/kn/commands/domain/create_test.go rename to pkg/commands/domain/create_test.go index c8338df4e7..3650765fb8 100644 --- a/pkg/kn/commands/domain/create_test.go +++ b/pkg/commands/domain/create_test.go @@ -19,9 +19,9 @@ import ( "gotest.tools/v3/assert" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - "knative.dev/client/pkg/serving/v1beta1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + "knative.dev/client-pkg/pkg/serving/v1beta1" + "knative.dev/client-pkg/pkg/util" ) func TestDomainMappingCreate(t *testing.T) { diff --git a/pkg/kn/commands/domain/delete.go b/pkg/commands/domain/delete.go similarity index 95% rename from pkg/kn/commands/domain/delete.go rename to pkg/commands/domain/delete.go index 6d0e65e5be..ab6bd6d4ab 100644 --- a/pkg/kn/commands/domain/delete.go +++ b/pkg/commands/domain/delete.go @@ -20,8 +20,8 @@ import ( "github.com/spf13/cobra" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client/pkg/commands" ) // NewDomainMappingDeleteCommand to create event channels diff --git a/pkg/kn/commands/domain/delete_test.go b/pkg/commands/domain/delete_test.go similarity index 94% rename from pkg/kn/commands/domain/delete_test.go rename to pkg/commands/domain/delete_test.go index 6b8b74ccb5..71830e9d18 100644 --- a/pkg/kn/commands/domain/delete_test.go +++ b/pkg/commands/domain/delete_test.go @@ -20,9 +20,9 @@ import ( "gotest.tools/v3/assert" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - "knative.dev/client/pkg/serving/v1beta1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + "knative.dev/client-pkg/pkg/serving/v1beta1" + "knative.dev/client-pkg/pkg/util" ) func TestDomainMappingDelete(t *testing.T) { diff --git a/pkg/kn/commands/domain/describe.go b/pkg/commands/domain/describe.go similarity index 97% rename from pkg/kn/commands/domain/describe.go rename to pkg/commands/domain/describe.go index 5ebc051e96..500a911b93 100644 --- a/pkg/kn/commands/domain/describe.go +++ b/pkg/commands/domain/describe.go @@ -23,8 +23,8 @@ import ( "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" "knative.dev/serving/pkg/apis/serving/v1beta1" ) diff --git a/pkg/kn/commands/domain/describe_test.go b/pkg/commands/domain/describe_test.go similarity index 98% rename from pkg/kn/commands/domain/describe_test.go rename to pkg/commands/domain/describe_test.go index 6421f6bcb6..06c1324f65 100644 --- a/pkg/kn/commands/domain/describe_test.go +++ b/pkg/commands/domain/describe_test.go @@ -24,8 +24,8 @@ import ( "gotest.tools/v3/assert" "gotest.tools/v3/assert/cmp" - "knative.dev/client/pkg/serving/v1beta1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/serving/v1beta1" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" diff --git a/pkg/kn/commands/domain/domain.go b/pkg/commands/domain/domain.go similarity index 97% rename from pkg/kn/commands/domain/domain.go rename to pkg/commands/domain/domain.go index 280b590aa8..3093da2d77 100644 --- a/pkg/kn/commands/domain/domain.go +++ b/pkg/commands/domain/domain.go @@ -22,8 +22,8 @@ import ( "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" - clientdynamic "knative.dev/client/pkg/dynamic" - "knative.dev/client/pkg/kn/commands" + clientdynamic "knative.dev/client-pkg/pkg/dynamic" + "knative.dev/client/pkg/commands" duckv1 "knative.dev/pkg/apis/duck/v1" ) diff --git a/pkg/kn/commands/domain/domain_test.go b/pkg/commands/domain/domain_test.go similarity index 95% rename from pkg/kn/commands/domain/domain_test.go rename to pkg/commands/domain/domain_test.go index 9a246627fc..05ea5bd8d3 100644 --- a/pkg/kn/commands/domain/domain_test.go +++ b/pkg/commands/domain/domain_test.go @@ -26,11 +26,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/clientcmd" - kndynamic "knative.dev/client/pkg/dynamic" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - "knative.dev/client/pkg/kn/commands" - knflags "knative.dev/client/pkg/kn/flags" - clientservingv1beta1 "knative.dev/client/pkg/serving/v1beta1" + kndynamic "knative.dev/client-pkg/pkg/dynamic" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + clientservingv1beta1 "knative.dev/client-pkg/pkg/serving/v1beta1" + "knative.dev/client/pkg/commands" + knflags "knative.dev/client/pkg/flags" duckv1 "knative.dev/pkg/apis/duck/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" diff --git a/pkg/kn/commands/domain/human_readable_flags.go b/pkg/commands/domain/human_readable_flags.go similarity index 97% rename from pkg/kn/commands/domain/human_readable_flags.go rename to pkg/commands/domain/human_readable_flags.go index 9cba66b4c6..79338a4508 100644 --- a/pkg/kn/commands/domain/human_readable_flags.go +++ b/pkg/commands/domain/human_readable_flags.go @@ -19,8 +19,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" "knative.dev/serving/pkg/apis/serving/v1beta1" - "knative.dev/client/pkg/kn/commands" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) // DomainMappingListHandlers adds print handlers for route list command diff --git a/pkg/kn/commands/domain/list.go b/pkg/commands/domain/list.go similarity index 92% rename from pkg/kn/commands/domain/list.go rename to pkg/commands/domain/list.go index e6dbb99f59..1e0fe3532b 100644 --- a/pkg/kn/commands/domain/list.go +++ b/pkg/commands/domain/list.go @@ -18,14 +18,14 @@ import ( "fmt" "github.com/spf13/cobra" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" ) // NewDomainMappingListCommand represents 'kn revision list' command func NewDomainMappingListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(DomainMappingListHandlers) + listFlags := listfl.NewPrintFlags(DomainMappingListHandlers) cmd := &cobra.Command{ Use: "list", Short: "List domain mappings", diff --git a/pkg/kn/commands/domain/list_test.go b/pkg/commands/domain/list_test.go similarity index 97% rename from pkg/kn/commands/domain/list_test.go rename to pkg/commands/domain/list_test.go index 8685c32f0a..dcf20a1e79 100644 --- a/pkg/kn/commands/domain/list_test.go +++ b/pkg/commands/domain/list_test.go @@ -20,8 +20,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/pkg/serving/v1beta1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/serving/v1beta1" + "knative.dev/client-pkg/pkg/util" servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" "knative.dev/serving/pkg/client/clientset/versioned/scheme" ) diff --git a/pkg/kn/commands/domain/update.go b/pkg/commands/domain/update.go similarity index 95% rename from pkg/kn/commands/domain/update.go rename to pkg/commands/domain/update.go index 52b0e8ade7..aa708e4d00 100644 --- a/pkg/kn/commands/domain/update.go +++ b/pkg/commands/domain/update.go @@ -18,13 +18,13 @@ import ( "errors" "fmt" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" "knative.dev/serving/pkg/apis/serving/v1beta1" "github.com/spf13/cobra" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client/pkg/commands" ) // NewDomainMappingUpdateCommand to create event channels diff --git a/pkg/kn/commands/domain/update_test.go b/pkg/commands/domain/update_test.go similarity index 95% rename from pkg/kn/commands/domain/update_test.go rename to pkg/commands/domain/update_test.go index c027632d41..099c0c7786 100644 --- a/pkg/kn/commands/domain/update_test.go +++ b/pkg/commands/domain/update_test.go @@ -23,9 +23,9 @@ import ( "gotest.tools/v3/assert" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - "knative.dev/client/pkg/serving/v1beta1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + "knative.dev/client-pkg/pkg/serving/v1beta1" + "knative.dev/client-pkg/pkg/util" ) func TestDomainMappingUpdate(t *testing.T) { diff --git a/pkg/kn/commands/eventtype/create.go b/pkg/commands/eventtype/create.go similarity index 93% rename from pkg/kn/commands/eventtype/create.go rename to pkg/commands/eventtype/create.go index 7c8d557a66..ce8745b3a3 100644 --- a/pkg/kn/commands/eventtype/create.go +++ b/pkg/commands/eventtype/create.go @@ -21,9 +21,10 @@ import ( "fmt" "github.com/spf13/cobra" - clienteventingv1beta2 "knative.dev/client/pkg/eventing/v1beta2" - "knative.dev/client/pkg/kn/commands" - knflags "knative.dev/client/pkg/kn/commands/flags" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + clienteventingv1beta2 "knative.dev/client-pkg/pkg/eventing/v1beta2" + "knative.dev/client/pkg/commands" + knflags "knative.dev/client/pkg/commands/flags" "knative.dev/pkg/apis" ) @@ -40,7 +41,7 @@ func NewEventtypeCreateCommand(p *commands.KnParams) *cobra.Command { var eventtypeFlags knflags.EventtypeFlags - referenceFlag := knflags.NewSinkFlag(referenceMappings) + referenceFlag := sinkfl.NewFlag(referenceMappings) cmd := &cobra.Command{ Use: "create", diff --git a/pkg/kn/commands/eventtype/create_test.go b/pkg/commands/eventtype/create_test.go similarity index 97% rename from pkg/kn/commands/eventtype/create_test.go rename to pkg/commands/eventtype/create_test.go index ad41989d43..d8eaa933df 100644 --- a/pkg/kn/commands/eventtype/create_test.go +++ b/pkg/commands/eventtype/create_test.go @@ -20,11 +20,11 @@ import ( "fmt" "testing" - dynamicfake "knative.dev/client/pkg/dynamic/fake" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" "gotest.tools/v3/assert" - "knative.dev/client/pkg/eventing/v1beta2" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/eventing/v1beta2" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/apis" ) diff --git a/pkg/kn/commands/eventtype/delete.go b/pkg/commands/eventtype/delete.go similarity index 98% rename from pkg/kn/commands/eventtype/delete.go rename to pkg/commands/eventtype/delete.go index 72c8b19eba..d247318c80 100644 --- a/pkg/kn/commands/eventtype/delete.go +++ b/pkg/commands/eventtype/delete.go @@ -21,7 +21,7 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) var deleteExample = ` diff --git a/pkg/kn/commands/eventtype/delete_test.go b/pkg/commands/eventtype/delete_test.go similarity index 94% rename from pkg/kn/commands/eventtype/delete_test.go rename to pkg/commands/eventtype/delete_test.go index f96524c7b4..03ca891e66 100644 --- a/pkg/kn/commands/eventtype/delete_test.go +++ b/pkg/commands/eventtype/delete_test.go @@ -20,11 +20,11 @@ import ( "fmt" "testing" - dynamicfake "knative.dev/client/pkg/dynamic/fake" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" "gotest.tools/v3/assert" - "knative.dev/client/pkg/eventing/v1beta2" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/eventing/v1beta2" + "knative.dev/client-pkg/pkg/util" ) func TestEventtypeDelete(t *testing.T) { diff --git a/pkg/kn/commands/eventtype/describe.go b/pkg/commands/eventtype/describe.go similarity index 98% rename from pkg/kn/commands/eventtype/describe.go rename to pkg/commands/eventtype/describe.go index 4e292933f1..515a351a49 100644 --- a/pkg/kn/commands/eventtype/describe.go +++ b/pkg/commands/eventtype/describe.go @@ -26,8 +26,8 @@ import ( "k8s.io/cli-runtime/pkg/genericclioptions" "knative.dev/eventing/pkg/apis/eventing/v1beta2" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) var describeExample = ` diff --git a/pkg/kn/commands/eventtype/describe_test.go b/pkg/commands/eventtype/describe_test.go similarity index 97% rename from pkg/kn/commands/eventtype/describe_test.go rename to pkg/commands/eventtype/describe_test.go index ba732aa3a2..441a7e252d 100644 --- a/pkg/kn/commands/eventtype/describe_test.go +++ b/pkg/commands/eventtype/describe_test.go @@ -21,14 +21,14 @@ import ( "fmt" "testing" - dynamicfake "knative.dev/client/pkg/dynamic/fake" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" "gotest.tools/v3/assert" "gotest.tools/v3/assert/cmp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/client/pkg/eventing/v1beta2" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/eventing/v1beta2" + "knative.dev/client-pkg/pkg/util" eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" diff --git a/pkg/kn/commands/eventtype/eventtype.go b/pkg/commands/eventtype/eventtype.go similarity index 97% rename from pkg/kn/commands/eventtype/eventtype.go rename to pkg/commands/eventtype/eventtype.go index 6e6b75fd2c..56c2fbeb8b 100644 --- a/pkg/kn/commands/eventtype/eventtype.go +++ b/pkg/commands/eventtype/eventtype.go @@ -20,7 +20,7 @@ import ( "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewEventTypeCommand represents event type management commands diff --git a/pkg/kn/commands/eventtype/eventtype_test.go b/pkg/commands/eventtype/eventtype_test.go similarity index 95% rename from pkg/kn/commands/eventtype/eventtype_test.go rename to pkg/commands/eventtype/eventtype_test.go index f4a44be857..ed942df3d9 100644 --- a/pkg/kn/commands/eventtype/eventtype_test.go +++ b/pkg/commands/eventtype/eventtype_test.go @@ -19,11 +19,11 @@ package eventtype import ( "bytes" - kndynamic "knative.dev/client/pkg/dynamic" + kndynamic "knative.dev/client-pkg/pkg/dynamic" "k8s.io/client-go/tools/clientcmd" - "knative.dev/client/pkg/eventing/v1beta2" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client-pkg/pkg/eventing/v1beta2" + "knative.dev/client/pkg/commands" eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" "knative.dev/pkg/apis" ) diff --git a/pkg/kn/commands/eventtype/list.go b/pkg/commands/eventtype/list.go similarity index 95% rename from pkg/kn/commands/eventtype/list.go rename to pkg/commands/eventtype/list.go index 53da78e53e..3085529ecc 100644 --- a/pkg/kn/commands/eventtype/list.go +++ b/pkg/commands/eventtype/list.go @@ -20,13 +20,13 @@ import ( "fmt" "github.com/spf13/cobra" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" ) @@ -39,7 +39,7 @@ var listExample = ` // NewEventtypeListCommand represents command to list all eventtypes func NewEventtypeListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(ListHandlers) + listFlags := listfl.NewPrintFlags(ListHandlers) cmd := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/eventtype/list_test.go b/pkg/commands/eventtype/list_test.go similarity index 96% rename from pkg/kn/commands/eventtype/list_test.go rename to pkg/commands/eventtype/list_test.go index d76892686e..a7a1e965d2 100644 --- a/pkg/kn/commands/eventtype/list_test.go +++ b/pkg/commands/eventtype/list_test.go @@ -21,11 +21,11 @@ import ( "strings" "testing" - dynamicfake "knative.dev/client/pkg/dynamic/fake" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" "gotest.tools/v3/assert" - "knative.dev/client/pkg/eventing/v1beta2" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/eventing/v1beta2" + "knative.dev/client-pkg/pkg/util" eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" ) diff --git a/pkg/kn/commands/flags/eventtype.go b/pkg/commands/flags/eventtype.go similarity index 100% rename from pkg/kn/commands/flags/eventtype.go rename to pkg/commands/flags/eventtype.go diff --git a/pkg/kn/commands/flags/eventtype_test.go b/pkg/commands/flags/eventtype_test.go similarity index 100% rename from pkg/kn/commands/flags/eventtype_test.go rename to pkg/commands/flags/eventtype_test.go diff --git a/pkg/kn/commands/flags/listfilters.go b/pkg/commands/flags/listfilters.go similarity index 100% rename from pkg/kn/commands/flags/listfilters.go rename to pkg/commands/flags/listfilters.go diff --git a/pkg/kn/commands/flags/listfilters_test.go b/pkg/commands/flags/listfilters_test.go similarity index 100% rename from pkg/kn/commands/flags/listfilters_test.go rename to pkg/commands/flags/listfilters_test.go diff --git a/pkg/kn/commands/flags/listprint.go b/pkg/commands/flags/listprint.go similarity index 84% rename from pkg/kn/commands/flags/listprint.go rename to pkg/commands/flags/listprint.go index da73381c01..b6032e3b7a 100644 --- a/pkg/kn/commands/flags/listprint.go +++ b/pkg/commands/flags/listprint.go @@ -21,9 +21,9 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/cli-runtime/pkg/genericclioptions" - "knative.dev/client/pkg/kn/commands" - hprinters "knative.dev/client/pkg/printers" - "knative.dev/client/pkg/util" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // ListFlags composes common printer flag structs @@ -85,16 +85,6 @@ func (f *ListPrintFlags) AddFlags(cmd *cobra.Command) { f.HumanReadableFlags.AddFlags(cmd) } -// NewListFlags returns flags associated with humanreadable, -// template, and "name" printing, with default values set. -func NewListPrintFlags(printer func(h hprinters.PrintHandler)) *ListPrintFlags { - return &ListPrintFlags{ - GenericPrintFlags: genericclioptions.NewPrintFlags(""), - HumanReadableFlags: commands.NewHumanPrintFlags(), - PrinterHandler: printer, - } -} - // EnsureWithNamespace ensures that humanreadable flags return // a printer capable of printing with a "namespace" column. func (f *ListPrintFlags) EnsureWithNamespace() { diff --git a/pkg/kn/commands/flags/traffic.go b/pkg/commands/flags/traffic.go similarity index 100% rename from pkg/kn/commands/flags/traffic.go rename to pkg/commands/flags/traffic.go diff --git a/pkg/kn/commands/flags/traffic_test.go b/pkg/commands/flags/traffic_test.go similarity index 100% rename from pkg/kn/commands/flags/traffic_test.go rename to pkg/commands/flags/traffic_test.go diff --git a/pkg/kn/commands/human_readable_flags.go b/pkg/commands/human_readable_flags.go similarity index 98% rename from pkg/kn/commands/human_readable_flags.go rename to pkg/commands/human_readable_flags.go index 716c119706..faa477e2d6 100644 --- a/pkg/kn/commands/human_readable_flags.go +++ b/pkg/commands/human_readable_flags.go @@ -22,7 +22,7 @@ import ( "github.com/spf13/pflag" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/duration" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" ) diff --git a/pkg/kn/commands/human_readable_flags_test.go b/pkg/commands/human_readable_flags_test.go similarity index 98% rename from pkg/kn/commands/human_readable_flags_test.go rename to pkg/commands/human_readable_flags_test.go index ca606b3b6a..d910e55716 100644 --- a/pkg/kn/commands/human_readable_flags_test.go +++ b/pkg/commands/human_readable_flags_test.go @@ -29,8 +29,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/duration" - "knative.dev/client/pkg/printers" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client-pkg/pkg/util" ) var ( diff --git a/pkg/kn/commands/namespaced.go b/pkg/commands/namespaced.go similarity index 100% rename from pkg/kn/commands/namespaced.go rename to pkg/commands/namespaced.go diff --git a/pkg/kn/commands/namespaced_test.go b/pkg/commands/namespaced_test.go similarity index 99% rename from pkg/kn/commands/namespaced_test.go rename to pkg/commands/namespaced_test.go index 3110c08508..d88dd1b450 100644 --- a/pkg/kn/commands/namespaced_test.go +++ b/pkg/commands/namespaced_test.go @@ -19,7 +19,7 @@ import ( "path/filepath" "testing" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" "k8s.io/client-go/tools/clientcmd" diff --git a/pkg/kn/commands/options/options.go b/pkg/commands/options/options.go similarity index 100% rename from pkg/kn/commands/options/options.go rename to pkg/commands/options/options.go diff --git a/pkg/kn/commands/plugin/list.go b/pkg/commands/plugin/list.go similarity index 97% rename from pkg/kn/commands/plugin/list.go rename to pkg/commands/plugin/list.go index a97ca5d88b..d9f70cd1e9 100644 --- a/pkg/kn/commands/plugin/list.go +++ b/pkg/commands/plugin/list.go @@ -21,9 +21,9 @@ import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/config" - "knative.dev/client/pkg/kn/plugin" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/config" + "knative.dev/client/pkg/plugin" ) // ValidPluginFilenamePrefixes controls the prefix for all kn plugins diff --git a/pkg/kn/commands/plugin/list_test.go b/pkg/commands/plugin/list_test.go similarity index 97% rename from pkg/kn/commands/plugin/list_test.go rename to pkg/commands/plugin/list_test.go index 9d6fdba5b6..901815c6cc 100644 --- a/pkg/kn/commands/plugin/list_test.go +++ b/pkg/commands/plugin/list_test.go @@ -22,9 +22,9 @@ import ( "strings" "testing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/config" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/config" "github.com/spf13/cobra" "gotest.tools/v3/assert" diff --git a/pkg/kn/commands/plugin/plugin.go b/pkg/commands/plugin/plugin.go similarity index 96% rename from pkg/kn/commands/plugin/plugin.go rename to pkg/commands/plugin/plugin.go index 155023fe9a..d79c4d5354 100644 --- a/pkg/kn/commands/plugin/plugin.go +++ b/pkg/commands/plugin/plugin.go @@ -17,7 +17,7 @@ package plugin import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) func NewPluginCommand(p *commands.KnParams) *cobra.Command { diff --git a/pkg/kn/commands/plugin/plugin_test.go b/pkg/commands/plugin/plugin_test.go similarity index 93% rename from pkg/kn/commands/plugin/plugin_test.go rename to pkg/commands/plugin/plugin_test.go index 2a23d7a241..56e8ac3d2e 100644 --- a/pkg/kn/commands/plugin/plugin_test.go +++ b/pkg/commands/plugin/plugin_test.go @@ -19,8 +19,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) func TestNewPluginCommand(t *testing.T) { diff --git a/pkg/kn/commands/revision/delete.go b/pkg/commands/revision/delete.go similarity index 98% rename from pkg/kn/commands/revision/delete.go rename to pkg/commands/revision/delete.go index db9b6c9982..4a50fea9af 100644 --- a/pkg/kn/commands/revision/delete.go +++ b/pkg/commands/revision/delete.go @@ -22,8 +22,8 @@ import ( "time" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - v1 "knative.dev/client/pkg/serving/v1" + v1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/revision/delete_mock_test.go b/pkg/commands/revision/delete_mock_test.go similarity index 97% rename from pkg/kn/commands/revision/delete_mock_test.go rename to pkg/commands/revision/delete_mock_test.go index c70753a89d..782bc37160 100644 --- a/pkg/kn/commands/revision/delete_mock_test.go +++ b/pkg/commands/revision/delete_mock_test.go @@ -21,9 +21,9 @@ import ( "testing" "gotest.tools/v3/assert" - clientservingv1 "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/util/mock" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/mock" "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/revision/delete_test.go b/pkg/commands/revision/delete_test.go similarity index 97% rename from pkg/kn/commands/revision/delete_test.go rename to pkg/commands/revision/delete_test.go index d6ab73c5e4..3b80c8b9d9 100644 --- a/pkg/kn/commands/revision/delete_test.go +++ b/pkg/commands/revision/delete_test.go @@ -24,9 +24,9 @@ import ( "k8s.io/apimachinery/pkg/watch" clienttesting "k8s.io/client-go/testing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/wait" + "knative.dev/client/pkg/commands" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/revision/describe.go b/pkg/commands/revision/describe.go similarity index 98% rename from pkg/kn/commands/revision/describe.go rename to pkg/commands/revision/describe.go index 8c8acab0d3..17f7802f8d 100644 --- a/pkg/kn/commands/revision/describe.go +++ b/pkg/commands/revision/describe.go @@ -28,9 +28,9 @@ import ( "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" - clientserving "knative.dev/client/pkg/serving" + "knative.dev/client-pkg/pkg/printers" + clientserving "knative.dev/client-pkg/pkg/serving" + "knative.dev/client/pkg/commands" ) // Matching image digest diff --git a/pkg/kn/commands/revision/describe_test.go b/pkg/commands/revision/describe_test.go similarity index 98% rename from pkg/kn/commands/revision/describe_test.go rename to pkg/commands/revision/describe_test.go index bb09ff9649..b93f2f8fcc 100644 --- a/pkg/kn/commands/revision/describe_test.go +++ b/pkg/commands/revision/describe_test.go @@ -34,8 +34,8 @@ import ( servingv1 "knative.dev/serving/pkg/apis/serving/v1" "sigs.k8s.io/yaml" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) const ( diff --git a/pkg/kn/commands/revision/human_readable_flags.go b/pkg/commands/revision/human_readable_flags.go similarity index 97% rename from pkg/kn/commands/revision/human_readable_flags.go rename to pkg/commands/revision/human_readable_flags.go index 081279b9c4..34563dd273 100644 --- a/pkg/kn/commands/revision/human_readable_flags.go +++ b/pkg/commands/revision/human_readable_flags.go @@ -20,8 +20,8 @@ import ( "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) const ( diff --git a/pkg/kn/commands/revision/list.go b/pkg/commands/revision/list.go similarity index 97% rename from pkg/kn/commands/revision/list.go rename to pkg/commands/revision/list.go index 2f818b73f4..fdf552f3a1 100644 --- a/pkg/kn/commands/revision/list.go +++ b/pkg/commands/revision/list.go @@ -21,14 +21,14 @@ import ( "strconv" "strings" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" "knative.dev/serving/pkg/apis/serving" "github.com/spf13/cobra" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" ) // Service name filter, used with "-s" @@ -36,7 +36,7 @@ var serviceNameFilter string // NewRevisionListCommand represents 'kn revision list' command func NewRevisionListCommand(p *commands.KnParams) *cobra.Command { - revisionListFlags := flags.NewListPrintFlags(RevisionListHandlers) + revisionListFlags := listfl.NewPrintFlags(RevisionListHandlers) revisionListCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/revision/list_test.go b/pkg/commands/revision/list_test.go similarity index 99% rename from pkg/kn/commands/revision/list_test.go rename to pkg/commands/revision/list_test.go index 647baec9f5..32fb31d3d8 100644 --- a/pkg/kn/commands/revision/list_test.go +++ b/pkg/commands/revision/list_test.go @@ -25,8 +25,8 @@ import ( "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) var revisionListHeader = []string{"NAME", "SERVICE", "TRAFFIC", "TAGS", "GENERATION", "AGE", "CONDITIONS", "READY", "REASON"} diff --git a/pkg/kn/commands/revision/revision.go b/pkg/commands/revision/revision.go similarity index 97% rename from pkg/kn/commands/revision/revision.go rename to pkg/commands/revision/revision.go index 6b8bac0648..a344666b81 100644 --- a/pkg/kn/commands/revision/revision.go +++ b/pkg/commands/revision/revision.go @@ -18,7 +18,7 @@ import ( "github.com/spf13/cobra" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) func NewRevisionCommand(p *commands.KnParams) *cobra.Command { diff --git a/pkg/kn/commands/revision/revision_test.go b/pkg/commands/revision/revision_test.go similarity index 93% rename from pkg/kn/commands/revision/revision_test.go rename to pkg/commands/revision/revision_test.go index 3bf77b6bc1..14250a88f9 100644 --- a/pkg/kn/commands/revision/revision_test.go +++ b/pkg/commands/revision/revision_test.go @@ -22,12 +22,12 @@ import ( "github.com/spf13/cobra" "gotest.tools/v3/assert" "k8s.io/client-go/tools/clientcmd" - knflags "knative.dev/client/pkg/kn/flags" + knflags "knative.dev/client/pkg/flags" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // Helper methods diff --git a/pkg/kn/commands/route/describe.go b/pkg/commands/route/describe.go similarity index 98% rename from pkg/kn/commands/route/describe.go rename to pkg/commands/route/describe.go index 3064350cd2..07ea4e1f43 100644 --- a/pkg/kn/commands/route/describe.go +++ b/pkg/commands/route/describe.go @@ -23,8 +23,8 @@ import ( "k8s.io/cli-runtime/pkg/genericclioptions" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) // NewRouteDescribeCommand represents 'kn route describe' command diff --git a/pkg/kn/commands/route/describe_test.go b/pkg/commands/route/describe_test.go similarity index 98% rename from pkg/kn/commands/route/describe_test.go rename to pkg/commands/route/describe_test.go index c26e9fbaac..ec40529ed3 100644 --- a/pkg/kn/commands/route/describe_test.go +++ b/pkg/commands/route/describe_test.go @@ -27,8 +27,8 @@ import ( servingv1 "knative.dev/serving/pkg/apis/serving/v1" "sigs.k8s.io/yaml" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" "knative.dev/pkg/ptr" ) diff --git a/pkg/kn/commands/route/human_readable_flags.go b/pkg/commands/route/human_readable_flags.go similarity index 96% rename from pkg/kn/commands/route/human_readable_flags.go rename to pkg/commands/route/human_readable_flags.go index f366f9580d..44de6487c3 100644 --- a/pkg/kn/commands/route/human_readable_flags.go +++ b/pkg/commands/route/human_readable_flags.go @@ -19,8 +19,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) // RouteListHandlers adds print handlers for route list command diff --git a/pkg/kn/commands/route/list.go b/pkg/commands/route/list.go similarity index 91% rename from pkg/kn/commands/route/list.go rename to pkg/commands/route/list.go index 2e40896341..ae22f56c21 100644 --- a/pkg/kn/commands/route/list.go +++ b/pkg/commands/route/list.go @@ -18,18 +18,17 @@ import ( "errors" "fmt" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" "github.com/spf13/cobra" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - - "knative.dev/client/pkg/kn/commands/flags" ) // NewrouteListCommand represents 'kn route list' command func NewRouteListCommand(p *commands.KnParams) *cobra.Command { - routeListFlags := flags.NewListPrintFlags(RouteListHandlers) + routeListFlags := listfl.NewPrintFlags(RouteListHandlers) routeListCommand := &cobra.Command{ Use: "list NAME", Short: "List routes", diff --git a/pkg/kn/commands/route/list_test.go b/pkg/commands/route/list_test.go similarity index 98% rename from pkg/kn/commands/route/list_test.go rename to pkg/commands/route/list_test.go index de87b69563..88af18dd3c 100644 --- a/pkg/kn/commands/route/list_test.go +++ b/pkg/commands/route/list_test.go @@ -25,8 +25,8 @@ import ( "knative.dev/pkg/ptr" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) func fakeRouteList(args []string, response *servingv1.RouteList) (action client_testing.Action, output []string, err error) { diff --git a/pkg/kn/commands/route/route.go b/pkg/commands/route/route.go similarity index 96% rename from pkg/kn/commands/route/route.go rename to pkg/commands/route/route.go index e2d855696e..ad84683cd5 100644 --- a/pkg/kn/commands/route/route.go +++ b/pkg/commands/route/route.go @@ -17,7 +17,7 @@ package route import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) func NewRouteCommand(p *commands.KnParams) *cobra.Command { diff --git a/pkg/kn/commands/secret/create.go b/pkg/commands/secret/create.go similarity index 97% rename from pkg/kn/commands/secret/create.go rename to pkg/commands/secret/create.go index 7bd2abb852..b7c570d4e6 100644 --- a/pkg/kn/commands/secret/create.go +++ b/pkg/commands/secret/create.go @@ -22,9 +22,9 @@ import ( "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) func NewSecretCreateCommand(p *commands.KnParams) *cobra.Command { diff --git a/pkg/kn/commands/secret/create_test.go b/pkg/commands/secret/create_test.go similarity index 97% rename from pkg/kn/commands/secret/create_test.go rename to pkg/commands/secret/create_test.go index d7924f3dfc..ee62167cff 100644 --- a/pkg/kn/commands/secret/create_test.go +++ b/pkg/commands/secret/create_test.go @@ -19,7 +19,7 @@ import ( "gotest.tools/v3/assert" "k8s.io/client-go/kubernetes/fake" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestSecretCreate(t *testing.T) { diff --git a/pkg/kn/commands/secret/delete.go b/pkg/commands/secret/delete.go similarity index 97% rename from pkg/kn/commands/secret/delete.go rename to pkg/commands/secret/delete.go index 4d9de01832..43d44497dd 100644 --- a/pkg/kn/commands/secret/delete.go +++ b/pkg/commands/secret/delete.go @@ -19,7 +19,7 @@ import ( "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) func NewSecretDeleteCommand(p *commands.KnParams) *cobra.Command { diff --git a/pkg/kn/commands/secret/delete_test.go b/pkg/commands/secret/delete_test.go similarity index 100% rename from pkg/kn/commands/secret/delete_test.go rename to pkg/commands/secret/delete_test.go diff --git a/pkg/kn/commands/secret/list.go b/pkg/commands/secret/list.go similarity index 93% rename from pkg/kn/commands/secret/list.go rename to pkg/commands/secret/list.go index 66e8fde37e..98db605b2a 100644 --- a/pkg/kn/commands/secret/list.go +++ b/pkg/commands/secret/list.go @@ -22,14 +22,13 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/kn/commands/flags" - hprinters "knative.dev/client/pkg/printers" - - "knative.dev/client/pkg/kn/commands" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) func NewSecretListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(SecretListHandlers) + listFlags := listfl.NewPrintFlags(SecretListHandlers) cmd := &cobra.Command{ Use: "list", Short: "List secrets", diff --git a/pkg/kn/commands/secret/list_test.go b/pkg/commands/secret/list_test.go similarity index 97% rename from pkg/kn/commands/secret/list_test.go rename to pkg/commands/secret/list_test.go index d65a83f3f6..c5829259d8 100644 --- a/pkg/kn/commands/secret/list_test.go +++ b/pkg/commands/secret/list_test.go @@ -21,7 +21,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestSecretList(t *testing.T) { diff --git a/pkg/kn/commands/secret/secret.go b/pkg/commands/secret/secret.go similarity index 96% rename from pkg/kn/commands/secret/secret.go rename to pkg/commands/secret/secret.go index d1c6a9de4b..120b735601 100644 --- a/pkg/kn/commands/secret/secret.go +++ b/pkg/commands/secret/secret.go @@ -16,7 +16,7 @@ package secret import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) func NewSecretCommand(p *commands.KnParams) *cobra.Command { diff --git a/pkg/kn/commands/secret/secret_test.go b/pkg/commands/secret/secret_test.go similarity index 96% rename from pkg/kn/commands/secret/secret_test.go rename to pkg/commands/secret/secret_test.go index aa7ecce7e5..61b51790c1 100644 --- a/pkg/kn/commands/secret/secret_test.go +++ b/pkg/commands/secret/secret_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" - "knative.dev/client/pkg/kn/commands" - knflags "knative.dev/client/pkg/kn/flags" + "knative.dev/client/pkg/commands" + knflags "knative.dev/client/pkg/flags" ) // Helper methods diff --git a/pkg/kn/commands/service/apply.go b/pkg/commands/service/apply.go similarity index 97% rename from pkg/kn/commands/service/apply.go rename to pkg/commands/service/apply.go index f0771bf1df..762e27cff2 100644 --- a/pkg/kn/commands/service/apply.go +++ b/pkg/commands/service/apply.go @@ -23,8 +23,8 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" ) var applyExample = ` diff --git a/pkg/kn/commands/service/apply_mock_test.go b/pkg/commands/service/apply_mock_test.go similarity index 97% rename from pkg/kn/commands/service/apply_mock_test.go rename to pkg/commands/service/apply_mock_test.go index e6042d067c..ebb87449d2 100644 --- a/pkg/kn/commands/service/apply_mock_test.go +++ b/pkg/commands/service/apply_mock_test.go @@ -26,11 +26,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - knclient "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util/mock" - "knative.dev/client/pkg/wait" + knclient "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util/mock" + "knative.dev/client-pkg/pkg/wait" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestServiceApplyCreateMock(t *testing.T) { diff --git a/pkg/kn/commands/service/configuration_edit_flags.go b/pkg/commands/service/configuration_edit_flags.go similarity index 99% rename from pkg/kn/commands/service/configuration_edit_flags.go rename to pkg/commands/service/configuration_edit_flags.go index d4d7a45d6c..586486df5c 100644 --- a/pkg/kn/commands/service/configuration_edit_flags.go +++ b/pkg/commands/service/configuration_edit_flags.go @@ -24,10 +24,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "knative.dev/serving/pkg/apis/config" - knconfig "knative.dev/client/pkg/kn/config" - knflags "knative.dev/client/pkg/kn/flags" - servinglib "knative.dev/client/pkg/serving" - "knative.dev/client/pkg/util" + servinglib "knative.dev/client-pkg/pkg/serving" + "knative.dev/client-pkg/pkg/util" + knconfig "knative.dev/client/pkg/config" + knflags "knative.dev/client/pkg/flags" network "knative.dev/networking/pkg/apis/networking" "knative.dev/serving/pkg/apis/autoscaling" "knative.dev/serving/pkg/apis/serving" diff --git a/pkg/kn/commands/service/configuration_edit_flags_test.go b/pkg/commands/service/configuration_edit_flags_test.go similarity index 98% rename from pkg/kn/commands/service/configuration_edit_flags_test.go rename to pkg/commands/service/configuration_edit_flags_test.go index 4955fcc942..99d0f71daa 100644 --- a/pkg/kn/commands/service/configuration_edit_flags_test.go +++ b/pkg/commands/service/configuration_edit_flags_test.go @@ -22,9 +22,9 @@ import ( "github.com/spf13/viper" "gotest.tools/v3/assert" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/config" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/config" "knative.dev/serving/pkg/apis/autoscaling" ) diff --git a/pkg/kn/commands/service/create.go b/pkg/commands/service/create.go similarity index 97% rename from pkg/kn/commands/service/create.go rename to pkg/commands/service/create.go index 24bf476ff9..dcf88c316c 100644 --- a/pkg/kn/commands/service/create.go +++ b/pkg/commands/service/create.go @@ -22,11 +22,11 @@ import ( "os" "time" - "knative.dev/client/pkg/config" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - "knative.dev/client/pkg/kn/traffic" - servinglib "knative.dev/client/pkg/serving" + "knative.dev/client-pkg/pkg/config" + servinglib "knative.dev/client-pkg/pkg/serving" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/commands/flags" + "knative.dev/client/pkg/traffic" "knative.dev/serving/pkg/apis/serving" @@ -38,7 +38,7 @@ import ( servingv1 "knative.dev/serving/pkg/apis/serving/v1" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" ) var create_example = ` diff --git a/pkg/kn/commands/service/create_mock_test.go b/pkg/commands/service/create_mock_test.go similarity index 99% rename from pkg/kn/commands/service/create_mock_test.go rename to pkg/commands/service/create_mock_test.go index 67a83a6f23..1f409f4652 100644 --- a/pkg/kn/commands/service/create_mock_test.go +++ b/pkg/commands/service/create_mock_test.go @@ -28,12 +28,12 @@ import ( servingv1 "knative.dev/serving/pkg/apis/serving/v1" - servinglib "knative.dev/client/pkg/serving" - knclient "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util/mock" - "knative.dev/client/pkg/wait" + servinglib "knative.dev/client-pkg/pkg/serving" + knclient "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util/mock" + "knative.dev/client-pkg/pkg/wait" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/ptr" ) diff --git a/pkg/kn/commands/service/create_test.go b/pkg/commands/service/create_test.go similarity index 99% rename from pkg/kn/commands/service/create_test.go rename to pkg/commands/service/create_test.go index 97bd28123f..2a69066c39 100644 --- a/pkg/kn/commands/service/create_test.go +++ b/pkg/commands/service/create_test.go @@ -30,9 +30,9 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/watch" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/wait" + "knative.dev/client/pkg/commands" network "knative.dev/networking/pkg/apis/networking" corev1 "k8s.io/api/core/v1" diff --git a/pkg/kn/commands/service/delete.go b/pkg/commands/service/delete.go similarity index 97% rename from pkg/kn/commands/service/delete.go rename to pkg/commands/service/delete.go index d7524f167d..e5d8453bf9 100644 --- a/pkg/kn/commands/service/delete.go +++ b/pkg/commands/service/delete.go @@ -23,8 +23,8 @@ import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" ) // NewServiceDeleteCommand represent 'service delete' command diff --git a/pkg/kn/commands/service/delete_mock_test.go b/pkg/commands/service/delete_mock_test.go similarity index 97% rename from pkg/kn/commands/service/delete_mock_test.go rename to pkg/commands/service/delete_mock_test.go index 177b80dfd1..f00265378a 100644 --- a/pkg/kn/commands/service/delete_mock_test.go +++ b/pkg/commands/service/delete_mock_test.go @@ -20,9 +20,9 @@ import ( "gotest.tools/v3/assert" - clientservingv1 "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/util/mock" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/mock" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/service/delete_test.go b/pkg/commands/service/delete_test.go similarity index 97% rename from pkg/kn/commands/service/delete_test.go rename to pkg/commands/service/delete_test.go index 7bf6d77ca3..1f0dad521f 100644 --- a/pkg/kn/commands/service/delete_test.go +++ b/pkg/commands/service/delete_test.go @@ -25,9 +25,9 @@ import ( client_testing "k8s.io/client-go/testing" clienttesting "k8s.io/client-go/testing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/wait" + "knative.dev/client/pkg/commands" ) func fakeServiceDelete(args []string) (action client_testing.Action, name string, output string, err error) { diff --git a/pkg/kn/commands/service/describe.go b/pkg/commands/service/describe.go similarity index 98% rename from pkg/kn/commands/service/describe.go rename to pkg/commands/service/describe.go index dc438ef415..54c657d79a 100644 --- a/pkg/kn/commands/service/describe.go +++ b/pkg/commands/service/describe.go @@ -27,17 +27,17 @@ import ( "k8s.io/cli-runtime/pkg/genericclioptions" "knative.dev/serving/pkg/apis/serving" - "knative.dev/client/pkg/kn/commands/revision" - "knative.dev/client/pkg/kn/plugin" - "knative.dev/client/pkg/printers" - clientservingv1 "knative.dev/client/pkg/serving/v1" + "knative.dev/client-pkg/pkg/printers" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands/revision" + "knative.dev/client/pkg/plugin" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" "knative.dev/pkg/apis" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // Command for printing out a description of a service, meant to be consumed by humans diff --git a/pkg/kn/commands/service/describe_test.go b/pkg/commands/service/describe_test.go similarity index 99% rename from pkg/kn/commands/service/describe_test.go rename to pkg/commands/service/describe_test.go index f61f88a80a..1a9ffad0e1 100644 --- a/pkg/kn/commands/service/describe_test.go +++ b/pkg/commands/service/describe_test.go @@ -33,9 +33,9 @@ import ( api_serving "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - client_serving "knative.dev/client/pkg/serving" - knclient "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" + client_serving "knative.dev/client-pkg/pkg/serving" + knclient "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/ptr" ) diff --git a/pkg/kn/commands/service/export.go b/pkg/commands/service/export.go similarity index 98% rename from pkg/kn/commands/service/export.go rename to pkg/commands/service/export.go index 570da9961a..9aac7691f2 100644 --- a/pkg/kn/commands/service/export.go +++ b/pkg/commands/service/export.go @@ -19,7 +19,7 @@ import ( "errors" "fmt" - clientserving "knative.dev/client/pkg/serving" + clientserving "knative.dev/client-pkg/pkg/serving" "sort" "strconv" @@ -31,9 +31,9 @@ import ( "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/cli-runtime/pkg/printers" - clientv1alpha1 "knative.dev/client/pkg/apis/client/v1alpha1" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientv1alpha1 "knative.dev/client-pkg/pkg/apis/client/v1alpha1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/service/export_test.go b/pkg/commands/service/export_test.go similarity index 97% rename from pkg/kn/commands/service/export_test.go rename to pkg/commands/service/export_test.go index 7b2b2ee83f..e29b0c60ce 100644 --- a/pkg/kn/commands/service/export_test.go +++ b/pkg/commands/service/export_test.go @@ -19,15 +19,15 @@ import ( "encoding/json" "testing" - "knative.dev/client/pkg/serving" + "knative.dev/client-pkg/pkg/serving" "gotest.tools/v3/assert" v1 "k8s.io/api/core/v1" - libtest "knative.dev/client/lib/test" - clientv1alpha1 "knative.dev/client/pkg/apis/client/v1alpha1" - knclient "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util/mock" + clientv1alpha1 "knative.dev/client-pkg/pkg/apis/client/v1alpha1" + knclient "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util/mock" + libtest "knative.dev/client-pkg/pkg/util/test" "knative.dev/pkg/ptr" apiserving "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" diff --git a/pkg/kn/commands/service/human_readable_flags.go b/pkg/commands/service/human_readable_flags.go similarity index 97% rename from pkg/kn/commands/service/human_readable_flags.go rename to pkg/commands/service/human_readable_flags.go index a4e2a8fb79..29ae28e4f2 100644 --- a/pkg/kn/commands/service/human_readable_flags.go +++ b/pkg/commands/service/human_readable_flags.go @@ -19,8 +19,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) // ServiceListHandlers adds print handlers for service list command diff --git a/pkg/kn/commands/service/import.go b/pkg/commands/service/import.go similarity index 96% rename from pkg/kn/commands/service/import.go rename to pkg/commands/service/import.go index 64fac87902..f61a794c76 100644 --- a/pkg/kn/commands/service/import.go +++ b/pkg/commands/service/import.go @@ -28,9 +28,9 @@ import ( "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/util/retry" - clientv1alpha1 "knative.dev/client/pkg/apis/client/v1alpha1" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientv1alpha1 "knative.dev/client-pkg/pkg/apis/client/v1alpha1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" "knative.dev/pkg/kmeta" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/service/import_test.go b/pkg/commands/service/import_test.go similarity index 97% rename from pkg/kn/commands/service/import_test.go rename to pkg/commands/service/import_test.go index 04cc0a6c8c..11ecc56fa0 100644 --- a/pkg/kn/commands/service/import_test.go +++ b/pkg/commands/service/import_test.go @@ -23,10 +23,10 @@ import ( "gotest.tools/v3/assert" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knclient "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/util/mock" - "knative.dev/client/pkg/wait" + knclient "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/mock" + "knative.dev/client-pkg/pkg/wait" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/service/list.go b/pkg/commands/service/list.go similarity index 93% rename from pkg/kn/commands/service/list.go rename to pkg/commands/service/list.go index 1212a0db53..6894bce675 100644 --- a/pkg/kn/commands/service/list.go +++ b/pkg/commands/service/list.go @@ -20,16 +20,16 @@ import ( "sort" "github.com/spf13/cobra" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" ) // NewServiceListCommand represents 'kn service list' command func NewServiceListCommand(p *commands.KnParams) *cobra.Command { - serviceListFlags := flags.NewListPrintFlags(ServiceListHandlers) + serviceListFlags := listfl.NewPrintFlags(ServiceListHandlers) serviceListCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/service/list_mock_test.go b/pkg/commands/service/list_mock_test.go similarity index 97% rename from pkg/kn/commands/service/list_mock_test.go rename to pkg/commands/service/list_mock_test.go index e89a973812..40f6e10c96 100644 --- a/pkg/kn/commands/service/list_mock_test.go +++ b/pkg/commands/service/list_mock_test.go @@ -21,9 +21,9 @@ import ( "gotest.tools/v3/assert" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - clientservingv1 "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/util/mock" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/mock" ) func TestServiceListAllNamespaceMock(t *testing.T) { diff --git a/pkg/kn/commands/service/list_test.go b/pkg/commands/service/list_test.go similarity index 99% rename from pkg/kn/commands/service/list_test.go rename to pkg/commands/service/list_test.go index c74539ec04..5283b9b06e 100644 --- a/pkg/kn/commands/service/list_test.go +++ b/pkg/commands/service/list_test.go @@ -26,8 +26,8 @@ import ( "knative.dev/pkg/apis" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) func fakeServiceList(args []string, response *servingv1.ServiceList) (action clienttesting.Action, output []string, err error) { diff --git a/pkg/kn/commands/service/service.go b/pkg/commands/service/service.go similarity index 95% rename from pkg/kn/commands/service/service.go rename to pkg/commands/service/service.go index 6b1afcdf38..c626ead949 100644 --- a/pkg/kn/commands/service/service.go +++ b/pkg/commands/service/service.go @@ -20,9 +20,9 @@ import ( "io" "time" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/wait" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/wait" + "knative.dev/client/pkg/commands" "github.com/spf13/cobra" ) diff --git a/pkg/kn/commands/service/service_test.go b/pkg/commands/service/service_test.go similarity index 93% rename from pkg/kn/commands/service/service_test.go rename to pkg/commands/service/service_test.go index 6b57d4a740..f4d6b75bc0 100644 --- a/pkg/kn/commands/service/service_test.go +++ b/pkg/commands/service/service_test.go @@ -21,9 +21,9 @@ import ( "github.com/spf13/cobra" "k8s.io/client-go/tools/clientcmd" - "knative.dev/client/pkg/kn/commands" - knflags "knative.dev/client/pkg/kn/flags" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" + knflags "knative.dev/client/pkg/flags" ) // Helper methods diff --git a/pkg/kn/commands/service/service_update_mock_test.go b/pkg/commands/service/service_update_mock_test.go similarity index 99% rename from pkg/kn/commands/service/service_update_mock_test.go rename to pkg/commands/service/service_update_mock_test.go index 94c57aad85..788a757850 100644 --- a/pkg/kn/commands/service/service_update_mock_test.go +++ b/pkg/commands/service/service_update_mock_test.go @@ -25,9 +25,9 @@ import ( servingv1 "knative.dev/serving/pkg/apis/serving/v1" - clientserving "knative.dev/client/pkg/serving" - clientservingv1 "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" + clientserving "knative.dev/client-pkg/pkg/serving" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/ptr" ) diff --git a/pkg/kn/commands/service/update.go b/pkg/commands/service/update.go similarity index 96% rename from pkg/kn/commands/service/update.go rename to pkg/commands/service/update.go index 5beefaf8d5..6c2beb65fb 100644 --- a/pkg/kn/commands/service/update.go +++ b/pkg/commands/service/update.go @@ -20,15 +20,15 @@ import ( "time" "github.com/spf13/cobra" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" - "knative.dev/client/pkg/kn/commands/flags" - "knative.dev/client/pkg/kn/traffic" + "knative.dev/client/pkg/commands/flags" + "knative.dev/client/pkg/traffic" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" ) var updateExample = ` diff --git a/pkg/kn/commands/service/update_test.go b/pkg/commands/service/update_test.go similarity index 99% rename from pkg/kn/commands/service/update_test.go rename to pkg/commands/service/update_test.go index 4a695fd693..0cc00b5e7e 100644 --- a/pkg/kn/commands/service/update_test.go +++ b/pkg/commands/service/update_test.go @@ -28,10 +28,10 @@ import ( "gotest.tools/v3/assert" "gotest.tools/v3/assert/cmp" - "knative.dev/client/pkg/kn/commands" - servinglib "knative.dev/client/pkg/serving" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" + servinglib "knative.dev/client-pkg/pkg/serving" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/wait" + "knative.dev/client/pkg/commands" network "knative.dev/networking/pkg/apis/networking" corev1 "k8s.io/api/core/v1" @@ -40,7 +40,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" clienttesting "k8s.io/client-go/testing" - "knative.dev/client/pkg/kn/flags" + "knative.dev/client/pkg/flags" "knative.dev/serving/pkg/apis/serving" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/service/wait.go b/pkg/commands/service/wait.go similarity index 96% rename from pkg/kn/commands/service/wait.go rename to pkg/commands/service/wait.go index 66b39b893e..243f32610c 100644 --- a/pkg/kn/commands/service/wait.go +++ b/pkg/commands/service/wait.go @@ -21,8 +21,8 @@ import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - clientservingv1 "knative.dev/client/pkg/serving/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client/pkg/commands" ) var waitExample = ` diff --git a/pkg/kn/commands/service/wait_test.go b/pkg/commands/service/wait_test.go similarity index 96% rename from pkg/kn/commands/service/wait_test.go rename to pkg/commands/service/wait_test.go index af340e4e07..8c3af600a0 100644 --- a/pkg/kn/commands/service/wait_test.go +++ b/pkg/commands/service/wait_test.go @@ -20,9 +20,9 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/wait" + "knative.dev/client/pkg/commands" servingv1 "knative.dev/serving/pkg/apis/serving/v1" "k8s.io/apimachinery/pkg/runtime" diff --git a/pkg/kn/commands/source/apiserver/apiserver.go b/pkg/commands/source/apiserver/apiserver.go similarity index 96% rename from pkg/kn/commands/source/apiserver/apiserver.go rename to pkg/commands/source/apiserver/apiserver.go index dba6af956b..ae7fb43b47 100644 --- a/pkg/kn/commands/source/apiserver/apiserver.go +++ b/pkg/commands/source/apiserver/apiserver.go @@ -19,8 +19,8 @@ import ( "k8s.io/client-go/tools/clientcmd" clientv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1" - "knative.dev/client/pkg/kn/commands" - v1 "knative.dev/client/pkg/sources/v1" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client/pkg/commands" ) // NewAPIServerCommand for managing ApiServer source diff --git a/pkg/kn/commands/source/apiserver/apiserver_test.go b/pkg/commands/source/apiserver/apiserver_test.go similarity index 95% rename from pkg/kn/commands/source/apiserver/apiserver_test.go rename to pkg/commands/source/apiserver/apiserver_test.go index b3586997ab..c5b2590572 100644 --- a/pkg/kn/commands/source/apiserver/apiserver_test.go +++ b/pkg/commands/source/apiserver/apiserver_test.go @@ -21,10 +21,10 @@ import ( v1 "knative.dev/eventing/pkg/apis/sources/v1" duckv1 "knative.dev/pkg/apis/duck/v1" - kndynamic "knative.dev/client/pkg/dynamic" - clientv1 "knative.dev/client/pkg/sources/v1" + kndynamic "knative.dev/client-pkg/pkg/dynamic" + clientv1 "knative.dev/client-pkg/pkg/sources/v1" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) var blankConfig clientcmd.ClientConfig diff --git a/pkg/kn/commands/source/apiserver/create.go b/pkg/commands/source/apiserver/create.go similarity index 93% rename from pkg/kn/commands/source/apiserver/create.go rename to pkg/commands/source/apiserver/create.go index 3412866f30..faf2e4d343 100644 --- a/pkg/kn/commands/source/apiserver/create.go +++ b/pkg/commands/source/apiserver/create.go @@ -19,17 +19,17 @@ import ( "fmt" "github.com/spf13/cobra" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // NewAPIServerCreateCommand for creating source func NewAPIServerCreateCommand(p *commands.KnParams) *cobra.Command { var updateFlags APIServerSourceUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "create NAME --resource RESOURCE --sink SINK", diff --git a/pkg/kn/commands/source/apiserver/create_test.go b/pkg/commands/source/apiserver/create_test.go similarity index 95% rename from pkg/kn/commands/source/apiserver/create_test.go rename to pkg/commands/source/apiserver/create_test.go index 70b3c818ad..04bca9ad15 100644 --- a/pkg/kn/commands/source/apiserver/create_test.go +++ b/pkg/commands/source/apiserver/create_test.go @@ -21,9 +21,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestCreateApiServerSource(t *testing.T) { diff --git a/pkg/kn/commands/source/apiserver/delete.go b/pkg/commands/source/apiserver/delete.go similarity index 97% rename from pkg/kn/commands/source/apiserver/delete.go rename to pkg/commands/source/apiserver/delete.go index be7f2fb7f0..b314f9703e 100644 --- a/pkg/kn/commands/source/apiserver/delete.go +++ b/pkg/commands/source/apiserver/delete.go @@ -20,7 +20,7 @@ import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewAPIServerDeleteCommand for deleting source diff --git a/pkg/kn/commands/source/apiserver/delete_test.go b/pkg/commands/source/apiserver/delete_test.go similarity index 96% rename from pkg/kn/commands/source/apiserver/delete_test.go rename to pkg/commands/source/apiserver/delete_test.go index f8efa39b75..beee96e455 100644 --- a/pkg/kn/commands/source/apiserver/delete_test.go +++ b/pkg/commands/source/apiserver/delete_test.go @@ -20,8 +20,8 @@ import ( "gotest.tools/v3/assert" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestApiServerSourceDelete(t *testing.T) { diff --git a/pkg/kn/commands/source/apiserver/describe.go b/pkg/commands/source/apiserver/describe.go similarity index 95% rename from pkg/kn/commands/source/apiserver/describe.go rename to pkg/commands/source/apiserver/describe.go index ad692bc14e..3a321d46bd 100644 --- a/pkg/kn/commands/source/apiserver/describe.go +++ b/pkg/commands/source/apiserver/describe.go @@ -21,10 +21,10 @@ import ( "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" + "knative.dev/client/pkg/describe" - "knative.dev/client/lib/printing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" v1 "knative.dev/eventing/pkg/apis/sources/v1" ) @@ -85,7 +85,7 @@ func NewAPIServerDescribeCommand(p *commands.KnParams) *cobra.Command { return err } - printing.DescribeSink(dw, "Sink", apiSource.Namespace, &apiSource.Spec.Sink) + describe.Sink(dw, "Sink", apiSource.Namespace, &apiSource.Spec.Sink) dw.WriteLine() if err := dw.Flush(); err != nil { return err diff --git a/pkg/kn/commands/source/apiserver/describe_test.go b/pkg/commands/source/apiserver/describe_test.go similarity index 98% rename from pkg/kn/commands/source/apiserver/describe_test.go rename to pkg/commands/source/apiserver/describe_test.go index 31bbb8d384..f190aac0fc 100644 --- a/pkg/kn/commands/source/apiserver/describe_test.go +++ b/pkg/commands/source/apiserver/describe_test.go @@ -20,8 +20,8 @@ import ( "gotest.tools/v3/assert" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" ) diff --git a/pkg/kn/commands/source/apiserver/flags.go b/pkg/commands/source/apiserver/flags.go similarity index 98% rename from pkg/kn/commands/source/apiserver/flags.go rename to pkg/commands/source/apiserver/flags.go index f891d36ba7..fdc9475bff 100644 --- a/pkg/kn/commands/source/apiserver/flags.go +++ b/pkg/commands/source/apiserver/flags.go @@ -25,13 +25,13 @@ import ( "k8s.io/apimachinery/pkg/runtime" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + "knative.dev/client/pkg/commands" metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" - hprinters "knative.dev/client/pkg/printers" - "knative.dev/client/pkg/util" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client-pkg/pkg/util" ) const ( @@ -206,7 +206,7 @@ func printSource(source *sourcesv1.ApiServerSource, options hprinters.PrintOptio // Not moving to SinkToString() as it references v1beta1.Destination // This source is going to be moved/removed soon to sourcesv1, so no need to move // it now - sink := flags.SinkToString(source.Spec.Sink) + sink := sinkfl.SinkToString(source.Spec.Sink) if options.AllNamespaces { row.Cells = append(row.Cells, source.Namespace) diff --git a/pkg/kn/commands/source/apiserver/flags_test.go b/pkg/commands/source/apiserver/flags_test.go similarity index 100% rename from pkg/kn/commands/source/apiserver/flags_test.go rename to pkg/commands/source/apiserver/flags_test.go diff --git a/pkg/kn/commands/source/apiserver/list.go b/pkg/commands/source/apiserver/list.go similarity index 92% rename from pkg/kn/commands/source/apiserver/list.go rename to pkg/commands/source/apiserver/list.go index edf701e7d8..84cd596602 100644 --- a/pkg/kn/commands/source/apiserver/list.go +++ b/pkg/commands/source/apiserver/list.go @@ -18,14 +18,14 @@ import ( "fmt" "github.com/spf13/cobra" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" ) // NewAPIServerListCommand is for listing ApiServer source COs func NewAPIServerListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(APIServerSourceListHandlers) + listFlags := listfl.NewPrintFlags(APIServerSourceListHandlers) listCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/source/apiserver/list_test.go b/pkg/commands/source/apiserver/list_test.go similarity index 97% rename from pkg/kn/commands/source/apiserver/list_test.go rename to pkg/commands/source/apiserver/list_test.go index 4077c79350..1d3702653a 100644 --- a/pkg/kn/commands/source/apiserver/list_test.go +++ b/pkg/commands/source/apiserver/list_test.go @@ -23,8 +23,8 @@ import ( v1 "knative.dev/eventing/pkg/apis/sources/v1" - v12 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v12 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestListAPIServerSource(t *testing.T) { diff --git a/pkg/kn/commands/source/apiserver/update.go b/pkg/commands/source/apiserver/update.go similarity index 94% rename from pkg/kn/commands/source/apiserver/update.go rename to pkg/commands/source/apiserver/update.go index f369a8aafd..dc0e84c153 100644 --- a/pkg/kn/commands/source/apiserver/update.go +++ b/pkg/commands/source/apiserver/update.go @@ -19,17 +19,17 @@ import ( "fmt" "github.com/spf13/cobra" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // NewAPIServerUpdateCommand for managing source update func NewAPIServerUpdateCommand(p *commands.KnParams) *cobra.Command { var updateFlags APIServerSourceUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "update NAME", diff --git a/pkg/kn/commands/source/apiserver/update_test.go b/pkg/commands/source/apiserver/update_test.go similarity index 96% rename from pkg/kn/commands/source/apiserver/update_test.go rename to pkg/commands/source/apiserver/update_test.go index 594e07525e..c11a25d7bc 100644 --- a/pkg/kn/commands/source/apiserver/update_test.go +++ b/pkg/commands/source/apiserver/update_test.go @@ -24,9 +24,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestApiServerSourceUpdate(t *testing.T) { diff --git a/pkg/kn/commands/source/binding/binding.go b/pkg/commands/source/binding/binding.go similarity index 96% rename from pkg/kn/commands/source/binding/binding.go rename to pkg/commands/source/binding/binding.go index 403ce143ad..3d07054588 100644 --- a/pkg/kn/commands/source/binding/binding.go +++ b/pkg/commands/source/binding/binding.go @@ -22,8 +22,8 @@ import ( v1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1" "knative.dev/pkg/tracker" - "knative.dev/client/pkg/kn/commands" - clientsourcesv1alpha1 "knative.dev/client/pkg/sources/v1" + clientsourcesv1alpha1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client/pkg/commands" ) // NewBindingCommand is the root command for all binding related commands diff --git a/pkg/kn/commands/source/binding/binding_test.go b/pkg/commands/source/binding/binding_test.go similarity index 95% rename from pkg/kn/commands/source/binding/binding_test.go rename to pkg/commands/source/binding/binding_test.go index d68105ba7b..1301f65776 100644 --- a/pkg/kn/commands/source/binding/binding_test.go +++ b/pkg/commands/source/binding/binding_test.go @@ -22,9 +22,9 @@ import ( sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" duckv1 "knative.dev/pkg/apis/duck/v1" - kndynamic "knative.dev/client/pkg/dynamic" - "knative.dev/client/pkg/kn/commands" - clientv1 "knative.dev/client/pkg/sources/v1" + kndynamic "knative.dev/client-pkg/pkg/dynamic" + clientv1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client/pkg/commands" ) // Helper methods diff --git a/pkg/kn/commands/source/binding/create.go b/pkg/commands/source/binding/create.go similarity index 93% rename from pkg/kn/commands/source/binding/create.go rename to pkg/commands/source/binding/create.go index 13f868a033..d4598d5d35 100644 --- a/pkg/kn/commands/source/binding/create.go +++ b/pkg/commands/source/binding/create.go @@ -19,17 +19,17 @@ import ( "fmt" "github.com/spf13/cobra" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - v1alpha12 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1alpha12 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // NewBindingCreateCommand is for creating sink bindings func NewBindingCreateCommand(p *commands.KnParams) *cobra.Command { var bindingFlags bindingUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "create NAME --subject SUBJECT --sink SINK", diff --git a/pkg/kn/commands/source/binding/create_test.go b/pkg/commands/source/binding/create_test.go similarity index 94% rename from pkg/kn/commands/source/binding/create_test.go rename to pkg/commands/source/binding/create_test.go index e11a6c6cba..a1ae21d29c 100644 --- a/pkg/kn/commands/source/binding/create_test.go +++ b/pkg/commands/source/binding/create_test.go @@ -19,10 +19,10 @@ import ( "gotest.tools/v3/assert" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - v1 "knative.dev/client/pkg/sources/v1" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + v1 "knative.dev/client-pkg/pkg/sources/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestSimpleCreateBinding(t *testing.T) { diff --git a/pkg/kn/commands/source/binding/delete.go b/pkg/commands/source/binding/delete.go similarity index 97% rename from pkg/kn/commands/source/binding/delete.go rename to pkg/commands/source/binding/delete.go index ff1cf0dc27..5f76c96f96 100644 --- a/pkg/kn/commands/source/binding/delete.go +++ b/pkg/commands/source/binding/delete.go @@ -19,7 +19,7 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewBindingDeleteCommand is for deleting a sink binding diff --git a/pkg/kn/commands/source/binding/delete_test.go b/pkg/commands/source/binding/delete_test.go similarity index 95% rename from pkg/kn/commands/source/binding/delete_test.go rename to pkg/commands/source/binding/delete_test.go index 33bba3484c..c0a8f3c5b4 100644 --- a/pkg/kn/commands/source/binding/delete_test.go +++ b/pkg/commands/source/binding/delete_test.go @@ -20,8 +20,8 @@ import ( "gotest.tools/v3/assert" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestSimpleDelete(t *testing.T) { diff --git a/pkg/kn/commands/source/binding/describe.go b/pkg/commands/source/binding/describe.go similarity index 96% rename from pkg/kn/commands/source/binding/describe.go rename to pkg/commands/source/binding/describe.go index 152e2c5687..70ed37315d 100644 --- a/pkg/kn/commands/source/binding/describe.go +++ b/pkg/commands/source/binding/describe.go @@ -21,12 +21,12 @@ import ( "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" + "knative.dev/client/pkg/describe" v1 "knative.dev/eventing/pkg/apis/sources/v1" "knative.dev/pkg/tracker" - "knative.dev/client/lib/printing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) var describeExample = ` @@ -105,7 +105,7 @@ func NewBindingDescribeCommand(p *commands.KnParams) *cobra.Command { func writeSinkBinding(dw printers.PrefixWriter, binding *v1.SinkBinding, printDetails bool) { commands.WriteMetadata(dw, &binding.ObjectMeta, printDetails) writeSubject(dw, binding.Namespace, &binding.Spec.Subject) - printing.DescribeSink(dw, "Sink", binding.Namespace, &binding.Spec.Sink) + describe.Sink(dw, "Sink", binding.Namespace, &binding.Spec.Sink) if binding.Spec.CloudEventOverrides != nil && binding.Spec.CloudEventOverrides.Extensions != nil { writeCeOverrides(dw, binding.Spec.CloudEventOverrides.Extensions) } diff --git a/pkg/kn/commands/source/binding/describe_test.go b/pkg/commands/source/binding/describe_test.go similarity index 98% rename from pkg/kn/commands/source/binding/describe_test.go rename to pkg/commands/source/binding/describe_test.go index 90f7025bdd..394a7d9dfd 100644 --- a/pkg/kn/commands/source/binding/describe_test.go +++ b/pkg/commands/source/binding/describe_test.go @@ -26,8 +26,8 @@ import ( duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/tracker" - clientv1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + clientv1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) var ( diff --git a/pkg/kn/commands/source/binding/flags.go b/pkg/commands/source/binding/flags.go similarity index 95% rename from pkg/kn/commands/source/binding/flags.go rename to pkg/commands/source/binding/flags.go index f8a2ab42cd..3f90976db2 100644 --- a/pkg/kn/commands/source/binding/flags.go +++ b/pkg/commands/source/binding/flags.go @@ -18,10 +18,10 @@ import ( "github.com/spf13/cobra" metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" v1 "knative.dev/eventing/pkg/apis/sources/v1" ) @@ -68,7 +68,7 @@ func printSinkBinding(binding *v1.SinkBinding, options hprinters.PrintOptions) ( name := binding.Name subject := subjectToString(binding.Spec.Subject) - sink := flags.SinkToString(binding.Spec.Sink) + sink := sinkfl.SinkToString(binding.Spec.Sink) age := commands.TranslateTimestampSince(binding.CreationTimestamp) conditions := commands.ConditionsValue(binding.Status.Conditions) ready := commands.ReadyCondition(binding.Status.Conditions) diff --git a/pkg/kn/commands/source/binding/list.go b/pkg/commands/source/binding/list.go similarity index 92% rename from pkg/kn/commands/source/binding/list.go rename to pkg/commands/source/binding/list.go index cf8bb0234e..92dece7524 100644 --- a/pkg/kn/commands/source/binding/list.go +++ b/pkg/commands/source/binding/list.go @@ -18,13 +18,13 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + "knative.dev/client/pkg/commands" ) // NewBindingListCommand is for listing sink bindings func NewBindingListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(BindingListHandlers) + listFlags := listfl.NewPrintFlags(BindingListHandlers) cmd := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/source/binding/list_test.go b/pkg/commands/source/binding/list_test.go similarity index 96% rename from pkg/kn/commands/source/binding/list_test.go rename to pkg/commands/source/binding/list_test.go index f5ee82c9fb..bf3bc705be 100644 --- a/pkg/kn/commands/source/binding/list_test.go +++ b/pkg/commands/source/binding/list_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" v1 "knative.dev/eventing/pkg/apis/sources/v1" - clientv1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + clientv1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestListBindingSimple(t *testing.T) { diff --git a/pkg/kn/commands/source/binding/update.go b/pkg/commands/source/binding/update.go similarity index 93% rename from pkg/kn/commands/source/binding/update.go rename to pkg/commands/source/binding/update.go index 3886e3f3d5..4b8b85430d 100644 --- a/pkg/kn/commands/source/binding/update.go +++ b/pkg/commands/source/binding/update.go @@ -19,17 +19,17 @@ import ( "fmt" "github.com/spf13/cobra" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - v1alpha12 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1alpha12 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // NewBindingUpdateCommand prepares the command for a sink binding update func NewBindingUpdateCommand(p *commands.KnParams) *cobra.Command { var bindingFlags bindingUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "update NAME", diff --git a/pkg/kn/commands/source/binding/update_test.go b/pkg/commands/source/binding/update_test.go similarity index 95% rename from pkg/kn/commands/source/binding/update_test.go rename to pkg/commands/source/binding/update_test.go index 8edaf25b63..c6b095e1dc 100644 --- a/pkg/kn/commands/source/binding/update_test.go +++ b/pkg/commands/source/binding/update_test.go @@ -23,9 +23,9 @@ import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - clientsourcesv1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + clientsourcesv1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestSimpleBindingUpdate(t *testing.T) { diff --git a/pkg/kn/commands/source/container/container.go b/pkg/commands/source/container/container.go similarity index 96% rename from pkg/kn/commands/source/container/container.go rename to pkg/commands/source/container/container.go index 3cfa0942a3..6cb3284141 100644 --- a/pkg/kn/commands/source/container/container.go +++ b/pkg/commands/source/container/container.go @@ -19,8 +19,8 @@ package container import ( "github.com/spf13/cobra" "k8s.io/client-go/tools/clientcmd" - "knative.dev/client/pkg/kn/commands" - v1 "knative.dev/client/pkg/sources/v1" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client/pkg/commands" clientv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1" ) diff --git a/pkg/kn/commands/source/container/container_test.go b/pkg/commands/source/container/container_test.go similarity index 95% rename from pkg/kn/commands/source/container/container_test.go rename to pkg/commands/source/container/container_test.go index 10dadf3259..5fff1ebcaa 100644 --- a/pkg/kn/commands/source/container/container_test.go +++ b/pkg/commands/source/container/container_test.go @@ -25,10 +25,10 @@ import ( v1 "knative.dev/eventing/pkg/apis/sources/v1" duckv1 "knative.dev/pkg/apis/duck/v1" - kndynamic "knative.dev/client/pkg/dynamic" - clientv1 "knative.dev/client/pkg/sources/v1" + kndynamic "knative.dev/client-pkg/pkg/dynamic" + clientv1 "knative.dev/client-pkg/pkg/sources/v1" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) var blankConfig clientcmd.ClientConfig diff --git a/pkg/kn/commands/source/container/create.go b/pkg/commands/source/container/create.go similarity index 92% rename from pkg/kn/commands/source/container/create.go rename to pkg/commands/source/container/create.go index d7f817519a..376c278d80 100644 --- a/pkg/kn/commands/source/container/create.go +++ b/pkg/commands/source/container/create.go @@ -22,18 +22,18 @@ import ( "os" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands/flags" - knflags "knative.dev/client/pkg/kn/flags" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + knflags "knative.dev/client/pkg/flags" corev1 "k8s.io/api/core/v1" - "knative.dev/client/pkg/kn/commands" - v1 "knative.dev/client/pkg/sources/v1" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client/pkg/commands" ) // NewContainerCreateCommand for creating source func NewContainerCreateCommand(p *commands.KnParams) *cobra.Command { var podFlags knflags.PodSpecFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "create NAME --image IMAGE --sink SINK", diff --git a/pkg/kn/commands/source/container/create_test.go b/pkg/commands/source/container/create_test.go similarity index 96% rename from pkg/kn/commands/source/container/create_test.go rename to pkg/commands/source/container/create_test.go index 0a30bd07fb..397300bdaf 100644 --- a/pkg/kn/commands/source/container/create_test.go +++ b/pkg/commands/source/container/create_test.go @@ -23,9 +23,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestCreateContainerSource(t *testing.T) { diff --git a/pkg/kn/commands/source/container/delete.go b/pkg/commands/source/container/delete.go similarity index 97% rename from pkg/kn/commands/source/container/delete.go rename to pkg/commands/source/container/delete.go index 0354233923..49a7464a15 100644 --- a/pkg/kn/commands/source/container/delete.go +++ b/pkg/commands/source/container/delete.go @@ -22,7 +22,7 @@ import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewContainerDeleteCommand for deleting source diff --git a/pkg/kn/commands/source/container/delete_test.go b/pkg/commands/source/container/delete_test.go similarity index 96% rename from pkg/kn/commands/source/container/delete_test.go rename to pkg/commands/source/container/delete_test.go index d724524361..8a6fb81f1d 100644 --- a/pkg/kn/commands/source/container/delete_test.go +++ b/pkg/commands/source/container/delete_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestContainerSourceDelete(t *testing.T) { diff --git a/pkg/kn/commands/source/container/describe.go b/pkg/commands/source/container/describe.go similarity index 95% rename from pkg/kn/commands/source/container/describe.go rename to pkg/commands/source/container/describe.go index 7e5b1efe8b..03850e4079 100644 --- a/pkg/kn/commands/source/container/describe.go +++ b/pkg/commands/source/container/describe.go @@ -22,9 +22,9 @@ import ( "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" - "knative.dev/client/lib/printing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/describe" v1 "knative.dev/eventing/pkg/apis/sources/v1" ) @@ -67,7 +67,7 @@ func NewContainerDescribeCommand(p *commands.KnParams) *cobra.Command { return err } - printing.DescribeSink(dw, "Sink", source.Namespace, &source.Spec.Sink) + describe.Sink(dw, "Sink", source.Namespace, &source.Spec.Sink) dw.WriteLine() if err := dw.Flush(); err != nil { return err diff --git a/pkg/kn/commands/source/container/describe_test.go b/pkg/commands/source/container/describe_test.go similarity index 96% rename from pkg/kn/commands/source/container/describe_test.go rename to pkg/commands/source/container/describe_test.go index 9f32e40cef..21656ff203 100644 --- a/pkg/kn/commands/source/container/describe_test.go +++ b/pkg/commands/source/container/describe_test.go @@ -21,8 +21,8 @@ import ( "testing" "gotest.tools/v3/assert" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" ) func TestDescribeError(t *testing.T) { diff --git a/pkg/kn/commands/source/container/human_readable_flags.go b/pkg/commands/source/container/human_readable_flags.go similarity index 96% rename from pkg/kn/commands/source/container/human_readable_flags.go rename to pkg/commands/source/container/human_readable_flags.go index 1454f9657f..3a3ab15b56 100644 --- a/pkg/kn/commands/source/container/human_readable_flags.go +++ b/pkg/commands/source/container/human_readable_flags.go @@ -21,14 +21,13 @@ import ( "strings" "k8s.io/apimachinery/pkg/runtime" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" v1 "knative.dev/eventing/pkg/apis/sources/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" + "knative.dev/client/pkg/commands" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" ) // ContainerSourceListHandlers handles printing human readable table for `kn source apiserver list` command's output @@ -63,7 +62,7 @@ func printSource(source *v1.ContainerSource, options hprinters.PrintOptions) ([] // Not moving to SinkToString() as it references v1beta1.Destination // This source is going to be moved/removed soon to v1, so no need to move // it now - sink := flags.SinkToString(source.Spec.Sink) + sink := sinkfl.SinkToString(source.Spec.Sink) if options.AllNamespaces { row.Cells = append(row.Cells, source.Namespace) diff --git a/pkg/kn/commands/source/container/list.go b/pkg/commands/source/container/list.go similarity index 91% rename from pkg/kn/commands/source/container/list.go rename to pkg/commands/source/container/list.go index a28a1d52dd..a694ba6708 100644 --- a/pkg/kn/commands/source/container/list.go +++ b/pkg/commands/source/container/list.go @@ -20,14 +20,14 @@ import ( "fmt" "github.com/spf13/cobra" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" ) // NewContainerListCommand is for listing Container sources func NewContainerListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(ContainerSourceListHandlers) + listFlags := listfl.NewPrintFlags(ContainerSourceListHandlers) listCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/source/container/list_test.go b/pkg/commands/source/container/list_test.go similarity index 97% rename from pkg/kn/commands/source/container/list_test.go rename to pkg/commands/source/container/list_test.go index 718a279d2f..bdb31a0559 100644 --- a/pkg/kn/commands/source/container/list_test.go +++ b/pkg/commands/source/container/list_test.go @@ -22,8 +22,8 @@ import ( "knative.dev/eventing/pkg/client/clientset/versioned/scheme" "gotest.tools/v3/assert" - v12 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + v12 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" v1 "knative.dev/eventing/pkg/apis/sources/v1" ) diff --git a/pkg/kn/commands/source/container/update.go b/pkg/commands/source/container/update.go similarity index 92% rename from pkg/kn/commands/source/container/update.go rename to pkg/commands/source/container/update.go index e0e1816cd5..93db9d29d0 100644 --- a/pkg/kn/commands/source/container/update.go +++ b/pkg/commands/source/container/update.go @@ -22,19 +22,19 @@ import ( "os" "github.com/spf13/cobra" - "knative.dev/client/pkg/config" - "knative.dev/client/pkg/kn/commands/flags" - knflags "knative.dev/client/pkg/kn/flags" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + "knative.dev/client-pkg/pkg/config" + knflags "knative.dev/client/pkg/flags" - "knative.dev/client/pkg/kn/commands" - v1 "knative.dev/client/pkg/sources/v1" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client/pkg/commands" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" ) // NewContainerUpdateCommand for managing source update func NewContainerUpdateCommand(p *commands.KnParams) *cobra.Command { var podFlags knflags.PodSpecFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "update NAME --image IMAGE", diff --git a/pkg/kn/commands/source/container/update_test.go b/pkg/commands/source/container/update_test.go similarity index 96% rename from pkg/kn/commands/source/container/update_test.go rename to pkg/commands/source/container/update_test.go index a2bbd5f0b8..00accc2458 100644 --- a/pkg/kn/commands/source/container/update_test.go +++ b/pkg/commands/source/container/update_test.go @@ -22,9 +22,9 @@ import ( "gotest.tools/v3/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - v1 "knative.dev/client/pkg/sources/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client-pkg/pkg/util" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/source/duck/multisourcelist.go b/pkg/commands/source/duck/multisourcelist.go similarity index 95% rename from pkg/kn/commands/source/duck/multisourcelist.go rename to pkg/commands/source/duck/multisourcelist.go index 28d3346233..dbee6bb9b4 100644 --- a/pkg/kn/commands/source/duck/multisourcelist.go +++ b/pkg/commands/source/duck/multisourcelist.go @@ -19,6 +19,7 @@ import ( "fmt" "strings" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -26,11 +27,10 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" - duck "knative.dev/pkg/apis/duck" + "knative.dev/pkg/apis/duck" duckv1 "knative.dev/pkg/apis/duck/v1" - "knative.dev/client/pkg/kn/commands" - knflags "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" ) // Source struct holds common properties between different eventing sources @@ -157,17 +157,17 @@ func findSink(source *unstructured.Unstructured) string { case "ApiServerSource": var apiSource sourcesv1.ApiServerSource if err := duck.FromUnstructured(source, &apiSource); err == nil { - return knflags.SinkToString(apiSource.Spec.Sink) + return sinkfl.SinkToString(apiSource.Spec.Sink) } case "SinkBinding": var binding sourcesv1.SinkBinding if err := duck.FromUnstructured(source, &binding); err == nil { - return knflags.SinkToString(binding.Spec.Sink) + return sinkfl.SinkToString(binding.Spec.Sink) } case "PingSource": var pingSource sourcesv1beta2.PingSource if err := duck.FromUnstructured(source, &pingSource); err == nil { - return knflags.SinkToString(pingSource.Spec.Sink) + return sinkfl.SinkToString(pingSource.Spec.Sink) } default: sink, err := sinkFromUnstructured(source) @@ -177,7 +177,7 @@ func findSink(source *unstructured.Unstructured) string { if sink == nil { return "" } - return knflags.SinkToString(*sink) + return sinkfl.SinkToString(*sink) } return "" } diff --git a/pkg/kn/commands/source/duck/multisourcelist_test.go b/pkg/commands/source/duck/multisourcelist_test.go similarity index 99% rename from pkg/kn/commands/source/duck/multisourcelist_test.go rename to pkg/commands/source/duck/multisourcelist_test.go index dad6c43fc4..91f6ed2e7c 100644 --- a/pkg/kn/commands/source/duck/multisourcelist_test.go +++ b/pkg/commands/source/duck/multisourcelist_test.go @@ -21,7 +21,7 @@ import ( "gotest.tools/v3/assert" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - //"knative.dev/client/pkg/util" + //"knative.dev/client-pkg/pkg/util" ) func TestToSource(t *testing.T) { diff --git a/pkg/kn/commands/source/human_readable_flags.go b/pkg/commands/source/human_readable_flags.go similarity index 98% rename from pkg/kn/commands/source/human_readable_flags.go rename to pkg/commands/source/human_readable_flags.go index c86045cff6..8e0ae9905b 100644 --- a/pkg/kn/commands/source/human_readable_flags.go +++ b/pkg/commands/source/human_readable_flags.go @@ -22,8 +22,8 @@ import ( metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" - clientduck "knative.dev/client/pkg/kn/commands/source/duck" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + clientduck "knative.dev/client/pkg/commands/source/duck" ) var sourceTypeDescription = map[string]string{ diff --git a/pkg/kn/commands/source/list.go b/pkg/commands/source/list.go similarity index 90% rename from pkg/kn/commands/source/list.go rename to pkg/commands/source/list.go index 82f2519075..83532e17c0 100644 --- a/pkg/kn/commands/source/list.go +++ b/pkg/commands/source/list.go @@ -17,16 +17,17 @@ package source import ( "fmt" - "knative.dev/client/pkg/sources" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + "knative.dev/client-pkg/pkg/sources" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/client/pkg/dynamic" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - "knative.dev/client/pkg/kn/commands/source/duck" + "knative.dev/client-pkg/pkg/dynamic" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/commands/flags" + "knative.dev/client/pkg/commands/source/duck" ) const ( @@ -48,7 +49,7 @@ var listExample = ` // NewListCommand defines and processes `kn source list` func NewListCommand(p *commands.KnParams) *cobra.Command { filterFlags := &flags.SourceTypeFilters{} - listFlags := flags.NewListPrintFlags(ListHandlers) + listFlags := listfl.NewPrintFlags(ListHandlers) listCommand := &cobra.Command{ Use: "list", Short: "List event sources", diff --git a/pkg/kn/commands/source/list_test.go b/pkg/commands/source/list_test.go similarity index 98% rename from pkg/kn/commands/source/list_test.go rename to pkg/commands/source/list_test.go index 9a568f6afb..dae72bf076 100644 --- a/pkg/kn/commands/source/list_test.go +++ b/pkg/commands/source/list_test.go @@ -19,15 +19,15 @@ import ( "strings" "testing" - "knative.dev/client/pkg/dynamic/fake" + "knative.dev/client-pkg/pkg/dynamic/fake" "gotest.tools/v3/assert" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) const ( diff --git a/pkg/kn/commands/source/list_types.go b/pkg/commands/source/list_types.go similarity index 91% rename from pkg/kn/commands/source/list_types.go rename to pkg/commands/source/list_types.go index f0fbb1108b..f3ae78f6da 100644 --- a/pkg/kn/commands/source/list_types.go +++ b/pkg/commands/source/list_types.go @@ -17,21 +17,21 @@ package source import ( "context" - "knative.dev/client/pkg/sources" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + "knative.dev/client-pkg/pkg/sources" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/client/pkg/dynamic" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client-pkg/pkg/dynamic" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client/pkg/commands" ) // NewListTypesCommand defines and processes `kn source list-types` func NewListTypesCommand(p *commands.KnParams) *cobra.Command { - listTypesFlags := flags.NewListPrintFlags(ListTypesHandlers) + listTypesFlags := listfl.NewPrintFlags(ListTypesHandlers) listTypesCommand := &cobra.Command{ Use: "list-types", Short: "List event source types", diff --git a/pkg/kn/commands/source/ping/create.go b/pkg/commands/source/ping/create.go similarity index 92% rename from pkg/kn/commands/source/ping/create.go rename to pkg/commands/source/ping/create.go index e566936a31..d6840d4a3c 100644 --- a/pkg/kn/commands/source/ping/create.go +++ b/pkg/commands/source/ping/create.go @@ -19,17 +19,17 @@ import ( "fmt" "github.com/spf13/cobra" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - clientsourcesv1beta2 "knative.dev/client/pkg/sources/v1beta2" - "knative.dev/client/pkg/util" + clientsourcesv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // NewPingCreateCommand is for creating Ping source COs func NewPingCreateCommand(p *commands.KnParams) *cobra.Command { var updateFlags pingUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "create NAME --sink SINK", diff --git a/pkg/kn/commands/source/ping/create_test.go b/pkg/commands/source/ping/create_test.go similarity index 96% rename from pkg/kn/commands/source/ping/create_test.go rename to pkg/commands/source/ping/create_test.go index 00add675c5..39a8c5a467 100644 --- a/pkg/kn/commands/source/ping/create_test.go +++ b/pkg/commands/source/ping/create_test.go @@ -21,10 +21,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - clientsourcesv1beta2 "knative.dev/client/pkg/sources/v1beta2" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + clientsourcesv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestSimpleCreatePingSource(t *testing.T) { diff --git a/pkg/kn/commands/source/ping/delete.go b/pkg/commands/source/ping/delete.go similarity index 97% rename from pkg/kn/commands/source/ping/delete.go rename to pkg/commands/source/ping/delete.go index b7e8699b02..e789cd9a1e 100644 --- a/pkg/kn/commands/source/ping/delete.go +++ b/pkg/commands/source/ping/delete.go @@ -19,7 +19,7 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewPingDeleteCommand is for deleting a Ping source diff --git a/pkg/kn/commands/source/ping/delete_test.go b/pkg/commands/source/ping/delete_test.go similarity index 94% rename from pkg/kn/commands/source/ping/delete_test.go rename to pkg/commands/source/ping/delete_test.go index 927dd65963..e1baca95b1 100644 --- a/pkg/kn/commands/source/ping/delete_test.go +++ b/pkg/commands/source/ping/delete_test.go @@ -19,9 +19,9 @@ import ( "testing" "gotest.tools/v3/assert" - clientsourcesv1beta2 "knative.dev/client/pkg/sources/v1beta2" + clientsourcesv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestSimpleDelete(t *testing.T) { diff --git a/pkg/kn/commands/source/ping/describe.go b/pkg/commands/source/ping/describe.go similarity index 95% rename from pkg/kn/commands/source/ping/describe.go rename to pkg/commands/source/ping/describe.go index b6fc2c119e..5a78ea0457 100644 --- a/pkg/kn/commands/source/ping/describe.go +++ b/pkg/commands/source/ping/describe.go @@ -20,10 +20,10 @@ import ( "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" + "knative.dev/client/pkg/describe" - "knative.dev/client/lib/printing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" clientsourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" ) @@ -85,7 +85,7 @@ func NewPingDescribeCommand(p *commands.KnParams) *cobra.Command { } // Revisions summary info - printing.DescribeSink(dw, "Sink", pingSource.Namespace, &pingSource.Spec.Sink) + describe.Sink(dw, "Sink", pingSource.Namespace, &pingSource.Spec.Sink) dw.WriteLine() if err := dw.Flush(); err != nil { return err diff --git a/pkg/kn/commands/source/ping/describe_test.go b/pkg/commands/source/ping/describe_test.go similarity index 97% rename from pkg/kn/commands/source/ping/describe_test.go rename to pkg/commands/source/ping/describe_test.go index de3653dc26..4100e20c59 100644 --- a/pkg/kn/commands/source/ping/describe_test.go +++ b/pkg/commands/source/ping/describe_test.go @@ -23,8 +23,8 @@ import ( sourcesv1beta "knative.dev/eventing/pkg/apis/sources/v1beta2" duckv1 "knative.dev/pkg/apis/duck/v1" - clientv1beta2 "knative.dev/client/pkg/sources/v1beta2" - "knative.dev/client/pkg/util" + clientv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/apis" ) diff --git a/pkg/kn/commands/source/ping/flags.go b/pkg/commands/source/ping/flags.go similarity index 98% rename from pkg/kn/commands/source/ping/flags.go rename to pkg/commands/source/ping/flags.go index 65cd916d0d..81117a867a 100644 --- a/pkg/kn/commands/source/ping/flags.go +++ b/pkg/commands/source/ping/flags.go @@ -23,8 +23,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/kn/commands" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" ) diff --git a/pkg/kn/commands/source/ping/list.go b/pkg/commands/source/ping/list.go similarity index 92% rename from pkg/kn/commands/source/ping/list.go rename to pkg/commands/source/ping/list.go index 9e2118af13..3a35fb459b 100644 --- a/pkg/kn/commands/source/ping/list.go +++ b/pkg/commands/source/ping/list.go @@ -18,14 +18,14 @@ import ( "fmt" "github.com/spf13/cobra" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" ) // NewPingListCommand is for listing Ping source COs func NewPingListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(PingSourceListHandlers) + listFlags := listfl.NewPrintFlags(PingSourceListHandlers) listCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/source/ping/list_test.go b/pkg/commands/source/ping/list_test.go similarity index 96% rename from pkg/kn/commands/source/ping/list_test.go rename to pkg/commands/source/ping/list_test.go index a09ce091ad..a9f7daf6d0 100644 --- a/pkg/kn/commands/source/ping/list_test.go +++ b/pkg/commands/source/ping/list_test.go @@ -23,8 +23,8 @@ import ( sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" - clientv1beta2 "knative.dev/client/pkg/sources/v1beta2" - "knative.dev/client/pkg/util" + clientv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" + "knative.dev/client-pkg/pkg/util" ) func TestListPingSource(t *testing.T) { diff --git a/pkg/kn/commands/source/ping/ping.go b/pkg/commands/source/ping/ping.go similarity index 95% rename from pkg/kn/commands/source/ping/ping.go rename to pkg/commands/source/ping/ping.go index ad09247efd..c517791949 100644 --- a/pkg/kn/commands/source/ping/ping.go +++ b/pkg/commands/source/ping/ping.go @@ -19,8 +19,8 @@ import ( "k8s.io/client-go/tools/clientcmd" - "knative.dev/client/pkg/kn/commands" - clientv1beta2 "knative.dev/client/pkg/sources/v1beta2" + clientv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" + "knative.dev/client/pkg/commands" sourcesv1beta2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1beta2" ) diff --git a/pkg/kn/commands/source/ping/ping_test.go b/pkg/commands/source/ping/ping_test.go similarity index 95% rename from pkg/kn/commands/source/ping/ping_test.go rename to pkg/commands/source/ping/ping_test.go index ee3af4666e..7d2a60d51e 100644 --- a/pkg/kn/commands/source/ping/ping_test.go +++ b/pkg/commands/source/ping/ping_test.go @@ -24,9 +24,9 @@ import ( sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" duckv1 "knative.dev/pkg/apis/duck/v1" - kndynamic "knative.dev/client/pkg/dynamic" - "knative.dev/client/pkg/kn/commands" - clientv1beta2 "knative.dev/client/pkg/sources/v1beta2" + kndynamic "knative.dev/client-pkg/pkg/dynamic" + clientv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" + "knative.dev/client/pkg/commands" ) // Helper methods diff --git a/pkg/kn/commands/source/ping/update.go b/pkg/commands/source/ping/update.go similarity index 92% rename from pkg/kn/commands/source/ping/update.go rename to pkg/commands/source/ping/update.go index 1eda2f25c7..6feb023f79 100644 --- a/pkg/kn/commands/source/ping/update.go +++ b/pkg/commands/source/ping/update.go @@ -18,22 +18,22 @@ import ( "errors" "fmt" - "knative.dev/client/pkg/config" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + "knative.dev/client-pkg/pkg/config" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - sourcesv1beta2 "knative.dev/client/pkg/sources/v1beta2" + sourcesv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" + "knative.dev/client/pkg/commands" eventingsourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // NewPingUpdateCommand prepares the command for a PingSource update func NewPingUpdateCommand(p *commands.KnParams) *cobra.Command { var updateFlags pingUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "update NAME", diff --git a/pkg/kn/commands/source/ping/update_test.go b/pkg/commands/source/ping/update_test.go similarity index 97% rename from pkg/kn/commands/source/ping/update_test.go rename to pkg/commands/source/ping/update_test.go index 4b87e53099..8e8b7c8817 100644 --- a/pkg/kn/commands/source/ping/update_test.go +++ b/pkg/commands/source/ping/update_test.go @@ -22,9 +22,9 @@ import ( "gotest.tools/v3/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - sourcesv1beta2 "knative.dev/client/pkg/sources/v1beta2" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + sourcesv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" + "knative.dev/client-pkg/pkg/util" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/kn/commands/source/source.go b/pkg/commands/source/source.go similarity index 82% rename from pkg/kn/commands/source/source.go rename to pkg/commands/source/source.go index 42bb4548d7..0bf28c41c6 100644 --- a/pkg/kn/commands/source/source.go +++ b/pkg/commands/source/source.go @@ -17,11 +17,11 @@ package source import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/source/apiserver" - "knative.dev/client/pkg/kn/commands/source/binding" - "knative.dev/client/pkg/kn/commands/source/container" - "knative.dev/client/pkg/kn/commands/source/ping" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/commands/source/apiserver" + "knative.dev/client/pkg/commands/source/binding" + "knative.dev/client/pkg/commands/source/container" + "knative.dev/client/pkg/commands/source/ping" ) func NewSourceCommand(p *commands.KnParams) *cobra.Command { diff --git a/pkg/kn/commands/subscription/create.go b/pkg/commands/subscription/create.go similarity index 91% rename from pkg/kn/commands/subscription/create.go rename to pkg/commands/subscription/create.go index f2f9019ab2..5e409fd128 100644 --- a/pkg/kn/commands/subscription/create.go +++ b/pkg/commands/subscription/create.go @@ -21,19 +21,19 @@ import ( "fmt" "github.com/spf13/cobra" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - knflags "knative.dev/client/pkg/kn/flags" - knmessagingv1 "knative.dev/client/pkg/messaging/v1" + knerrors "knative.dev/client-pkg/pkg/errors" + knmessagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" + knflags "knative.dev/client/pkg/flags" ) // NewSubscriptionCreateCommand to create event subscriptions func NewSubscriptionCreateCommand(p *commands.KnParams) *cobra.Command { var ( crefFlag knflags.ChannelRef - subscriberFlag, replyFlag, dlsFlag flags.SinkFlags + subscriberFlag, replyFlag, dlsFlag sinkfl.Flag ) cmd := &cobra.Command{ diff --git a/pkg/kn/commands/subscription/create_test.go b/pkg/commands/subscription/create_test.go similarity index 94% rename from pkg/kn/commands/subscription/create_test.go rename to pkg/commands/subscription/create_test.go index dad6d720ec..1a99a0bb8d 100644 --- a/pkg/kn/commands/subscription/create_test.go +++ b/pkg/commands/subscription/create_test.go @@ -21,9 +21,9 @@ import ( "gotest.tools/v3/assert" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - clientmessagingv1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + clientmessagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" ) func TestCreateSubscriptionErrorCase(t *testing.T) { diff --git a/pkg/kn/commands/subscription/delete.go b/pkg/commands/subscription/delete.go similarity index 97% rename from pkg/kn/commands/subscription/delete.go rename to pkg/commands/subscription/delete.go index 26a7e23509..de01661df7 100644 --- a/pkg/kn/commands/subscription/delete.go +++ b/pkg/commands/subscription/delete.go @@ -21,7 +21,7 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewSubscriptionDeleteCommand is for deleting a Subscription diff --git a/pkg/kn/commands/subscription/delete_test.go b/pkg/commands/subscription/delete_test.go similarity index 95% rename from pkg/kn/commands/subscription/delete_test.go rename to pkg/commands/subscription/delete_test.go index e99805dae9..46d23de506 100644 --- a/pkg/kn/commands/subscription/delete_test.go +++ b/pkg/commands/subscription/delete_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - v1beta1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + v1beta1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" ) func TestDeleteSubscriptionErrorCase(t *testing.T) { diff --git a/pkg/kn/commands/subscription/describe.go b/pkg/commands/subscription/describe.go similarity index 86% rename from pkg/kn/commands/subscription/describe.go rename to pkg/commands/subscription/describe.go index aced44a85c..61cb51ba66 100644 --- a/pkg/kn/commands/subscription/describe.go +++ b/pkg/commands/subscription/describe.go @@ -21,14 +21,14 @@ import ( "fmt" "github.com/spf13/cobra" + "knative.dev/client/pkg/describe" "k8s.io/cli-runtime/pkg/genericclioptions" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - "knative.dev/client/lib/printing" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" ) // NewSubscriptionDescribeCommand returns a new command for describe a subscription object @@ -103,9 +103,9 @@ func writeSubscription(dw printers.PrefixWriter, subscription *messagingv1.Subsc commands.WriteMetadata(dw, &subscription.ObjectMeta, printDetails) ctype := fmt.Sprintf("%s:%s (%s)", subscription.Spec.Channel.Kind, subscription.Spec.Channel.Name, subscription.Spec.Channel.APIVersion) dw.WriteAttribute("Channel", ctype) - printing.DescribeSink(dw, "Subscriber", subscription.Namespace, subscription.Spec.Subscriber) - printing.DescribeSink(dw, "Reply", subscription.Namespace, subscription.Spec.Reply) + describe.Sink(dw, "Subscriber", subscription.Namespace, subscription.Spec.Subscriber) + describe.Sink(dw, "Reply", subscription.Namespace, subscription.Spec.Reply) if subscription.Spec.DeepCopy().Delivery != nil { - printing.DescribeSink(dw, "DeadLetterSink", subscription.Namespace, subscription.Spec.Delivery.DeadLetterSink) + describe.Sink(dw, "DeadLetterSink", subscription.Namespace, subscription.Spec.Delivery.DeadLetterSink) } } diff --git a/pkg/kn/commands/subscription/describe_test.go b/pkg/commands/subscription/describe_test.go similarity index 96% rename from pkg/kn/commands/subscription/describe_test.go rename to pkg/commands/subscription/describe_test.go index da9eb5db24..7e94bef021 100644 --- a/pkg/kn/commands/subscription/describe_test.go +++ b/pkg/commands/subscription/describe_test.go @@ -23,8 +23,8 @@ import ( "gotest.tools/v3/assert" - clientv1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + clientv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" ) diff --git a/pkg/kn/commands/subscription/flags.go b/pkg/commands/subscription/flags.go similarity index 93% rename from pkg/kn/commands/subscription/flags.go rename to pkg/commands/subscription/flags.go index a139bac2a3..71fb45f772 100644 --- a/pkg/kn/commands/subscription/flags.go +++ b/pkg/commands/subscription/flags.go @@ -21,10 +21,10 @@ import ( metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - hprinters "knative.dev/client/pkg/printers" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" ) @@ -57,17 +57,17 @@ func printSubscription(subscription *messagingv1.Subscription, options hprinters var subscriber, reply, dls string if subscription.Spec.Subscriber != nil { - subscriber = flags.SinkToString(*subscription.Spec.Subscriber) + subscriber = sinkfl.SinkToString(*subscription.Spec.Subscriber) } else { subscriber = "" } if subscription.Spec.Reply != nil { - reply = flags.SinkToString(*subscription.Spec.Reply) + reply = sinkfl.SinkToString(*subscription.Spec.Reply) } else { reply = "" } if subscription.Spec.Delivery != nil && subscription.Spec.Delivery.DeadLetterSink != nil { - dls = flags.SinkToString(*subscription.Spec.Delivery.DeadLetterSink) + dls = sinkfl.SinkToString(*subscription.Spec.Delivery.DeadLetterSink) } else { dls = "" } diff --git a/pkg/kn/commands/subscription/list.go b/pkg/commands/subscription/list.go similarity index 92% rename from pkg/kn/commands/subscription/list.go rename to pkg/commands/subscription/list.go index d77da3741d..b92a947e02 100644 --- a/pkg/kn/commands/subscription/list.go +++ b/pkg/commands/subscription/list.go @@ -19,19 +19,19 @@ package subscription import ( "fmt" - "knative.dev/client/pkg/util" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" + "knative.dev/client-pkg/pkg/util" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" ) // NewSubscriptionListCommand is for listing subscription objects func NewSubscriptionListCommand(p *commands.KnParams) *cobra.Command { - listFlags := flags.NewListPrintFlags(ListHandlers) + listFlags := listfl.NewPrintFlags(ListHandlers) listCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/subscription/list_test.go b/pkg/commands/subscription/list_test.go similarity index 97% rename from pkg/kn/commands/subscription/list_test.go rename to pkg/commands/subscription/list_test.go index 28f29c2e7d..47dee26d2f 100644 --- a/pkg/kn/commands/subscription/list_test.go +++ b/pkg/commands/subscription/list_test.go @@ -25,8 +25,8 @@ import ( "gotest.tools/v3/assert" - clientv1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + clientv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" ) diff --git a/pkg/kn/commands/subscription/subscription.go b/pkg/commands/subscription/subscription.go similarity index 95% rename from pkg/kn/commands/subscription/subscription.go rename to pkg/commands/subscription/subscription.go index cc1b00eaa4..bb4421c6b4 100644 --- a/pkg/kn/commands/subscription/subscription.go +++ b/pkg/commands/subscription/subscription.go @@ -22,8 +22,8 @@ import ( "k8s.io/client-go/tools/clientcmd" clientv1beta1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" - "knative.dev/client/pkg/kn/commands" - messagingv1 "knative.dev/client/pkg/messaging/v1" + messagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" ) // NewSubscriptionCommand to manage event subscriptions diff --git a/pkg/kn/commands/subscription/subscription_test.go b/pkg/commands/subscription/subscription_test.go similarity index 96% rename from pkg/kn/commands/subscription/subscription_test.go rename to pkg/commands/subscription/subscription_test.go index 8a19d066bc..dae2124862 100644 --- a/pkg/kn/commands/subscription/subscription_test.go +++ b/pkg/commands/subscription/subscription_test.go @@ -26,9 +26,9 @@ import ( duckv1 "knative.dev/pkg/apis/duck/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - kndynamic "knative.dev/client/pkg/dynamic" - "knative.dev/client/pkg/kn/commands" - clientv1 "knative.dev/client/pkg/messaging/v1" + kndynamic "knative.dev/client-pkg/pkg/dynamic" + clientv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" ) // Helper methods diff --git a/pkg/kn/commands/subscription/update.go b/pkg/commands/subscription/update.go similarity index 91% rename from pkg/kn/commands/subscription/update.go rename to pkg/commands/subscription/update.go index 851755cc07..a59c6c3c5f 100644 --- a/pkg/kn/commands/subscription/update.go +++ b/pkg/commands/subscription/update.go @@ -20,20 +20,20 @@ import ( "errors" "fmt" - "knative.dev/client/pkg/config" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + "knative.dev/client-pkg/pkg/config" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" "github.com/spf13/cobra" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - knmessagingv1 "knative.dev/client/pkg/messaging/v1" + knerrors "knative.dev/client-pkg/pkg/errors" + knmessagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client/pkg/commands" ) // NewSubscriptionUpdateCommand to update event subscriptions func NewSubscriptionUpdateCommand(p *commands.KnParams) *cobra.Command { - var subscriberFlag, replyFlag, dlsFlag flags.SinkFlags + var subscriberFlag, replyFlag, dlsFlag sinkfl.Flag cmd := &cobra.Command{ Use: "update NAME", Short: "Update an event subscription", diff --git a/pkg/kn/commands/subscription/update_test.go b/pkg/commands/subscription/update_test.go similarity index 94% rename from pkg/kn/commands/subscription/update_test.go rename to pkg/commands/subscription/update_test.go index 41f21d57d9..3011642d1a 100644 --- a/pkg/kn/commands/subscription/update_test.go +++ b/pkg/commands/subscription/update_test.go @@ -21,9 +21,9 @@ import ( "gotest.tools/v3/assert" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - v1beta1 "knative.dev/client/pkg/messaging/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + v1beta1 "knative.dev/client-pkg/pkg/messaging/v1" + "knative.dev/client-pkg/pkg/util" ) func TestUpdateSubscriptionErrorCase(t *testing.T) { diff --git a/pkg/kn/commands/testing_helper.go b/pkg/commands/testing_helper.go similarity index 94% rename from pkg/kn/commands/testing_helper.go rename to pkg/commands/testing_helper.go index 391d8ab9c7..4e116b1c2c 100644 --- a/pkg/kn/commands/testing_helper.go +++ b/pkg/commands/testing_helper.go @@ -17,20 +17,20 @@ package commands import ( "bytes" - "knative.dev/client/pkg/dynamic/fake" + "knative.dev/client-pkg/pkg/dynamic/fake" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/runtime" clienttesting "k8s.io/client-go/testing" servingv1fake "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/fake" - "knative.dev/client/pkg/kn/flags" - clientservingv1 "knative.dev/client/pkg/serving/v1" - v1 "knative.dev/client/pkg/sources/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + v1 "knative.dev/client-pkg/pkg/sources/v1" + "knative.dev/client/pkg/flags" sourcesv1fake "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1/fake" - clientdynamic "knative.dev/client/pkg/dynamic" + clientdynamic "knative.dev/client-pkg/pkg/dynamic" ) const FakeNamespace = "current" diff --git a/pkg/kn/commands/testing_helper_test.go b/pkg/commands/testing_helper_test.go similarity index 98% rename from pkg/kn/commands/testing_helper_test.go rename to pkg/commands/testing_helper_test.go index 0685010abb..f78ae9673d 100644 --- a/pkg/kn/commands/testing_helper_test.go +++ b/pkg/commands/testing_helper_test.go @@ -21,7 +21,7 @@ import ( "github.com/spf13/cobra" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" ) func TestCreateTestKnCommand(t *testing.T) { diff --git a/pkg/kn/commands/trigger/create.go b/pkg/commands/trigger/create.go similarity index 94% rename from pkg/kn/commands/trigger/create.go rename to pkg/commands/trigger/create.go index 181c750551..978c79aa06 100644 --- a/pkg/kn/commands/trigger/create.go +++ b/pkg/commands/trigger/create.go @@ -19,18 +19,18 @@ import ( "fmt" "github.com/spf13/cobra" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" duckv1 "knative.dev/pkg/apis/duck/v1" - clientv1beta1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + clientv1beta1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client/pkg/commands" ) // NewTriggerCreateCommand to create trigger create command func NewTriggerCreateCommand(p *commands.KnParams) *cobra.Command { var triggerUpdateFlags TriggerUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "create NAME --sink SINK", diff --git a/pkg/kn/commands/trigger/create_test.go b/pkg/commands/trigger/create_test.go similarity index 96% rename from pkg/kn/commands/trigger/create_test.go rename to pkg/commands/trigger/create_test.go index fafb3f4d56..8c26478dd5 100644 --- a/pkg/kn/commands/trigger/create_test.go +++ b/pkg/commands/trigger/create_test.go @@ -22,9 +22,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" ) var ( diff --git a/pkg/kn/commands/trigger/delete.go b/pkg/commands/trigger/delete.go similarity index 97% rename from pkg/kn/commands/trigger/delete.go rename to pkg/commands/trigger/delete.go index 0335d2d249..f7ed7dcdb1 100644 --- a/pkg/kn/commands/trigger/delete.go +++ b/pkg/commands/trigger/delete.go @@ -19,7 +19,7 @@ import ( "fmt" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewTriggerDeleteCommand represent 'revision delete' command diff --git a/pkg/kn/commands/trigger/delete_test.go b/pkg/commands/trigger/delete_test.go similarity index 94% rename from pkg/kn/commands/trigger/delete_test.go rename to pkg/commands/trigger/delete_test.go index b2f21797f0..414dbaf605 100644 --- a/pkg/kn/commands/trigger/delete_test.go +++ b/pkg/commands/trigger/delete_test.go @@ -20,8 +20,8 @@ import ( "gotest.tools/v3/assert" - eventingclientv1beta1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + eventingclientv1beta1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" ) func TestTriggerDelete(t *testing.T) { diff --git a/pkg/kn/commands/trigger/describe.go b/pkg/commands/trigger/describe.go similarity index 96% rename from pkg/kn/commands/trigger/describe.go rename to pkg/commands/trigger/describe.go index 278c67499f..a3bcc2b740 100644 --- a/pkg/kn/commands/trigger/describe.go +++ b/pkg/commands/trigger/describe.go @@ -19,9 +19,9 @@ import ( "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" - "knative.dev/client/lib/printing" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/describe" v1beta1 "knative.dev/eventing/pkg/apis/eventing/v1" ) @@ -91,7 +91,7 @@ func NewTriggerDescribeCommand(p *commands.KnParams) *cobra.Command { } // Revisions summary info - printing.DescribeSink(dw, "Sink", trigger.Namespace, &trigger.Spec.Subscriber) + describe.Sink(dw, "Sink", trigger.Namespace, &trigger.Spec.Subscriber) dw.WriteLine() if err := dw.Flush(); err != nil { return err diff --git a/pkg/kn/commands/trigger/describe_test.go b/pkg/commands/trigger/describe_test.go similarity index 98% rename from pkg/kn/commands/trigger/describe_test.go rename to pkg/commands/trigger/describe_test.go index 4d5188965e..afdca4a15e 100644 --- a/pkg/kn/commands/trigger/describe_test.go +++ b/pkg/commands/trigger/describe_test.go @@ -20,7 +20,7 @@ import ( "errors" "testing" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" "gotest.tools/v3/assert" "gotest.tools/v3/assert/cmp" @@ -30,8 +30,8 @@ import ( "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" - clientv1beta1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + clientv1beta1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" ) func TestSimpleDescribe(t *testing.T) { diff --git a/pkg/kn/commands/trigger/list.go b/pkg/commands/trigger/list.go similarity index 92% rename from pkg/kn/commands/trigger/list.go rename to pkg/commands/trigger/list.go index 7c952a2bab..b9eb6ec412 100644 --- a/pkg/kn/commands/trigger/list.go +++ b/pkg/commands/trigger/list.go @@ -18,14 +18,14 @@ import ( "fmt" "github.com/spf13/cobra" + listfl "knative.dev/client-pkg/pkg/commands/flags/list" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands" ) // NewTriggerListCommand represents 'kn trigger list' command func NewTriggerListCommand(p *commands.KnParams) *cobra.Command { - triggerListFlags := flags.NewListPrintFlags(TriggerListHandlers) + triggerListFlags := listfl.NewPrintFlags(TriggerListHandlers) triggerListCommand := &cobra.Command{ Use: "list", diff --git a/pkg/kn/commands/trigger/list_flags.go b/pkg/commands/trigger/list_flags.go similarity index 95% rename from pkg/kn/commands/trigger/list_flags.go rename to pkg/commands/trigger/list_flags.go index a9dde8c379..bcab30f4ac 100644 --- a/pkg/kn/commands/trigger/list_flags.go +++ b/pkg/commands/trigger/list_flags.go @@ -19,9 +19,9 @@ import ( metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - hprinters "knative.dev/client/pkg/printers" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client/pkg/commands" v1beta1 "knative.dev/eventing/pkg/apis/eventing/v1" ) @@ -45,7 +45,7 @@ func TriggerListHandlers(h hprinters.PrintHandler) { func printTrigger(trigger *v1beta1.Trigger, options hprinters.PrintOptions) ([]metav1beta1.TableRow, error) { name := trigger.Name broker := trigger.Spec.Broker - sink := flags.SinkToString(trigger.Spec.Subscriber) + sink := sinkfl.SinkToString(trigger.Spec.Subscriber) age := commands.TranslateTimestampSince(trigger.CreationTimestamp) conditions := commands.ConditionsValue(trigger.Status.Conditions) ready := commands.ReadyCondition(trigger.Status.Conditions) diff --git a/pkg/kn/commands/trigger/list_test.go b/pkg/commands/trigger/list_test.go similarity index 97% rename from pkg/kn/commands/trigger/list_test.go rename to pkg/commands/trigger/list_test.go index ca729d8290..0f1da03a2f 100644 --- a/pkg/kn/commands/trigger/list_test.go +++ b/pkg/commands/trigger/list_test.go @@ -26,9 +26,9 @@ import ( eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - clientservingv1 "knative.dev/client/pkg/serving/v1" - "knative.dev/client/pkg/util" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + "knative.dev/client-pkg/pkg/util" ) func TestTriggerList(t *testing.T) { diff --git a/pkg/kn/commands/trigger/trigger.go b/pkg/commands/trigger/trigger.go similarity index 96% rename from pkg/kn/commands/trigger/trigger.go rename to pkg/commands/trigger/trigger.go index 5c448dbc34..c306bad05c 100644 --- a/pkg/kn/commands/trigger/trigger.go +++ b/pkg/commands/trigger/trigger.go @@ -17,7 +17,7 @@ package trigger import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" ) // NewTriggerCommand to create trigger command group diff --git a/pkg/kn/commands/trigger/trigger_test.go b/pkg/commands/trigger/trigger_test.go similarity index 95% rename from pkg/kn/commands/trigger/trigger_test.go rename to pkg/commands/trigger/trigger_test.go index 8665f2dc58..5ff520108f 100644 --- a/pkg/kn/commands/trigger/trigger_test.go +++ b/pkg/commands/trigger/trigger_test.go @@ -22,9 +22,9 @@ import ( "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" - clientdynamic "knative.dev/client/pkg/dynamic" - eventclientv1beta1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/kn/commands" + clientdynamic "knative.dev/client-pkg/pkg/dynamic" + eventclientv1beta1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client/pkg/commands" ) // Helper methods diff --git a/pkg/kn/commands/trigger/update.go b/pkg/commands/trigger/update.go similarity index 93% rename from pkg/kn/commands/trigger/update.go rename to pkg/commands/trigger/update.go index d0ab10610f..9d2d8ad130 100644 --- a/pkg/kn/commands/trigger/update.go +++ b/pkg/commands/trigger/update.go @@ -18,22 +18,22 @@ import ( "errors" "fmt" - "knative.dev/client/pkg/config" - clientv1beta1 "knative.dev/client/pkg/eventing/v1" + sinkfl "knative.dev/client-pkg/pkg/commands/flags/sink" + "knative.dev/client-pkg/pkg/config" + clientv1beta1 "knative.dev/client-pkg/pkg/eventing/v1" duckv1 "knative.dev/pkg/apis/duck/v1" "github.com/spf13/cobra" v1beta1 "knative.dev/eventing/pkg/apis/eventing/v1" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/flags" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) // NewTriggerUpdateCommand prepares the command for a tigger update func NewTriggerUpdateCommand(p *commands.KnParams) *cobra.Command { var triggerUpdateFlags TriggerUpdateFlags - var sinkFlags flags.SinkFlags + var sinkFlags sinkfl.Flag cmd := &cobra.Command{ Use: "update NAME", diff --git a/pkg/kn/commands/trigger/update_flags.go b/pkg/commands/trigger/update_flags.go similarity index 98% rename from pkg/kn/commands/trigger/update_flags.go rename to pkg/commands/trigger/update_flags.go index fd3aacf90e..2059a2b104 100644 --- a/pkg/kn/commands/trigger/update_flags.go +++ b/pkg/commands/trigger/update_flags.go @@ -19,7 +19,7 @@ import ( "github.com/spf13/cobra" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // TriggerUpdateFlags are flags for create and update a trigger diff --git a/pkg/kn/commands/trigger/update_flags_test.go b/pkg/commands/trigger/update_flags_test.go similarity index 100% rename from pkg/kn/commands/trigger/update_flags_test.go rename to pkg/commands/trigger/update_flags_test.go diff --git a/pkg/kn/commands/trigger/update_test.go b/pkg/commands/trigger/update_test.go similarity index 95% rename from pkg/kn/commands/trigger/update_test.go rename to pkg/commands/trigger/update_test.go index b9fb700eec..7b03b7b9ea 100644 --- a/pkg/kn/commands/trigger/update_test.go +++ b/pkg/commands/trigger/update_test.go @@ -23,9 +23,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - dynamicfake "knative.dev/client/pkg/dynamic/fake" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - "knative.dev/client/pkg/util" + dynamicfake "knative.dev/client-pkg/pkg/dynamic/fake" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + "knative.dev/client-pkg/pkg/util" ) func TestTriggerUpdate(t *testing.T) { diff --git a/pkg/kn/commands/types.go b/pkg/commands/types.go similarity index 94% rename from pkg/kn/commands/types.go rename to pkg/commands/types.go index 67621e0c18..c792b8b61e 100644 --- a/pkg/kn/commands/types.go +++ b/pkg/commands/types.go @@ -33,17 +33,17 @@ import ( servingv1client "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1" servingv1beta1client "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1" - "knative.dev/client/pkg/util" - - clientdynamic "knative.dev/client/pkg/dynamic" - knerrors "knative.dev/client/pkg/errors" - clienteventingv1 "knative.dev/client/pkg/eventing/v1" - clienteventingv1beta2 "knative.dev/client/pkg/eventing/v1beta2" - clientmessagingv1 "knative.dev/client/pkg/messaging/v1" - clientservingv1 "knative.dev/client/pkg/serving/v1" - clientservingv1beta1 "knative.dev/client/pkg/serving/v1beta1" - clientsourcesv1 "knative.dev/client/pkg/sources/v1" - clientsourcesv1beta2 "knative.dev/client/pkg/sources/v1beta2" + "knative.dev/client-pkg/pkg/util" + + clientdynamic "knative.dev/client-pkg/pkg/dynamic" + knerrors "knative.dev/client-pkg/pkg/errors" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + clienteventingv1beta2 "knative.dev/client-pkg/pkg/eventing/v1beta2" + clientmessagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + clientservingv1beta1 "knative.dev/client-pkg/pkg/serving/v1beta1" + clientsourcesv1 "knative.dev/client-pkg/pkg/sources/v1" + clientsourcesv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" ) // KnParams for creating commands. Useful for inserting mocks for testing. diff --git a/pkg/kn/commands/types_test.go b/pkg/commands/types_test.go similarity index 99% rename from pkg/kn/commands/types_test.go rename to pkg/commands/types_test.go index 0ae5f166c6..e76aedf42c 100644 --- a/pkg/kn/commands/types_test.go +++ b/pkg/commands/types_test.go @@ -21,12 +21,12 @@ import ( "strings" "testing" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" "gotest.tools/v3/assert" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) type configTestCase struct { diff --git a/pkg/kn/commands/version/version.go b/pkg/commands/version/version.go similarity index 99% rename from pkg/kn/commands/version/version.go rename to pkg/commands/version/version.go index f72a9d9357..05b91dfda2 100644 --- a/pkg/kn/commands/version/version.go +++ b/pkg/commands/version/version.go @@ -22,7 +22,7 @@ import ( "github.com/spf13/cobra" "golang.org/x/mod/semver" - "knative.dev/client/pkg/kn/commands" + "knative.dev/client/pkg/commands" "sigs.k8s.io/yaml" ) diff --git a/pkg/kn/commands/version/version_test.go b/pkg/commands/version/version_test.go similarity index 98% rename from pkg/kn/commands/version/version_test.go rename to pkg/commands/version/version_test.go index 8902fd9919..1dab98672e 100644 --- a/pkg/kn/commands/version/version_test.go +++ b/pkg/commands/version/version_test.go @@ -25,8 +25,8 @@ import ( "gotest.tools/v3/assert" "sigs.k8s.io/yaml" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client/pkg/commands" ) var versionOutputTemplate = `Version: {{.Version}} diff --git a/pkg/kn/commands/wait_flags.go b/pkg/commands/wait_flags.go similarity index 98% rename from pkg/kn/commands/wait_flags.go rename to pkg/commands/wait_flags.go index 22dae67463..0158c26875 100644 --- a/pkg/kn/commands/wait_flags.go +++ b/pkg/commands/wait_flags.go @@ -19,7 +19,7 @@ import ( "github.com/spf13/cobra" - knflags "knative.dev/client/pkg/kn/flags" + knflags "knative.dev/client/pkg/flags" ) // Default time out to use when waiting for reconciliation. It is deliberately very long as it is expected that diff --git a/pkg/kn/commands/wait_flags_test.go b/pkg/commands/wait_flags_test.go similarity index 99% rename from pkg/kn/commands/wait_flags_test.go rename to pkg/commands/wait_flags_test.go index 51b57bf0ed..d174f0809f 100644 --- a/pkg/kn/commands/wait_flags_test.go +++ b/pkg/commands/wait_flags_test.go @@ -19,7 +19,7 @@ import ( "strings" "testing" - knflags "knative.dev/client/pkg/kn/flags" + knflags "knative.dev/client/pkg/flags" "github.com/spf13/cobra" "gotest.tools/v3/assert" diff --git a/pkg/kn/config/config.go b/pkg/config/config.go similarity index 100% rename from pkg/kn/config/config.go rename to pkg/config/config.go diff --git a/pkg/kn/config/config_test.go b/pkg/config/config_test.go similarity index 100% rename from pkg/kn/config/config_test.go rename to pkg/config/config_test.go diff --git a/pkg/kn/config/testing.go b/pkg/config/testing.go similarity index 100% rename from pkg/kn/config/testing.go rename to pkg/config/testing.go diff --git a/pkg/kn/config/testing_test.go b/pkg/config/testing_test.go similarity index 100% rename from pkg/kn/config/testing_test.go rename to pkg/config/testing_test.go diff --git a/pkg/kn/config/types.go b/pkg/config/types.go similarity index 100% rename from pkg/kn/config/types.go rename to pkg/config/types.go diff --git a/lib/printing/describe.go b/pkg/describe/describe.go similarity index 83% rename from lib/printing/describe.go rename to pkg/describe/describe.go index 66467d01af..42c96bff57 100644 --- a/lib/printing/describe.go +++ b/pkg/describe/describe.go @@ -14,18 +14,18 @@ See the License for the specific language governing permissions and limitations under the License. */ -package printing +package describe import ( "fmt" - "knative.dev/client/pkg/printers" + "knative.dev/client-pkg/pkg/printers" duckv1 "knative.dev/pkg/apis/duck/v1" ) -// DescribeSink prints the given 'sink' for the given prefix writer 'dw', +// Sink prints the given 'sink' for the given prefix writer 'dw', // provide 'attribute' to print the section heading for this sink, -func DescribeSink(dw printers.PrefixWriter, attribute, namespace string, sink *duckv1.Destination) { +func Sink(dw printers.PrefixWriter, attribute, namespace string, sink *duckv1.Destination) { if sink == nil { return } diff --git a/pkg/dynamic/client_mock_test.go b/pkg/dynamic/client_mock_test.go deleted file mode 100644 index 74f1c523b4..0000000000 --- a/pkg/dynamic/client_mock_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright © 2019 The Knative 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 dynamic - -import ( - "context" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/client-go/dynamic/fake" - "knative.dev/client/pkg/util/mock" -) - -func TestMockKnDynamicClient(t *testing.T) { - - client := NewMockKnDynamicClient(t) - - recorder := client.Recorder() - - recorder.ListCRDs(mock.Any(), nil, nil) - recorder.ListSourcesTypes(nil, nil) - recorder.ListSources(mock.Any(), nil, nil) - recorder.ListChannelsTypes(nil, nil) - recorder.RawClient(&fake.FakeDynamicClient{}) - recorder.ListSourcesUsingGVKs(mock.Any(), mock.Any(), nil, nil) - recorder.ListChannelsUsingGVKs(mock.Any(), mock.Any(), nil, nil) - - ctx := context.Background() - client.ListCRDs(ctx, metav1.ListOptions{}) - client.ListSourcesTypes(ctx) - client.ListChannelsTypes(ctx) - client.ListSources(ctx, WithTypeFilter("blub")) - client.RawClient() - client.ListSourcesUsingGVKs(ctx, &[]schema.GroupVersionKind{}, WithTypeFilter("blub")) - client.ListChannelsUsingGVKs(ctx, &[]schema.GroupVersionKind{}, WithTypeFilter("blub")) - - // Validate - recorder.Validate() -} diff --git a/pkg/dynamic/client_test.go b/pkg/dynamic/client_test.go deleted file mode 100644 index 9e4a52f012..0000000000 --- a/pkg/dynamic/client_test.go +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright © 2019 The Knative 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 dynamic - -import ( - "context" - "strings" - "testing" - - "gotest.tools/v3/assert" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - - eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" - "knative.dev/eventing/pkg/apis/messaging" - messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" - sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" - dynamicclientfake "knative.dev/pkg/injection/clients/dynamicclient/fake" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - - "knative.dev/client/pkg/util" -) - -const testNamespace = "current" - -func TestNamespace(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace, newSourceCRDObj("foo")) - assert.Equal(t, client.Namespace(), testNamespace) -} - -func TestListCRDs(t *testing.T) { - client := createFakeKnDynamicClient( - testNamespace, - newSourceCRDObj("foo"), - newSourceCRDObj("bar"), - ) - assert.Check(t, client.RawClient() != nil) - - t.Run("List CRDs with match", func(t *testing.T) { - options := metav1.ListOptions{} - uList, err := client.ListCRDs(context.Background(), options) - assert.NilError(t, err) - assert.Equal(t, len(uList.Items), 2) - }) - - t.Run("List CRDs without match", func(t *testing.T) { - options := metav1.ListOptions{} - sourcesLabels := labels.Set{"duck.knative.dev/source": "true1"} - options.LabelSelector = sourcesLabels.String() - uList, err := client.ListCRDs(context.Background(), options) - if err != nil { - t.Fatal(err) - } - - assert.Equal(t, len(uList.Items), 0) - }) -} - -func TestListSourceTypes(t *testing.T) { - client := createFakeKnDynamicClient( - testNamespace, - newSourceCRDObj("foo"), - newSourceCRDObj("bar"), - ) - - t.Run("List source types", func(t *testing.T) { - uList, err := client.ListSourcesTypes(context.Background()) - if err != nil { - t.Fatal(err) - } - - assert.Equal(t, len(uList.Items), 2) - // List of objects is returned in sorted order according to the (ns first, then name) - assert.Equal(t, uList.Items[0].GetName(), "bar") - assert.Equal(t, uList.Items[1].GetName(), "foo") - }) -} - -func TestListSources(t *testing.T) { - t.Run("No GVRs set", func(t *testing.T) { - obj := newSourceCRDObj("foo") - client := createFakeKnDynamicClient(testNamespace, obj) - assert.Check(t, client.RawClient() != nil) - _, err := client.ListSources(context.Background()) - assert.Check(t, err != nil) - assert.Check(t, util.ContainsAll(err.Error(), "can't", "find", "source", "kind", "CRD")) - }) - - t.Run("sources not installed", func(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace) - _, err := client.ListSources(context.Background()) - assert.Check(t, err != nil) - assert.Check(t, util.ContainsAll(err.Error(), "no sources", "found", "backend", "verify", "installation")) - }) - - t.Run("source list empty", func(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace, - newSourceCRDObjWithSpec("pingsources", "sources.knative.dev", "v1beta2", "PingSource"), - ) - sources, err := client.ListSources(context.Background()) - assert.NilError(t, err) - assert.Equal(t, len(sources.Items), 0) - }) - - t.Run("source list non empty", func(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace, - newSourceCRDObjWithSpec("pingsources", "sources.knative.dev", "v1beta2", "PingSource"), - newSourceCRDObjWithSpec("apiserversources", "sources.knative.dev", "v1", "ApiServerSource"), - newSourceUnstructuredObj("p1", "sources.knative.dev/v1beta2", "PingSource"), - newSourceUnstructuredObj("a1", "sources.knative.dev/v1", "ApiServerSource"), - ) - sources, err := client.ListSources(context.Background(), WithTypeFilter("pingsource"), WithTypeFilter("ApiServerSource")) - assert.NilError(t, err) - assert.Equal(t, len(sources.Items), 2) - assert.DeepEqual(t, sources.GroupVersionKind(), schema.GroupVersionKind{Group: sourceListGroup, Version: sourceListVersion, Kind: sourceListKind}) - }) -} - -func TestListSourcesUsingGVKs(t *testing.T) { - t.Run("No GVKs given", func(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace) - assert.Check(t, client.RawClient() != nil) - s, err := client.ListSourcesUsingGVKs(context.Background(), nil) - assert.NilError(t, err) - assert.Check(t, s == nil) - }) - - t.Run("source list with given GVKs", func(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace, - newSourceCRDObjWithSpec("pingsources", "sources.knative.dev", "v1beta2", "PingSource"), - newSourceCRDObjWithSpec("apiserversources", "sources.knative.dev", "v1", "ApiServerSource"), - newSourceUnstructuredObj("p1", "sources.knative.dev/v1beta2", "PingSource"), - newSourceUnstructuredObj("a1", "sources.knative.dev/v1", "ApiServerSource"), - ) - assert.Check(t, client.RawClient() != nil) - gvks := []schema.GroupVersionKind{ - {Group: "sources.knative.dev", Version: "v1beta2", Kind: "PingSource"}, - {Group: "sources.knative.dev", Version: "v1", Kind: "ApiServerSource"}, - } - - s, err := client.ListSourcesUsingGVKs(context.Background(), &gvks) - assert.NilError(t, err) - if s == nil { - t.Fatal("s = nil, want not nil") - } - assert.Equal(t, len(s.Items), 2) - assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{Group: sourceListGroup, Version: sourceListVersion, Kind: sourceListKind}) - - // withType - s, err = client.ListSourcesUsingGVKs(context.Background(), &gvks, WithTypeFilter("PingSource")) - assert.NilError(t, err) - if s == nil { - t.Fatal("s = nil, want not nil") - } - assert.Equal(t, len(s.Items), 1) - assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{Group: sourceListGroup, Version: sourceListVersion, Kind: sourceListKind}) - }) - -} - -// createFakeKnDynamicClient gives you a dynamic client for testing containing the given objects. -// See also the one in the fake package. Duplicated here to avoid a dependency loop. -func createFakeKnDynamicClient(testNamespace string, objects ...runtime.Object) KnDynamicClient { - scheme := runtime.NewScheme() - servingv1.AddToScheme(scheme) - eventingv1.AddToScheme(scheme) - messagingv1.AddToScheme(scheme) - sourcesv1.AddToScheme(scheme) - sourcesv1beta2.AddToScheme(scheme) - apiextensionsv1.AddToScheme(scheme) - _, dynamicClient := dynamicclientfake.With(context.TODO(), scheme, objects...) - return NewKnDynamicClient(dynamicClient, testNamespace) -} - -func newSourceCRDObj(name string) *unstructured.Unstructured { - obj := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": crdGroup + "/" + crdVersion, - "kind": crdKind, - "metadata": map[string]interface{}{ - "namespace": testNamespace, - "name": name, - }, - }, - } - obj.SetLabels(labels.Set{sourcesLabelKey: sourcesLabelValue}) - return obj -} - -func newSourceCRDObjWithSpec(name, group, version, kind string) *unstructured.Unstructured { - obj := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": crdGroup + "/" + crdVersion, - "kind": crdKind, - "metadata": map[string]interface{}{ - "namespace": testNamespace, - "name": name, - }, - }, - } - - obj.Object["spec"] = map[string]interface{}{ - "group": group, - "version": version, - "names": map[string]interface{}{ - "kind": kind, - "plural": strings.ToLower(kind) + "s", - }, - } - obj.SetLabels(labels.Set{sourcesLabelKey: sourcesLabelValue}) - return obj -} - -func newSourceUnstructuredObj(name, apiVersion, kind string) *unstructured.Unstructured { - return &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": apiVersion, - "kind": kind, - "metadata": map[string]interface{}{ - "namespace": "current", - "name": name, - }, - "spec": map[string]interface{}{ - "sink": map[string]interface{}{ - "ref": map[string]interface{}{ - "kind": "Service", - "name": "foo", - }, - }, - }, - }, - } -} - -func newChannelCRDObj(name string) *unstructured.Unstructured { - obj := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": crdGroup + "/" + crdVersion, - "kind": crdKind, - "metadata": map[string]interface{}{ - "namespace": testNamespace, - "name": name, - }, - }, - } - obj.SetLabels(labels.Set{messaging.SubscribableDuckVersionAnnotation: channelLabelValue}) - return obj -} - -func newChannelCRDObjWithSpec(name, group, version, kind string) *unstructured.Unstructured { - obj := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": crdGroup + "/" + crdVersion, - "kind": crdKind, - "metadata": map[string]interface{}{ - "namespace": testNamespace, - "name": name, - }, - }, - } - - obj.Object["spec"] = map[string]interface{}{ - "group": group, - "version": version, - "names": map[string]interface{}{ - "kind": kind, - "plural": strings.ToLower(kind) + "s", - }, - } - obj.SetLabels(labels.Set{messaging.SubscribableDuckVersionAnnotation: channelLabelValue}) - return obj -} - -func newChannelUnstructuredObj(name, apiVersion, kind string) *unstructured.Unstructured { - return &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": apiVersion, - "kind": kind, - "metadata": map[string]interface{}{ - "namespace": "current", - "name": name, - }, - "spec": map[string]interface{}{ - "sink": map[string]interface{}{ - "ref": map[string]interface{}{ - "name": "foo", - }, - }, - }, - }, - } -} -func TestListChannelsTypes(t *testing.T) { - t.Run("List channel types", func(t *testing.T) { - client := createFakeKnDynamicClient( - testNamespace, - newChannelCRDObjWithSpec("Channel", "messaging.knative.dev", "v1", "Channel"), - newChannelCRDObjWithSpec("InMemoryChannel", "messaging.knative.dev", "v1", "InMemoryChannel"), - ) - - uList, err := client.ListChannelsTypes(context.Background()) - if err != nil { - t.Fatal(err) - } - assert.Equal(t, len(uList.Items), 1) - assert.Equal(t, uList.Items[0].GetName(), "InMemoryChannel") - }) - - t.Run("List channel types error", func(t *testing.T) { - client := createFakeKnDynamicClient( - testNamespace, - newChannelCRDObj("foo"), - ) - uList, err := client.ListChannelsTypes(context.Background()) - assert.Check(t, err == nil) - if err != nil { - t.Fatal(err) - } - assert.Equal(t, len(uList.Items), 1) - assert.Equal(t, uList.Items[0].GetName(), "foo") - }) -} - -func TestListChannelsUsingGVKs(t *testing.T) { - t.Run("No GVKs given", func(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace) - assert.Check(t, client.RawClient() != nil) - s, err := client.ListChannelsUsingGVKs(context.Background(), nil) - assert.NilError(t, err) - assert.Check(t, s == nil) - }) - - t.Run("channel list with given GVKs", func(t *testing.T) { - client := createFakeKnDynamicClient(testNamespace, - newChannelCRDObjWithSpec("InMemoryChannel", "messaging.knative.dev", "v1", "InMemoryChannel"), - newChannelUnstructuredObj("i1", "messaging.knative.dev/v1", "InMemoryChannel"), - ) - assert.Check(t, client.RawClient() != nil) - gv := schema.GroupVersion{Group: "messaging.knative.dev", Version: "v1"} - gvks := []schema.GroupVersionKind{gv.WithKind("InMemoryChannel")} - - s, err := client.ListChannelsUsingGVKs(context.Background(), &gvks) - assert.NilError(t, err) - if s == nil { - t.Fatal("s = nil, want not nil") - } - assert.Equal(t, len(s.Items), 1) - assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{Group: messaging.GroupName, Version: channelListVersion, Kind: channelListKind}) - - // withType - s, err = client.ListChannelsUsingGVKs(context.Background(), &gvks, WithTypeFilter("InMemoryChannel")) - assert.NilError(t, err) - if s == nil { - t.Fatal("s = nil, want not nil") - } - assert.Equal(t, len(s.Items), 1) - assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{Group: messaging.GroupName, Version: channelListVersion, Kind: channelListKind}) - }) - -} diff --git a/pkg/dynamic/lib_test.go b/pkg/dynamic/lib_test.go deleted file mode 100644 index d5130afa71..0000000000 --- a/pkg/dynamic/lib_test.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright © 2020 The Knative 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 dynamic - -import ( - "testing" - - "gotest.tools/v3/assert" - "k8s.io/apimachinery/pkg/runtime/schema" - - "knative.dev/client/pkg/util" -) - -func TestKindFromUnstructured(t *testing.T) { - kind, err := kindFromUnstructured( - newSourceCRDObjWithSpec("pingsources", "sources.knative.dev", "v1alpha1", "PingSource"), - ) - assert.NilError(t, err) - assert.Equal(t, kind, "PingSource") - _, err = kindFromUnstructured(newSourceCRDObj("foo")) - assert.Check(t, err != nil) -} - -func TestGVRFromUnstructured(t *testing.T) { - obj := newSourceCRDObj("foo") - - obj.Object["spec"] = map[string]interface{}{} - _, err := gvrFromUnstructured(obj) - assert.Check(t, err != nil) - assert.Check(t, util.ContainsAll(err.Error(), "can't", "find", "group")) - - obj.Object["spec"] = map[string]interface{}{ - "group": "sources.knative.dev", - } - _, err = gvrFromUnstructured(obj) - assert.Check(t, err != nil) - assert.Check(t, util.ContainsAll(err.Error(), "can't", "find", "version")) - - // with deprecated CRD field spec version - obj.Object["spec"] = map[string]interface{}{ - "group": "sources.knative.dev", - "version": "v1alpha1", - } - _, err = gvrFromUnstructured(obj) - assert.Check(t, err != nil) - assert.Check(t, util.ContainsAll(err.Error(), "can't", "find", "resource")) - - // with CRD field spec versions - obj.Object["spec"] = map[string]interface{}{ - "group": "sources.knative.dev", - "versions": []interface{}{ - map[string]interface{}{"name": "v1alpha1", "served": true}, - }, - } - _, err = gvrFromUnstructured(obj) - assert.Check(t, err != nil) - assert.Check(t, util.ContainsAll(err.Error(), "can't", "find", "resource")) - - obj.Object["spec"] = map[string]interface{}{ - "group": "sources.knative.dev", - "versions": []interface{}{ - map[string]interface{}{}, - }, - } - _, err = gvrFromUnstructured(obj) - assert.Check(t, err != nil) - assert.Check(t, util.ContainsAll(err.Error(), "can't", "find", "version")) -} - -func TestUnstructuredCRDFromGVK(t *testing.T) { - u := UnstructuredCRDFromGVK(schema.GroupVersionKind{Group: "sources.knative.dev", Version: "v1", Kind: "ApiServerSource"}) - g, err := groupFromUnstructured(u) - assert.NilError(t, err) - assert.Equal(t, g, "sources.knative.dev") - - v, err := versionFromUnstructured(u) - assert.NilError(t, err) - assert.Equal(t, v, "v1") - - k, err := kindFromUnstructured(u) - assert.NilError(t, err) - assert.Equal(t, k, "ApiServerSource") - - r, err := resourceFromUnstructured(u) - assert.NilError(t, err) - assert.Equal(t, r, "apiserversources") -} diff --git a/pkg/errors/errors_test.go b/pkg/errors/errors_test.go deleted file mode 100644 index ba94738f75..0000000000 --- a/pkg/errors/errors_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright © 2019 The Knative 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 errors - -import ( - "testing" - - "knative.dev/client/pkg/util" - - "gotest.tools/v3/assert" -) - -func TestNewInvalidCRD(t *testing.T) { - err := NewInvalidCRD("serving.knative.dev") - assert.Assert(t, util.ContainsAll(err.Error(), "no or newer Knative Serving API found on the backend", "please verify the installation", "update", "'kn'")) - - err = NewInvalidCRD("eventing") - assert.Assert(t, util.ContainsAll(err.Error(), "no or newer Knative Eventing API found on the backend", "please verify the installation", "update", "'kn'")) - - err = NewInvalidCRD("") - assert.Assert(t, util.ContainsAll(err.Error(), "no or newer Knative API found on the backend", "please verify the installation", "update", "'kn'")) -} diff --git a/pkg/errors/factory_test.go b/pkg/errors/factory_test.go deleted file mode 100644 index 48f834d3b1..0000000000 --- a/pkg/errors/factory_test.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright © 2019 The Knative 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 errors - -import ( - "errors" - "fmt" - "testing" - - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - - "gotest.tools/v3/assert" - api_errors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type mockErrType struct{} - -func (err mockErrType) Error() string { - return "mock error message" -} -func (err mockErrType) Status() metav1.Status { - return metav1.Status{} -} - -func TestKnErrorsStatusErrors(t *testing.T) { - cases := []struct { - Name string - Schema schema.GroupResource - StatusError func(schema.GroupResource) *api_errors.StatusError - ExpectedMsg string - Validate func(t *testing.T, err error, msg string) - }{ - { - Name: "Should get a missing serving api error", - Schema: schema.GroupResource{ - Group: "serving.knative.dev", - Resource: "service", - }, - StatusError: func(resource schema.GroupResource) *api_errors.StatusError { - statusError := api_errors.NewNotFound(resource, "serv") - statusError.Status().Details.Causes = []v1.StatusCause{ - { - Type: "UnexpectedServerResponse", - Message: "404 page not found", - }, - } - return statusError - }, - ExpectedMsg: "no or newer Knative Serving API found on the backend, please verify the installation or update the 'kn' client", - Validate: func(t *testing.T, err error, msg string) { - assert.Error(t, err, msg) - }, - }, - { - Name: "Should get the default not found error", - Schema: schema.GroupResource{ - Group: "serving.knative.dev", - Resource: "service", - }, - StatusError: func(resource schema.GroupResource) *api_errors.StatusError { - return api_errors.NewNotFound(resource, "serv") - }, - ExpectedMsg: "service.serving.knative.dev \"serv\" not found", - Validate: func(t *testing.T, err error, msg string) { - assert.Error(t, err, msg) - }, - }, - { - Name: "Should return the original error", - Schema: schema.GroupResource{ - Group: "serving.knative.dev", - Resource: "service", - }, - StatusError: func(resource schema.GroupResource) *api_errors.StatusError { - return api_errors.NewAlreadyExists(resource, "serv") - }, - ExpectedMsg: "service.serving.knative.dev \"serv\" already exists", - Validate: func(t *testing.T, err error, msg string) { - assert.Error(t, err, msg) - }, - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.Name, func(t *testing.T) { - t.Parallel() - statusError := tc.StatusError(tc.Schema) - err := GetError(statusError) - tc.Validate(t, err, tc.ExpectedMsg) - }) - } -} - -func TestKnErrors(t *testing.T) { - cases := []struct { - Name string - Error error - ExpectedMsg string - }{ - { - Name: "no kubeconfig provided", - Error: errors.New("invalid configuration: no configuration has been provided"), - ExpectedMsg: "no kubeconfig has been provided, please use a valid configuration to connect to the cluster", - }, - { - Name: "i/o timeout", - Error: errors.New("Get https://api.example.com:27435/apis/foo/bar: dial tcp 192.168.1.1:27435: i/o timeout"), - ExpectedMsg: "error connecting to the cluster, please verify connection at: 192.168.1.1:27435: i/o timeout", - }, - { - Name: "no route to host", - Error: errors.New("Get https://192.168.39.141:8443/apis/foo/bar: dial tcp 192.168.39.141:8443: connect: no route to host"), - ExpectedMsg: "error connecting to the cluster, please verify connection at: 192.168.39.141:8443: connect: no route to host", - }, - { - Name: "no route to host without dial tcp string", - Error: errors.New("no route to host 192.168.1.1"), - ExpectedMsg: "error connecting to the cluster: no route to host 192.168.1.1", - }, - { - Name: "foo error which cant be converted to APIStatus", - Error: errors.New("foo error"), - ExpectedMsg: "foo error", - }, - } - for _, tc := range cases { - tc := tc - t.Run(tc.Name, func(t *testing.T) { - t.Parallel() - err := GetError(tc.Error) - assert.Error(t, err, tc.ExpectedMsg) - }) - } -} - -func TestIsForbiddenError(t *testing.T) { - cases := []struct { - Name string - Error error - Forbidden bool - }{ - { - Name: "forbidden error", - Error: api_errors.NewForbidden(schema.GroupResource{Group: "apiextensions.k8s.io", Resource: "CustomResourceDefinition"}, "", nil), - Forbidden: true, - }, - { - Name: "non forbidden error", - Error: errors.New("panic"), - Forbidden: false, - }, - } - for _, tc := range cases { - err := tc.Error - forbidden := tc.Forbidden - t.Run(tc.Name, func(t *testing.T) { - t.Parallel() - assert.Equal(t, IsForbiddenError(GetError(err)), forbidden) - }) - } -} - -func TestNilError(t *testing.T) { - assert.NilError(t, GetError(nil), nil) -} - -func TestIsInternalError(t *testing.T) { - cases := []struct { - Name string - Error error - Internal bool - }{ - { - Name: "internal error with connection refused", - Error: api_errors.NewInternalError(fmt.Errorf("failed calling webhook \"webhook.serving.knative.dev\": Post \"https://webhook.knative-serving.svc:443/defaulting?timeout=10s\": dial tcp 10.96.27.233:443: connect: connection refused")), - Internal: true, - }, - { - Name: "internal error with context deadline exceeded", - Error: api_errors.NewInternalError(fmt.Errorf("failed calling webhook \"webhook.serving.knative.dev\": Post https://webhook.knative-serving.svc:443/defaulting?timeout=10s: context deadline exceeded")), - Internal: true, - }, - { - Name: "internal error with i/o timeout", - Error: api_errors.NewInternalError(fmt.Errorf("failed calling webhook \"webhook.serving.knative.dev\": Post https://webhook.knative-serving.svc:443/defaulting?timeout=10s: i/o timeout")), - Internal: true, - }, - { - Name: "not internal error", - Error: mockErrType{}, - Internal: false, - }, - } - - for _, tc := range cases { - err := tc.Error - internal := tc.Internal - t.Run(tc.Name, func(t *testing.T) { - t.Parallel() - assert.Equal(t, api_errors.IsInternalError(GetError(err)), internal) - }) - } -} - -func TestStatusError(t *testing.T) { - cases := []struct { - Name string - Error error - ErrorType func(error) bool - }{ - { - Name: "Timeout error", - Error: api_errors.NewTimeoutError("failed processing request: i/o timeout", 10), - ErrorType: api_errors.IsTimeout, - }, - { - Name: "Conflict error", - Error: api_errors.NewConflict(servingv1.Resource("service"), "tempService", fmt.Errorf("failure: i/o timeout")), - ErrorType: api_errors.IsConflict, - }, - { - Name: "i/o timeout", - Error: errors.New("Get https://api.example.com:27435/apis/foo/bar: dial tcp 192.168.1.1:27435: i/o timeout"), - ErrorType: func(err error) bool { - var kne *KNError - return errors.As(err, &kne) - }, - }, - } - for _, tc := range cases { - itc := tc - t.Run(tc.Name, func(t *testing.T) { - t.Parallel() - assert.Assert(t, itc.ErrorType(GetError(itc.Error))) - }) - } -} diff --git a/pkg/errors/knerror_test.go b/pkg/errors/knerror_test.go deleted file mode 100644 index 61e318b8b0..0000000000 --- a/pkg/errors/knerror_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2019 The Knative 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 errors - -import ( - "testing" - - "gotest.tools/v3/assert" -) - -func TestNewKNError(t *testing.T) { - err := NewKNError("myerror") - assert.Error(t, err, "myerror") - - err = NewKNError("") - assert.Error(t, err, "") -} - -func TestKNError_Error(t *testing.T) { - err := NewKNError("myerror") - assert.Equal(t, err.Error(), "myerror") - - err = NewKNError("") - assert.Equal(t, err.Error(), "") -} diff --git a/pkg/eventing/v1/client_mock_test.go b/pkg/eventing/v1/client_mock_test.go deleted file mode 100644 index 7a84792df0..0000000000 --- a/pkg/eventing/v1/client_mock_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "testing" - "time" - - eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" -) - -func TestMockKnClient(t *testing.T) { - - client := NewMockKnEventingClient(t) - - recorder := client.Recorder() - - // Record all services - recorder.GetTrigger("hello", nil, nil) - recorder.CreateTrigger(&eventingv1.Trigger{}, nil) - recorder.DeleteTrigger("hello", nil) - recorder.ListTriggers(nil, nil) - recorder.UpdateTrigger(&eventingv1.Trigger{}, nil) - recorder.GetTrigger("hello", &eventingv1.Trigger{}, nil) - recorder.UpdateTrigger(&eventingv1.Trigger{}, nil) - - recorder.CreateBroker(&eventingv1.Broker{}, nil) - recorder.GetBroker("foo", nil, nil) - recorder.DeleteBroker("foo", time.Duration(10)*time.Second, nil) - recorder.ListBrokers(nil, nil) - recorder.GetBroker("foo", &eventingv1.Broker{}, nil) - recorder.UpdateBroker(&eventingv1.Broker{}, nil) - recorder.UpdateBroker(&eventingv1.Broker{}, nil) - - // Call all service - ctx := context.Background() - client.GetTrigger(ctx, "hello") - client.CreateTrigger(ctx, &eventingv1.Trigger{}) - client.DeleteTrigger(ctx, "hello") - client.ListTriggers(ctx) - client.UpdateTrigger(ctx, &eventingv1.Trigger{}) - client.UpdateTriggerWithRetry(ctx, "hello", func(origTrigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return origTrigger, nil - }, 10) - - client.CreateBroker(ctx, &eventingv1.Broker{}) - client.GetBroker(ctx, "foo") - client.DeleteBroker(ctx, "foo", time.Duration(10)*time.Second) - client.ListBrokers(ctx) - client.UpdateBroker(ctx, &eventingv1.Broker{}) - client.UpdateBrokerWithRetry(ctx, "foo", func(origBroker *eventingv1.Broker) (*eventingv1.Broker, error) { - return origBroker, nil - }, 10) - - // Validate - recorder.Validate() -} diff --git a/pkg/eventing/v1/client_test.go b/pkg/eventing/v1/client_test.go deleted file mode 100644 index be4ba6ddd5..0000000000 --- a/pkg/eventing/v1/client_test.go +++ /dev/null @@ -1,769 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "fmt" - "testing" - "time" - - "gotest.tools/v3/assert" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - v1 "knative.dev/eventing/pkg/apis/duck/v1" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - client_testing "k8s.io/client-go/testing" - "knative.dev/client/pkg/wait" - eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" - "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1/fake" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" -) - -var ( - testNamespace = "test-ns" - testClass = "test-class" - testConfig = &duckv1.KReference{ - Kind: "ConfigMap", - Namespace: "test-ns", - Name: "test-cm", - APIVersion: "v1", - } -) - -func setup() (fakeSvr fake.FakeEventingV1, client KnEventingClient) { - fakeE := fake.FakeEventingV1{Fake: &client_testing.Fake{}} - cli := NewKnEventingClient(&fakeE, testNamespace) - return fakeE, cli -} - -func TestNamespace(t *testing.T) { - _, client := setup() - assert.Equal(t, testNamespace, client.Namespace()) -} - -func TestDeleteTrigger(t *testing.T) { - var name = "new-trigger" - server, client := setup() - - server.AddReactor("delete", "triggers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.DeleteAction).GetName() - if name == "errorTrigger" { - return true, nil, fmt.Errorf("error while deleting trigger %s", name) - } - return true, nil, nil - }) - - err := client.DeleteTrigger(context.Background(), name) - assert.NilError(t, err) - - err = client.DeleteTrigger(context.Background(), "errorTrigger") - assert.ErrorContains(t, err, "errorTrigger") -} - -func TestCreateTrigger(t *testing.T) { - var name = "new-trigger" - server, client := setup() - - objNew := newTrigger(name) - - server.AddReactor("create", "triggers", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(client_testing.CreateAction).GetObject().(metav1.Object).GetName() - if name == objNew.Name { - objNew.Generation = 2 - return true, objNew, nil - } - return true, nil, fmt.Errorf("error while creating trigger %s", name) - }) - - t.Run("create trigger without error", func(t *testing.T) { - err := client.CreateTrigger(context.Background(), objNew) - assert.NilError(t, err) - }) - - t.Run("create trigger with an error returns an error object", func(t *testing.T) { - err := client.CreateTrigger(context.Background(), newTrigger("unknown")) - assert.ErrorContains(t, err, "unknown") - }) -} - -func TestGetTrigger(t *testing.T) { - var name = "mytrigger" - server, client := setup() - - server.AddReactor("get", "triggers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.GetAction).GetName() - if name == "errorTrigger" { - return true, nil, fmt.Errorf("error while getting trigger %s", name) - } - return true, newTrigger(name), nil - }) - - trigger, err := client.GetTrigger(context.Background(), name) - assert.NilError(t, err) - assert.Equal(t, trigger.Name, name) - assert.Equal(t, trigger.Spec.Broker, "default") - - _, err = client.GetTrigger(context.Background(), "errorTrigger") - assert.ErrorContains(t, err, "errorTrigger") -} - -func TestListTrigger(t *testing.T) { - serving, client := setup() - - t.Run("list trigger returns a list of triggers", func(t *testing.T) { - trigger1 := newTrigger("trigger-1") - trigger2 := newTrigger("trigger-2") - - serving.AddReactor("list", "triggers", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, &eventingv1.TriggerList{Items: []eventingv1.Trigger{*trigger1, *trigger2}}, nil - }) - - listTriggers, err := client.ListTriggers(context.Background()) - assert.NilError(t, err) - assert.Assert(t, len(listTriggers.Items) == 2) - assert.Equal(t, listTriggers.Items[0].Name, "trigger-1") - assert.Equal(t, listTriggers.Items[1].Name, "trigger-2") - }) -} - -func TestUpdateTrigger(t *testing.T) { - serving, client := setup() - t.Run("update trigger will update the trigger", - func(t *testing.T) { - trigger := newTrigger("trigger-1") - errTrigger := newTrigger("errorTrigger") - serving.AddReactor("update", "triggers", - func(a client_testing.Action) (bool, runtime.Object, error) { - newTrigger := a.(client_testing.UpdateAction).GetObject() - name := newTrigger.(metav1.Object).GetName() - if name == "errorTrigger" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, trigger, nil - }) - err := client.UpdateTrigger(context.Background(), trigger) - assert.NilError(t, err) - err = client.UpdateTrigger(context.Background(), errTrigger) - assert.ErrorType(t, err, errors.IsInternalError) - }) -} - -func TestUpdateTriggerWithRetry(t *testing.T) { - serving, client := setup() - var attemptCount, maxAttempts = 0, 5 - serving.AddReactor("get", "triggers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.GetAction).GetName() - if name == "deletedTrigger" { - trigger := newTrigger(name) - now := metav1.Now() - trigger.DeletionTimestamp = &now - return true, trigger, nil - } - if name == "getErrorTrigger" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, newTrigger(name), nil - }) - - serving.AddReactor("update", "triggers", - func(a client_testing.Action) (bool, runtime.Object, error) { - newTrigger := a.(client_testing.UpdateAction).GetObject() - name := newTrigger.(metav1.Object).GetName() - - if name == "testTrigger" && attemptCount > 0 { - attemptCount-- - return true, nil, errors.NewConflict(eventingv1.Resource("trigger"), "errorTrigger", fmt.Errorf("error updating because of conflict")) - } - if name == "errorTrigger" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, NewTriggerBuilderFromExisting(newTrigger.(*eventingv1.Trigger)).Build(), nil - }) - - t.Run("Update trigger successfully without any retries", func(t *testing.T) { - err := client.UpdateTriggerWithRetry(context.Background(), "testTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, nil - }, maxAttempts) - assert.NilError(t, err, "No retries required as no conflict error occurred") - }) - - t.Run("Update trigger with retry after max retries", func(t *testing.T) { - attemptCount = maxAttempts - 1 - err := client.UpdateTriggerWithRetry(context.Background(), "testTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, nil - }, maxAttempts) - assert.NilError(t, err, "Update retried %d times and succeeded", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update trigger with retry and fail with conflict after exhausting max retries", func(t *testing.T) { - attemptCount = maxAttempts - err := client.UpdateTriggerWithRetry(context.Background(), "testTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update trigger with retry and fail with conflict after exhausting max retries", func(t *testing.T) { - attemptCount = maxAttempts - err := client.UpdateTriggerWithRetry(context.Background(), "testTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update trigger with retry fails with a non conflict error", func(t *testing.T) { - err := client.UpdateTriggerWithRetry(context.Background(), "errorTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - }) - - t.Run("Update trigger with retry fails with resource already deleted error", func(t *testing.T) { - err := client.UpdateTriggerWithRetry(context.Background(), "deletedTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, nil - }, maxAttempts) - assert.ErrorContains(t, err, "marked for deletion") - }) - - t.Run("Update trigger with retry fails with error from updateFunc", func(t *testing.T) { - err := client.UpdateTriggerWithRetry(context.Background(), "testTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, fmt.Errorf("error updating object") - }, maxAttempts) - assert.ErrorContains(t, err, "error updating object") - }) - - t.Run("Update trigger with retry fails with error from GetTrigger", func(t *testing.T) { - err := client.UpdateTriggerWithRetry(context.Background(), "getErrorTrigger", func(trigger *eventingv1.Trigger) (*eventingv1.Trigger, error) { - return trigger, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - }) -} - -func TestTriggerBuilder(t *testing.T) { - a := NewTriggerBuilder("testtrigger") - a.Filters(map[string]string{"type": "foo"}) - - t.Run("update filters", func(t *testing.T) { - b := NewTriggerBuilderFromExisting(a.Build()) - assert.DeepEqual(t, b.Build(), a.Build()) - b.Filters(map[string]string{"type": "new"}) - expected := &eventingv1.TriggerFilter{ - Attributes: eventingv1.TriggerFilterAttributes{ - "type": "new", - }, - } - assert.DeepEqual(t, expected, b.Build().Spec.Filter) - }) - - t.Run("update filters with both new entry and updated entry", func(t *testing.T) { - b := NewTriggerBuilderFromExisting(a.Build()) - assert.DeepEqual(t, b.Build(), a.Build()) - b.Filters(map[string]string{"type": "new", "source": "bar"}) - expected := &eventingv1.TriggerFilter{ - Attributes: eventingv1.TriggerFilterAttributes{ - "type": "new", - "source": "bar", - }, - } - assert.DeepEqual(t, expected, b.Build().Spec.Filter) - }) - - t.Run("update filters to remove filters", func(t *testing.T) { - b := NewTriggerBuilderFromExisting(a.Build()) - assert.DeepEqual(t, b.Build(), a.Build()) - b.Filters(nil) - expected := &eventingv1.TriggerFilter{} - assert.DeepEqual(t, expected, b.Build().Spec.Filter) - - b.Filters((make(map[string]string))) - assert.DeepEqual(t, expected, b.Build().Spec.Filter) - }) - - t.Run("add and remove inject annotation", func(t *testing.T) { - b := NewTriggerBuilder("broker-trigger") - b.InjectBroker(true) - expected := &metav1.ObjectMeta{ - Annotations: map[string]string{ - eventingv1.InjectionAnnotation: "enabled", - }, - } - assert.DeepEqual(t, expected.Annotations, b.Build().ObjectMeta.Annotations) - - b = NewTriggerBuilderFromExisting(b.Build()) - b.InjectBroker(false) - assert.DeepEqual(t, make(map[string]string), b.Build().ObjectMeta.Annotations) - - }) -} - -func TestWithGvk(t *testing.T) { - t.Run("Broker withGvk", func(t *testing.T) { - b := NewBrokerBuilder("test").WithGvk().Build() - assert.Assert(t, !b.GroupVersionKind().Empty()) - }) - t.Run("Trigger withGvk", func(t *testing.T) { - trigger := NewTriggerBuilder("test").WithGvk().Build() - assert.Assert(t, !trigger.GroupVersionKind().Empty()) - }) -} - -func TestBrokerCreate(t *testing.T) { - var name = "broker" - server, client := setup() - - objNew := newBroker(name) - brokerObjWithClass := newBrokerWithClass(name) - brokerObjWithDeliveryOptions := newBrokerWithDeliveryOptions(name) - brokerObjWithNilDeliveryOptions := newBrokerWithNilDeliveryOptions(name) - brokerObjWithConfig := newBrokerWithConfig(name) - - server.AddReactor("create", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(client_testing.CreateAction).GetObject().(metav1.Object).GetName() - if name == objNew.Name { - objNew.Generation = 2 - return true, objNew, nil - } - return true, nil, fmt.Errorf("error while creating broker %s", name) - }) - - t.Run("create broker without error", func(t *testing.T) { - err := client.CreateBroker(context.Background(), objNew) - assert.NilError(t, err) - }) - - t.Run("create broker with class without error", func(t *testing.T) { - err := client.CreateBroker(context.Background(), brokerObjWithClass) - assert.NilError(t, err) - }) - - t.Run("create broker with an error returns an error object", func(t *testing.T) { - err := client.CreateBroker(context.Background(), newBroker("unknown")) - assert.ErrorContains(t, err, "unknown") - }) - - t.Run("create broker with delivery options", func(t *testing.T) { - err := client.CreateBroker(context.Background(), brokerObjWithDeliveryOptions) - assert.NilError(t, err) - }) - - t.Run("create broker with nil delivery options", func(t *testing.T) { - err := client.CreateBroker(context.Background(), brokerObjWithNilDeliveryOptions) - assert.NilError(t, err) - }) - - t.Run("create broker with nil delivery spec", func(t *testing.T) { - builderFuncs := []func(builder *BrokerBuilder) *BrokerBuilder{ - func(builder *BrokerBuilder) *BrokerBuilder { - var sink = &duckv1.Destination{ - Ref: &duckv1.KReference{Name: "test-svc", Kind: "Service", APIVersion: "serving.knative.dev/v1", Namespace: "default"}, - } - return builder.DlSink(sink) - }, - func(builder *BrokerBuilder) *BrokerBuilder { - var retry int32 = 5 - return builder.Retry(&retry) - }, - func(builder *BrokerBuilder) *BrokerBuilder { - var timeout = "PT5S" - return builder.Timeout(&timeout) - }, - func(builder *BrokerBuilder) *BrokerBuilder { - var policy = v1.BackoffPolicyType("linear") - return builder.BackoffPolicy(&policy) - }, - func(builder *BrokerBuilder) *BrokerBuilder { - var delay = "PT5S" - return builder.BackoffDelay(&delay) - }, - func(builder *BrokerBuilder) *BrokerBuilder { - var max = "PT5S" - return builder.RetryAfterMax(&max) - }, - } - for _, bf := range builderFuncs { - brokerBuilder := NewBrokerBuilder(name) - brokerBuilder.broker.Spec.Delivery = nil - updatedBuilder := bf(brokerBuilder) - - broker := updatedBuilder.Build() - err := client.CreateBroker(context.Background(), broker) - assert.NilError(t, err) - } - }) - - t.Run("create broker with spec", func(t *testing.T) { - err := client.CreateBroker(context.Background(), brokerObjWithConfig) - assert.NilError(t, err) - }) -} - -func TestBrokerGet(t *testing.T) { - var name = "foo" - server, client := setup() - - server.AddReactor("get", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.GetAction).GetName() - if name == "errorBroker" { - return true, nil, fmt.Errorf("error while getting broker %s", name) - } - return true, newBroker(name), nil - }) - - broker, err := client.GetBroker(context.Background(), name) - assert.NilError(t, err) - assert.Equal(t, broker.Name, name) - - _, err = client.GetBroker(context.Background(), "errorBroker") - assert.ErrorContains(t, err, "errorBroker") -} - -func TestBrokerDelete(t *testing.T) { - var name = "fooBroker" - server, client := setup() - - server.AddReactor("get", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.GetAction).GetName() - if name == "notFound" { - return true, nil, errors.NewNotFound(eventingv1.Resource("broker"), "notFound") - } - return false, nil, nil - }) - server.AddReactor("delete", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.DeleteAction).GetName() - if name == "errorBroker" { - return true, nil, fmt.Errorf("error while deleting broker %s", name) - } - return false, nil, nil - }) - - err := client.DeleteBroker(context.Background(), name, 0) - assert.NilError(t, err) - - err = client.DeleteBroker(context.Background(), "errorBroker", 0) - assert.ErrorContains(t, err, "errorBroker", 0) - - err = client.DeleteBroker(context.Background(), "notFound", 0) - assert.ErrorContains(t, err, "not found", 0) - assert.ErrorContains(t, err, "notFound", 0) -} - -func TestBrokerDeleteWithWait(t *testing.T) { - var brokerName = "fooBroker" - var deleted = "deletedBroker" - server, client := setup() - - server.AddReactor("get", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.GetAction).GetName() - if name == deleted { - deletedBroker := newBroker(deleted) - deletedBroker.DeletionTimestamp = &metav1.Time{Time: time.Now()} - return true, deletedBroker, nil - } - return false, nil, nil - }) - server.AddReactor("delete", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.DeleteAction).GetName() - if name == "errorBroker" { - return true, nil, fmt.Errorf("error while deleting broker %s", name) - } - if name == deleted { - deletedBroker := newBroker(deleted) - deletedBroker.DeletionTimestamp = &metav1.Time{Time: time.Now()} - return true, deletedBroker, nil - } - return true, nil, nil - }) - server.AddWatchReactor("brokers", - func(a client_testing.Action) (bool, watch.Interface, error) { - watchAction := a.(client_testing.WatchAction) - name, found := watchAction.GetWatchRestrictions().Fields.RequiresExactMatch("metadata.name") - if !found { - return true, nil, errors.NewNotFound(eventingv1.Resource("broker"), name) - } - w := wait.NewFakeWatch(getBrokerDeleteEvents("fooBroker")) - w.Start() - return true, w, nil - }) - - err := client.DeleteBroker(context.Background(), brokerName, time.Duration(10)*time.Second) - assert.NilError(t, err) - - err = client.DeleteBroker(context.Background(), "errorBroker", time.Duration(10)*time.Second) - assert.ErrorContains(t, err, "errorBroker", time.Duration(10)*time.Second) - - err = client.DeleteBroker(context.Background(), deleted, time.Duration(10)*time.Second) - assert.ErrorContains(t, err, "marked for deletion") - assert.ErrorContains(t, err, deleted, time.Duration(10)*time.Second) -} - -func TestBrokerList(t *testing.T) { - serving, client := setup() - - t.Run("broker list returns a list of brokers", func(t *testing.T) { - broker1 := newBrokerWithGvk("foo1") - broker2 := newBrokerWithGvk("foo2") - - serving.AddReactor("list", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, &eventingv1.BrokerList{Items: []eventingv1.Broker{*broker1, *broker2}}, nil - }) - - brokerList, err := client.ListBrokers(context.Background()) - assert.NilError(t, err) - assert.Assert(t, len(brokerList.Items) == 2) - assert.Equal(t, brokerList.Items[0].Name, "foo1") - assert.Equal(t, brokerList.Items[1].Name, "foo2") - assert.Assert(t, !brokerList.GroupVersionKind().Empty()) - assert.Assert(t, !brokerList.Items[0].GroupVersionKind().Empty()) - }) -} - -func TestBrokerUpdate(t *testing.T) { - var name = "broker" - server, client := setup() - - obj := newBroker(name) - errorObj := newBroker("error-obj") - updatedObj := newBrokerWithDeliveryOptions(name) - - server.AddReactor("update", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(client_testing.UpdateAction).GetObject().(metav1.Object).GetName() - if name == "error-obj" { - return true, nil, fmt.Errorf("error while creating broker %s", name) - } - return true, updatedObj, nil - }) - server.AddReactor("get", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, obj, nil - }) - - t.Run("update broker without error", func(t *testing.T) { - err := client.UpdateBroker(context.Background(), updatedObj) - assert.NilError(t, err) - }) - - t.Run("create broker with an error returns an error object", func(t *testing.T) { - err := client.UpdateBroker(context.Background(), errorObj) - assert.ErrorContains(t, err, "error while creating broker") - }) -} - -func TestUpdateBrokerWithRetry(t *testing.T) { - serving, client := setup() - var attemptCount, maxAttempts = 0, 5 - serving.AddReactor("get", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - name := a.(client_testing.GetAction).GetName() - if name == "deletedBroker" { - broker := newBroker(name) - now := metav1.Now() - broker.DeletionTimestamp = &now - return true, broker, nil - } - if name == "getErrorBroker" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, newBroker(name), nil - }) - - serving.AddReactor("update", "brokers", - func(a client_testing.Action) (bool, runtime.Object, error) { - newBroker := a.(client_testing.UpdateAction).GetObject() - name := newBroker.(metav1.Object).GetName() - - if name == "testBroker" && attemptCount > 0 { - attemptCount-- - return true, nil, errors.NewConflict(eventingv1.Resource("broker"), "errorBroker", fmt.Errorf("error updating because of conflict")) - } - if name == "errorBroker" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, NewBrokerBuilderFromExisting(newBroker.(*eventingv1.Broker)).Build(), nil - }) - - t.Run("Update broker successfully without any retries", func(t *testing.T) { - err := client.UpdateBrokerWithRetry(context.Background(), "testBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, nil - }, maxAttempts) - assert.NilError(t, err, "No retries required as no conflict error occurred") - }) - - t.Run("Update broker with retry after max retries", func(t *testing.T) { - attemptCount = maxAttempts - 1 - err := client.UpdateBrokerWithRetry(context.Background(), "testBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, nil - }, maxAttempts) - assert.NilError(t, err, "Update retried %d times and succeeded", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update broker with retry and fail with conflict after exhausting max retries", func(t *testing.T) { - attemptCount = maxAttempts - err := client.UpdateBrokerWithRetry(context.Background(), "testBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update broker with retry and fail with conflict after exhausting max retries", func(t *testing.T) { - attemptCount = maxAttempts - err := client.UpdateBrokerWithRetry(context.Background(), "testBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update broker with retry fails with a non conflict error", func(t *testing.T) { - err := client.UpdateBrokerWithRetry(context.Background(), "errorBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - }) - - t.Run("Update broker with retry fails with resource already deleted error", func(t *testing.T) { - err := client.UpdateBrokerWithRetry(context.Background(), "deletedBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, nil - }, maxAttempts) - assert.ErrorContains(t, err, "marked for deletion") - }) - - t.Run("Update broker with retry fails with error from updateFunc", func(t *testing.T) { - err := client.UpdateBrokerWithRetry(context.Background(), "testBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, fmt.Errorf("error updating object") - }, maxAttempts) - assert.ErrorContains(t, err, "error updating object") - }) - - t.Run("Update broker with retry fails with error from GetBroker", func(t *testing.T) { - err := client.UpdateBrokerWithRetry(context.Background(), "getErrorBroker", func(broker *eventingv1.Broker) (*eventingv1.Broker, error) { - return broker, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - }) -} - -func newTrigger(name string) *eventingv1.Trigger { - return NewTriggerBuilder(name). - Namespace(testNamespace). - Broker("default"). - Filters(map[string]string{"type": "foo"}). - Build() -} - -func newBroker(name string) *eventingv1.Broker { - return NewBrokerBuilder(name). - Namespace(testNamespace). - Class(""). - Build() -} - -func newBrokerWithGvk(name string) *eventingv1.Broker { - return NewBrokerBuilder(name). - Namespace(testNamespace). - WithGvk(). - Build() -} - -func newBrokerWithClass(name string) *eventingv1.Broker { - return NewBrokerBuilder(name). - Namespace(testNamespace). - Class(testClass). - Build() -} -func newBrokerWithConfig(name string) *eventingv1.Broker { - return NewBrokerBuilder(name). - Namespace(testNamespace). - Class(testClass). - Config(testConfig). - Build() -} - -func newBrokerWithDeliveryOptions(name string) *eventingv1.Broker { - sink := &duckv1.Destination{ - Ref: &duckv1.KReference{Name: "test-svc", Kind: "Service", APIVersion: "serving.knative.dev/v1", Namespace: "default"}, - } - testTimeout := "PT10S" - retry := int32(2) - policy := v1.BackoffPolicyType("linear") - return NewBrokerBuilder(name). - Namespace(testNamespace). - DlSink(sink). - Timeout(&testTimeout). - Retry(&retry). - BackoffDelay(&testTimeout). - BackoffPolicy(&policy). - RetryAfterMax(&testTimeout). - Build() -} - -func newBrokerWithNilDeliveryOptions(name string) *eventingv1.Broker { - return NewBrokerBuilder(name). - Namespace(testNamespace). - DlSink(nil). - Timeout(nil). - Retry(nil). - BackoffDelay(nil). - BackoffPolicy(nil). - RetryAfterMax(nil). - Build() -} - -func getBrokerDeleteEvents(name string) []watch.Event { - return []watch.Event{ - {Type: watch.Added, Object: createBrokerWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")}, - {Type: watch.Modified, Object: createBrokerWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")}, - {Type: watch.Deleted, Object: createBrokerWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")}, - } -} - -func createBrokerWithConditions(name string, readyStatus corev1.ConditionStatus, otherReadyStatus corev1.ConditionStatus, reason string, message string) runtime.Object { - broker := newBroker(name) - broker.Status.Conditions = duckv1.Conditions([]apis.Condition{ - {Type: "ChannelServiceReady", Status: otherReadyStatus}, - {Type: apis.ConditionReady, Status: readyStatus, Reason: reason, Message: message}, - {Type: "Addressable", Status: otherReadyStatus}, - }) - return broker -} diff --git a/pkg/eventing/v1beta2/client_mock_test.go b/pkg/eventing/v1beta2/client_mock_test.go deleted file mode 100644 index b4160feab5..0000000000 --- a/pkg/eventing/v1beta2/client_mock_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2022 The Knative 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 v1beta2 - -import ( - "context" - "testing" - - "knative.dev/eventing/pkg/apis/eventing/v1beta2" -) - -func TestMockKnClient(t *testing.T) { - client := NewMockKnEventingV1beta2Client(t, "test-ns") - - recorder := client.Recorder() - - recorder.CreateEventtype(&v1beta2.EventType{}, nil) - recorder.GetEventtype("eventtype-name", &v1beta2.EventType{}, nil) - recorder.DeleteEventtype("eventtype-name", nil) - recorder.ListEventtypes(&v1beta2.EventTypeList{}, nil) - - ctx := context.Background() - client.CreateEventtype(ctx, &v1beta2.EventType{}) - client.GetEventtype(ctx, "eventtype-name") - client.DeleteEventtype(ctx, "eventtype-name") - client.ListEventtypes(ctx) - - recorder.Validate() -} diff --git a/pkg/eventing/v1beta2/client_test.go b/pkg/eventing/v1beta2/client_test.go deleted file mode 100644 index ebe0c076a8..0000000000 --- a/pkg/eventing/v1beta2/client_test.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright © 2022 The Knative 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 v1beta2 - -import ( - "context" - "fmt" - "testing" - - eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" - v1 "knative.dev/pkg/apis/duck/v1" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - client_testing "k8s.io/client-go/testing" - "knative.dev/eventing/pkg/apis/eventing/v1beta2" - "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake" - "knative.dev/pkg/apis" -) - -const ( - testNamespace = "test-ns" - testBroker = "test-broker" - testSource = "test.source" - testType = "test-type" - testName = "test-eventtype" - errName = "error-eventtype" -) - -func setup(ns string) (fakeSvr fake.FakeEventingV1beta2, client KnEventingV1Beta2Client) { - fakeE := fake.FakeEventingV1beta2{Fake: &client_testing.Fake{}} - cli := NewKnEventingV1Beta2Client(&fakeE, ns) - return fakeE, cli -} - -func TestNamespace(t *testing.T) { - _, client := setup(testNamespace) - assert.Equal(t, testNamespace, client.Namespace()) -} - -func TestBuilder(t *testing.T) { - et := newEventtypeWithSourceBroker(testName, testSource, testBroker) - assert.Equal(t, et.Name, testName) - assert.Equal(t, et.Spec.Reference.Name, testBroker) - source := et.Spec.Source - assert.Assert(t, source != nil) - assert.Equal(t, source.String(), testSource) -} - -func TestBuilderWithRefence(t *testing.T) { - ref := &v1.KReference{ - APIVersion: eventingv1.SchemeGroupVersion.String(), - Kind: "Broker", - Name: testBroker, - } - et := newEventtypeWithSourceRef(testName, testSource, ref) - assert.Equal(t, et.Name, testName) - assert.Equal(t, et.Spec.Reference, ref) - source := et.Spec.Source - assert.Assert(t, source != nil) - assert.Equal(t, source.String(), testSource) -} - -func TestKnEventingV1Beta1Client_CreateEventtype(t *testing.T) { - server, client := setup(testNamespace) - - server.AddReactor("create", "eventtypes", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - - name := a.(client_testing.CreateAction).GetObject().(metav1.Object).GetName() - if name == errName { - return true, nil, fmt.Errorf("error while creating eventtype %s", name) - } - return true, nil, nil - }) - ctx := context.Background() - - t.Run("create eventtype successfully", func(t *testing.T) { - objNew := newEventtype(testName) - err := client.CreateEventtype(ctx, objNew) - assert.NilError(t, err) - }) - t.Run("create eventtype with source and broker successfully", func(t *testing.T) { - objNew := newEventtypeWithSourceBroker(testName, testSource, testBroker) - err := client.CreateEventtype(ctx, objNew) - assert.NilError(t, err) - }) - t.Run("create eventtype with error", func(t *testing.T) { - objNew := newEventtype(errName) - err := client.CreateEventtype(ctx, objNew) - assert.ErrorContains(t, err, "error while creating eventtype") - }) -} - -func TestKnEventingV1Beta1Client_DeleteEventtype(t *testing.T) { - server, client := setup(testNamespace) - - server.AddReactor("delete", "eventtypes", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - - name := a.(client_testing.DeleteAction).GetName() - if name == errName { - return true, nil, fmt.Errorf("error while deleting eventtype %s", name) - } - return true, nil, nil - }) - ctx := context.Background() - - t.Run("delete eventtype successfully", func(t *testing.T) { - err := client.DeleteEventtype(ctx, testName) - assert.NilError(t, err) - }) - t.Run("delete eventtype with error", func(t *testing.T) { - err := client.DeleteEventtype(ctx, errName) - assert.ErrorContains(t, err, "error while deleting eventtype") - }) -} - -func TestKnEventingV1Beta1Client_GetEventtype(t *testing.T) { - server, client := setup(testNamespace) - - server.AddReactor("get", "eventtypes", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - - name := a.(client_testing.GetAction).GetName() - if name == errName { - return true, nil, fmt.Errorf("error while getting eventtype %s", name) - } - return true, newEventtype(testName), nil - }) - ctx := context.Background() - - t.Run("get eventtype successfully", func(t *testing.T) { - et, err := client.GetEventtype(ctx, testName) - assert.NilError(t, err) - assert.Equal(t, et.Name, testName) - }) - t.Run("get eventtype with error", func(t *testing.T) { - _, err := client.GetEventtype(ctx, errName) - assert.ErrorContains(t, err, "error while getting eventtype") - }) -} - -func TestKnEventingV1Beta1Client_ListEventtypes(t *testing.T) { - server, client := setup(testNamespace) - - server.AddReactor("list", "eventtypes", - func(a client_testing.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - - return true, &v1beta2.EventTypeList{Items: []v1beta2.EventType{ - *newEventtype("eventtype-1"), - *newEventtype("eventtype-2")}}, nil - }) - ctx := context.Background() - - list, err := client.ListEventtypes(ctx) - assert.NilError(t, err) - assert.Assert(t, list != nil) - assert.Equal(t, len(list.Items), 2) - assert.Equal(t, list.Items[0].Name, "eventtype-1") - assert.Equal(t, list.Items[1].Name, "eventtype-2") -} - -func newEventtypeWithSourceBroker(name string, source string, broker string) *v1beta2.EventType { - url, _ := apis.ParseURL(source) - return NewEventtypeBuilder(name). - Namespace(testNamespace). - WithGvk(). - Type(testType). - Source(url). - Broker(broker). - Build() -} - -func newEventtypeWithSourceRef(name string, source string, ref *v1.KReference) *v1beta2.EventType { - url, _ := apis.ParseURL(source) - return NewEventtypeBuilder(name). - Namespace(testNamespace). - WithGvk(). - Type(testType). - Source(url). - Reference(ref). - Build() -} - -func newEventtype(name string) *v1beta2.EventType { - return NewEventtypeBuilder(name). - Namespace(testNamespace). - Type(testType). - Build() -} diff --git a/pkg/kn/flags/bool.go b/pkg/flags/bool.go similarity index 100% rename from pkg/kn/flags/bool.go rename to pkg/flags/bool.go diff --git a/pkg/kn/flags/bool_test.go b/pkg/flags/bool_test.go similarity index 100% rename from pkg/kn/flags/bool_test.go rename to pkg/flags/bool_test.go diff --git a/pkg/kn/flags/channel_types.go b/pkg/flags/channel_types.go similarity index 99% rename from pkg/kn/flags/channel_types.go rename to pkg/flags/channel_types.go index 58d0e96a32..338dbfcd27 100644 --- a/pkg/kn/flags/channel_types.go +++ b/pkg/flags/channel_types.go @@ -25,7 +25,7 @@ import ( "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/client/pkg/kn/config" + "knative.dev/client/pkg/config" ) type ChannelTypeFlags struct { diff --git a/pkg/kn/flags/channel_types_test.go b/pkg/flags/channel_types_test.go similarity index 100% rename from pkg/kn/flags/channel_types_test.go rename to pkg/flags/channel_types_test.go diff --git a/pkg/kn/flags/podspec.go b/pkg/flags/podspec.go similarity index 99% rename from pkg/kn/flags/podspec.go rename to pkg/flags/podspec.go index 502cec14d5..9f49f8dba7 100644 --- a/pkg/kn/flags/podspec.go +++ b/pkg/flags/podspec.go @@ -20,7 +20,7 @@ import ( "strings" corev1 "k8s.io/api/core/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "github.com/spf13/pflag" ) diff --git a/pkg/kn/flags/podspec_helper.go b/pkg/flags/podspec_helper.go similarity index 99% rename from pkg/kn/flags/podspec_helper.go rename to pkg/flags/podspec_helper.go index 862b7b7b89..d1d9f1b4b8 100644 --- a/pkg/kn/flags/podspec_helper.go +++ b/pkg/flags/podspec_helper.go @@ -30,7 +30,7 @@ import ( corev1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/sets" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // VolumeSourceType is a type standing for enumeration of ConfigMap and Secret diff --git a/pkg/kn/flags/podspec_helper_test.go b/pkg/flags/podspec_helper_test.go similarity index 99% rename from pkg/kn/flags/podspec_helper_test.go rename to pkg/flags/podspec_helper_test.go index b9bac561f3..6be309efe8 100644 --- a/pkg/kn/flags/podspec_helper_test.go +++ b/pkg/flags/podspec_helper_test.go @@ -27,11 +27,11 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/api/resource" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" "gotest.tools/v3/assert" corev1 "k8s.io/api/core/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/ptr" ) diff --git a/pkg/kn/flags/podspec_test.go b/pkg/flags/podspec_test.go similarity index 99% rename from pkg/kn/flags/podspec_test.go rename to pkg/flags/podspec_test.go index aaec95b799..3b8df147af 100644 --- a/pkg/kn/flags/podspec_test.go +++ b/pkg/flags/podspec_test.go @@ -24,12 +24,12 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" "github.com/spf13/cobra" "gotest.tools/v3/assert" corev1 "k8s.io/api/core/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "knative.dev/pkg/ptr" ) diff --git a/pkg/kn/flags/resources.go b/pkg/flags/resources.go similarity index 98% rename from pkg/kn/flags/resources.go rename to pkg/flags/resources.go index b703604648..945d89d0d9 100644 --- a/pkg/kn/flags/resources.go +++ b/pkg/flags/resources.go @@ -18,7 +18,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // ResourceOptions to hold the container resource requirements values diff --git a/pkg/kn/flags/resources_test.go b/pkg/flags/resources_test.go similarity index 100% rename from pkg/kn/flags/resources_test.go rename to pkg/flags/resources_test.go diff --git a/pkg/kn/commands/flags/listprint_test.go b/pkg/kn/commands/flags/listprint_test.go deleted file mode 100644 index a5e8e0cd46..0000000000 --- a/pkg/kn/commands/flags/listprint_test.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright © 2019 The Knative 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 flags - -import ( - "bytes" - "testing" - "time" - - "github.com/spf13/cobra" - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/duration" - - "k8s.io/cli-runtime/pkg/genericclioptions" - "knative.dev/client/pkg/printers" - hprinters "knative.dev/client/pkg/printers" - "knative.dev/client/pkg/util" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -var ( - validPrintFunc = func(obj *servingv1.Service, opts printers.PrintOptions) ([]metav1beta1.TableRow, error) { - tableRow := metav1beta1.TableRow{ - Object: runtime.RawExtension{Object: obj}, - } - tableRow.Cells = append(tableRow.Cells, obj.Name, duration.HumanDuration(time.Since(obj.CreationTimestamp.Time))) - if opts.AllNamespaces { - tableRow.Cells = append(tableRow.Cells, obj.Namespace) - } - return []metav1.TableRow{tableRow}, nil - } - columnDefs = []metav1beta1.TableColumnDefinition{ - {Name: "Namespace", Type: "string", Description: "Namespace of mock instance", Priority: 0}, - {Name: "Name", Type: "string", Description: "Name of the mock instance", Priority: 1}, - {Name: "Age", Type: "string", Description: "Age of the mock instance", Priority: 1}, - } - myksvc = &servingv1.Service{ - TypeMeta: metav1.TypeMeta{Kind: "Service", APIVersion: "serving.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "myksvc", Namespace: "default"}, - } -) - -func TestListPrintFlagsFormats(t *testing.T) { - flags := NewListPrintFlags(nil) - formats := flags.AllowedFormats() - expected := []string{"json", "yaml", "name", "go-template", "go-template-file", "template", "templatefile", "jsonpath", "jsonpath-as-json", "jsonpath-file", "no-headers"} - assert.DeepEqual(t, formats, expected) -} - -func TestListPrintFlags(t *testing.T) { - var cmd *cobra.Command - flags := NewListPrintFlags(func(h hprinters.PrintHandler) {}) - - cmd = &cobra.Command{} - flags.AddFlags(cmd) - - assert.Assert(t, flags != nil) - assert.Assert(t, cmd.Flags() != nil) - - allowMissingTemplateKeys, err := cmd.Flags().GetBool("allow-missing-template-keys") - assert.NilError(t, err) - assert.Assert(t, allowMissingTemplateKeys == true) - - _, err = flags.ToPrinter() - assert.NilError(t, err) -} - -func TestListPrintFlagsPrint(t *testing.T) { - var cmd *cobra.Command - flags := NewListPrintFlags(func(h hprinters.PrintHandler) { - h.TableHandler(columnDefs, validPrintFunc) - }) - - cmd = &cobra.Command{} - var out bytes.Buffer - cmd.SetOut(&out) - flags.AddFlags(cmd) - - pr, err := flags.ToPrinter() - assert.NilError(t, err) - assert.Assert(t, pr != nil) - - err = flags.Print(nil, cmd.OutOrStdout()) - assert.NilError(t, err) - flags.GenericPrintFlags = genericclioptions.NewPrintFlags("mockOperation") - flags.GenericPrintFlags.OutputFlagSpecified = func() bool { - return true - } - err = flags.Print(myksvc, cmd.OutOrStdout()) - assert.NilError(t, err) - assert.Assert(t, util.ContainsAll(out.String(), "myksvc")) -} - -func TestEnsureNamespaces(t *testing.T) { - var cmd *cobra.Command - flags := NewListPrintFlags(func(h hprinters.PrintHandler) { - h.TableHandler(columnDefs, validPrintFunc) - }) - - cmd = &cobra.Command{} - var out bytes.Buffer - cmd.SetOut(&out) - flags.AddFlags(cmd) - err := flags.Print(myksvc, cmd.OutOrStderr()) - assert.NilError(t, err) - assert.Assert(t, util.ContainsAll(out.String(), "myksvc")) - assert.Assert(t, util.ContainsNone(out.String(), "default")) - flags.EnsureWithNamespace() - err = flags.Print(myksvc, cmd.OutOrStderr()) - assert.Assert(t, util.ContainsAll(out.String(), "default")) - assert.NilError(t, err) -} diff --git a/pkg/kn/commands/flags/sink_test.go b/pkg/kn/commands/flags/sink_test.go deleted file mode 100644 index 7e2800ca12..0000000000 --- a/pkg/kn/commands/flags/sink_test.go +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright © 2019 The Knative 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 flags - -import ( - "context" - "testing" - - "github.com/spf13/cobra" - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" - messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - "knative.dev/eventing/pkg/apis/sources/v1beta2" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - - dynamicfake "knative.dev/client/pkg/dynamic/fake" -) - -type resolveCase struct { - sink string - destination *duckv1.Destination - errContents string -} - -type sinkFlagAddTestCases struct { - flagName string - expectedFlagName string - expectedShortName string -} - -func TestSinkFlagAdd(t *testing.T) { - cases := []*sinkFlagAddTestCases{ - { - "", - "sink", - "s", - }, - { - "subscriber", - "subscriber", - "", - }, - } - for _, tc := range cases { - c := &cobra.Command{Use: "sinktest"} - sinkFlags := SinkFlags{} - if tc.flagName == "" { - sinkFlags.Add(c) - assert.Equal(t, tc.expectedFlagName, c.Flag("sink").Name) - assert.Equal(t, tc.expectedShortName, c.Flag("sink").Shorthand) - } else { - sinkFlags.AddWithFlagName(c, tc.flagName, "") - assert.Equal(t, tc.expectedFlagName, c.Flag(tc.flagName).Name) - assert.Equal(t, tc.expectedShortName, c.Flag(tc.flagName).Shorthand) - } - } -} - -func TestResolve(t *testing.T) { - targetExampleCom, err := apis.ParseURL("http://target.example.com") - assert.NilError(t, err) - - mysvc := &servingv1.Service{ - TypeMeta: metav1.TypeMeta{Kind: "Service", APIVersion: "serving.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "default"}, - } - defaultBroker := &eventingv1.Broker{ - TypeMeta: metav1.TypeMeta{Kind: "Broker", APIVersion: "eventing.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "default", Namespace: "default"}, - } - pipeChannel := &messagingv1.Channel{ - TypeMeta: metav1.TypeMeta{Kind: "Channel", APIVersion: "messaging.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "pipe", Namespace: "default"}, - } - pingSource := &v1beta2.PingSource{ - TypeMeta: metav1.TypeMeta{Kind: "PingSource", APIVersion: "sources.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}, - } - cases := []resolveCase{ - {"ksvc:mysvc", &duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Service", - APIVersion: "serving.knative.dev/v1", - Namespace: "default", - Name: "mysvc"}}, ""}, - {"mysvc", &duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Service", - APIVersion: "serving.knative.dev/v1", - Namespace: "default", - Name: "mysvc"}}, ""}, - {"ksvc:absent", nil, "\"absent\" not found"}, - {"broker:default", &duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Broker", - APIVersion: "eventing.knative.dev/v1", - Namespace: "default", - Name: "default"}}, ""}, - {"channel:pipe", - &duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Channel", - APIVersion: "messaging.knative.dev/v1", - Namespace: "default", - Name: "pipe", - }, - }, - ""}, - - {"sources.knative.dev/v1/pingsource:foo", &duckv1.Destination{Ref: &duckv1.KReference{ - APIVersion: "sources.knative.dev/v1", - Kind: "PingSource", - Namespace: "default", - Name: "foo", - }}, ""}, - {"sources.knative.dev/v1/pingsources:foo", &duckv1.Destination{Ref: &duckv1.KReference{ - APIVersion: "sources.knative.dev/v1", - Kind: "PingSource", - Namespace: "default", - Name: "foo", - }}, ""}, - {"sources.knative.dev/v1/Pingsource:foo", &duckv1.Destination{Ref: &duckv1.KReference{ - APIVersion: "sources.knative.dev/v1", - Kind: "PingSource", - Namespace: "default", - Name: "foo", - }}, ""}, - {"sources.knative.dev/v1/PingSources:foo", &duckv1.Destination{Ref: &duckv1.KReference{ - APIVersion: "sources.knative.dev/v1", - Kind: "PingSource", - Namespace: "default", - Name: "foo", - }}, ""}, - {"http://target.example.com", &duckv1.Destination{ - URI: targetExampleCom, - }, ""}, - {"k8ssvc:foo", nil, "k8ssvcs \"foo\" not found"}, - {"svc:foo", nil, "please use prefix 'ksvc' for knative service"}, - {"service:foo", nil, "please use prefix 'ksvc' for knative service"}, - {"absent:foo", nil, "absents \"foo\" not found"}, - } - dynamicClient := dynamicfake.CreateFakeKnDynamicClient("default", mysvc, defaultBroker, pipeChannel, pingSource) - - for _, c := range cases { - i := &SinkFlags{Sink: c.sink} - result, err := i.ResolveSink(context.Background(), dynamicClient, "default") - if c.destination != nil { - assert.DeepEqual(t, result, c.destination) - assert.NilError(t, err) - } else { - assert.ErrorContains(t, err, c.errContents) - } - } -} - -func TestResolveWithNamespace(t *testing.T) { - mysvc := &servingv1.Service{ - TypeMeta: metav1.TypeMeta{Kind: "Service", APIVersion: "serving.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "my-namespace"}, - } - defaultBroker := &eventingv1.Broker{ - TypeMeta: metav1.TypeMeta{Kind: "Broker", APIVersion: "eventing.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "default", Namespace: "my-namespace"}, - } - pipeChannel := &messagingv1.Channel{ - TypeMeta: metav1.TypeMeta{Kind: "Channel", APIVersion: "messaging.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "pipe", Namespace: "my-namespace"}, - } - - cases := []resolveCase{ - {"ksvc:mysvc:my-namespace", &duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Service", - APIVersion: "serving.knative.dev/v1", - Namespace: "my-namespace", - Name: "mysvc"}}, ""}, - {"broker:default:my-namespace", &duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Broker", - APIVersion: "eventing.knative.dev/v1", - Namespace: "my-namespace", - Name: "default"}}, ""}, - {"channel:pipe:my-namespace", &duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Channel", - APIVersion: "messaging.knative.dev/v1", - Namespace: "my-namespace", - Name: "pipe"}}, ""}, - } - dynamicClient := dynamicfake.CreateFakeKnDynamicClient("my-namespace", mysvc, defaultBroker, pipeChannel) - for _, c := range cases { - i := &SinkFlags{Sink: c.sink} - result, err := i.ResolveSink(context.Background(), dynamicClient, "default") - if c.destination != nil { - assert.DeepEqual(t, result, c.destination) - assert.Equal(t, c.destination.Ref.Namespace, "my-namespace") - assert.NilError(t, err) - } else { - assert.ErrorContains(t, err, c.errContents) - } - } -} - -func TestSinkToString(t *testing.T) { - sink := duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Service", - APIVersion: "serving.knative.dev/v1", - Namespace: "my-namespace", - Name: "mysvc"}} - expected := "ksvc:mysvc" - assert.Equal(t, expected, SinkToString(sink)) - sink = duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Broker", - APIVersion: "eventing.knative.dev/v1", - Namespace: "my-namespace", - Name: "default"}} - expected = "broker:default" - assert.Equal(t, expected, SinkToString(sink)) - sink = duckv1.Destination{ - Ref: &duckv1.KReference{Kind: "Service", - APIVersion: "v1", - Namespace: "my-namespace", - Name: "mysvc"}} - expected = "service:mysvc" - assert.Equal(t, expected, SinkToString(sink)) - - uri := "http://target.example.com" - targetExampleCom, err := apis.ParseURL(uri) - assert.NilError(t, err) - sink = duckv1.Destination{ - URI: targetExampleCom, - } - assert.Equal(t, uri, SinkToString(sink)) - assert.Equal(t, "", SinkToString(duckv1.Destination{})) -} diff --git a/pkg/kn/plugin/context_sharing.go b/pkg/plugin/context_sharing.go similarity index 99% rename from pkg/kn/plugin/context_sharing.go rename to pkg/plugin/context_sharing.go index 35ea0a1666..b9751417c3 100644 --- a/pkg/kn/plugin/context_sharing.go +++ b/pkg/plugin/context_sharing.go @@ -23,7 +23,7 @@ import ( "path/filepath" "strings" - "knative.dev/client/pkg/kn/config" + "knative.dev/client/pkg/config" ) //--TYPES-- diff --git a/pkg/kn/plugin/context_sharing_test.go b/pkg/plugin/context_sharing_test.go similarity index 100% rename from pkg/kn/plugin/context_sharing_test.go rename to pkg/plugin/context_sharing_test.go diff --git a/pkg/kn/plugin/context_types.go b/pkg/plugin/context_types.go similarity index 100% rename from pkg/kn/plugin/context_types.go rename to pkg/plugin/context_types.go diff --git a/pkg/kn/plugin/manager.go b/pkg/plugin/manager.go similarity index 100% rename from pkg/kn/plugin/manager.go rename to pkg/plugin/manager.go diff --git a/pkg/kn/plugin/manager_test.go b/pkg/plugin/manager_test.go similarity index 100% rename from pkg/kn/plugin/manager_test.go rename to pkg/plugin/manager_test.go diff --git a/pkg/kn/plugin/stat.go b/pkg/plugin/stat.go similarity index 100% rename from pkg/kn/plugin/stat.go rename to pkg/plugin/stat.go diff --git a/pkg/kn/plugin/stat_windows.go b/pkg/plugin/stat_windows.go similarity index 100% rename from pkg/kn/plugin/stat_windows.go rename to pkg/plugin/stat_windows.go diff --git a/pkg/kn/plugin/verify.go b/pkg/plugin/verify.go similarity index 100% rename from pkg/kn/plugin/verify.go rename to pkg/plugin/verify.go diff --git a/pkg/kn/plugin/verify_test.go b/pkg/plugin/verify_test.go similarity index 99% rename from pkg/kn/plugin/verify_test.go rename to pkg/plugin/verify_test.go index 921a5fd9fa..1da9c96358 100644 --- a/pkg/kn/plugin/verify_test.go +++ b/pkg/plugin/verify_test.go @@ -24,7 +24,7 @@ import ( "strconv" "testing" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "gotest.tools/v3/assert" ) diff --git a/pkg/printers/interface_test.go b/pkg/printers/interface_test.go deleted file mode 100644 index d7105c60a2..0000000000 --- a/pkg/printers/interface_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright © 2021 The Knative 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 printers - -import ( - "fmt" - "io" - "testing" - - "gotest.tools/v3/assert" - "k8s.io/apimachinery/pkg/runtime" -) - -func TestResourcePrintObj(t *testing.T) { - mockFunc := ResourcePrinterFunc(func(runtime.Object, io.Writer) error { - return fmt.Errorf(mockErrorString) - }) - assert.Error(t, mockFunc.PrintObj(nil, nil), mockErrorString) -} diff --git a/pkg/printers/prefixwriter_test.go b/pkg/printers/prefixwriter_test.go deleted file mode 100644 index c1e2f03916..0000000000 --- a/pkg/printers/prefixwriter_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright © 2019 The Knative 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 printers - -import ( - "bytes" - "testing" - - "gotest.tools/v3/assert" -) - -func TestWriteColsLn(t *testing.T) { - buf := &bytes.Buffer{} - w := NewBarePrefixWriter(buf) - sub := w.WriteColsLn("a", "bbbb", "c", "ddd") - sub.WriteColsLn("B", "C", "D", "E") - expected := "a\tbbbb\tc\tddd\n\tB\tC\tD\tE\n" - actual := buf.String() - assert.Equal(t, actual, expected) -} - -func TestWriteAttribute(t *testing.T) { - buf := &bytes.Buffer{} - w := NewBarePrefixWriter(buf) - sub := w.WriteAttribute("Thing", "Stuff") - sub.WriteColsLn("B", "C", "D", "E") - expected := "Thing:\tStuff\n B\tC\tD\tE\n" - actual := buf.String() - assert.Equal(t, actual, expected) -} - -func TestWriteNested(t *testing.T) { - buf := &bytes.Buffer{} - w := NewBarePrefixWriter(buf) - sub := w.WriteColsLn("*", "Header") - subsub := sub.WriteAttribute("Thing", "stuff") - subsub.WriteAttribute("Subthing", "substuff") - expected := "*\tHeader\n\tThing:\tstuff\n\t Subthing:\tsubstuff\n" - actual := buf.String() - assert.Equal(t, actual, expected) -} diff --git a/pkg/printers/tablegenerator_test.go b/pkg/printers/tablegenerator_test.go deleted file mode 100644 index fca8aaf89d..0000000000 --- a/pkg/printers/tablegenerator_test.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright © 2021 The Knative 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 printers - -import ( - "fmt" - "reflect" - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/duration" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - - "gotest.tools/v3/assert" - metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" -) - -const ( - mockErrorString = "This function returns an error" -) - -var ( - invalidPrintTypeFunc = true - invalidPrintFuncIncorrectInCount = func() ([]metav1beta1.TableRow, error) { return nil, nil } - invalidPrintFuncIncorrectInType = func(*servingv1.Service, bool) ([]metav1beta1.TableRow, error) { return nil, nil } - validPrintFunc = func(obj *servingv1.Service, opts PrintOptions) ([]metav1beta1.TableRow, error) { - tableRow := metav1beta1.TableRow{ - Object: runtime.RawExtension{Object: obj}, - } - tableRow.Cells = append(tableRow.Cells, obj.Namespace, obj.Name, duration.HumanDuration(time.Since(obj.CreationTimestamp.Time))) - return []metav1.TableRow{tableRow}, nil - } - validPrintFuncErrOutput = func(obj *servingv1.Service, opts PrintOptions) ([]metav1beta1.TableRow, error) { - return nil, fmt.Errorf(mockErrorString) - } - columnDefs = []metav1beta1.TableColumnDefinition{ - {Name: "Namespace", Type: "string", Description: "Namespace of mock instance", Priority: 0}, - {Name: "Name", Type: "string", Description: "Name of the mock instance", Priority: 1}, - {Name: "Age", Type: "string", Description: "Age of the mock instance", Priority: 1}, - } -) - -// Do we need this function? -func TestValidateRowPrintHandlerFunc(t *testing.T) { - assert.Error(t, ValidateRowPrintHandlerFunc(reflect.ValueOf(invalidPrintTypeFunc)), fmt.Sprintf("invalid print handler. %#v is not a function", reflect.ValueOf(invalidPrintTypeFunc))) - assert.Error(t, ValidateRowPrintHandlerFunc(reflect.ValueOf(invalidPrintFuncIncorrectInCount)), fmt.Sprintf("invalid print handler."+ - "Must accept 2 parameters and return 2 value.")) - assert.Error(t, ValidateRowPrintHandlerFunc(reflect.ValueOf(invalidPrintFuncIncorrectInType)), fmt.Sprintf("invalid print handler. The expected signature is: "+ - "func handler(obj %v, options PrintOptions) ([]metav1beta1.TableRow, error)", reflect.TypeOf(&servingv1.Service{}))) - assert.NilError(t, ValidateRowPrintHandlerFunc(reflect.ValueOf(validPrintFunc))) -} - -func TestTableHandler(t *testing.T) { - h := NewTableGenerator() - assert.ErrorContains(t, h.TableHandler(columnDefs, invalidPrintTypeFunc), "invalid print handler") - assert.ErrorContains(t, h.TableHandler(columnDefs, invalidPrintFuncIncorrectInCount), "invalid print handler") - assert.ErrorContains(t, h.TableHandler(columnDefs, invalidPrintFuncIncorrectInType), "invalid print handler") - assert.NilError(t, h.TableHandler(columnDefs, validPrintFunc)) - assert.ErrorContains(t, h.TableHandler(columnDefs, validPrintFunc), "registered duplicate printer") -} - -func TestGenerateTable(t *testing.T) { - h := NewTableGenerator() - myksvc := &servingv1.Service{ - TypeMeta: metav1.TypeMeta{Kind: "Service", APIVersion: "serving.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "myksvc", Namespace: "default"}, - } - _, err := h.GenerateTable(myksvc, h.options) - assert.ErrorContains(t, err, "no table handler registered for this type") - err = h.TableHandler(columnDefs, validPrintFunc) - assert.NilError(t, err) - table, err := h.GenerateTable(myksvc, h.options) - assert.NilError(t, err) - expected := metav1beta1.TableRow{ - Object: runtime.RawExtension{Object: myksvc}, - } - expected.Cells = append(expected.Cells, myksvc.Namespace, myksvc.Name, duration.HumanDuration(time.Since(myksvc.CreationTimestamp.Time))) - assert.DeepEqual(t, table.Rows[0], expected) - - myksvcList := &servingv1.ServiceList{ - TypeMeta: metav1.TypeMeta{}, - ListMeta: metav1.ListMeta{}, - Items: []servingv1.Service{*myksvc}, - } - - printServiceList := func(objList *servingv1.ServiceList, opts PrintOptions) ([]metav1beta1.TableRow, error) { - rows := make([]metav1beta1.TableRow, 0, len(objList.Items)) - for _, obj := range objList.Items { - row, err := validPrintFunc(&obj, h.options) - assert.NilError(t, err) - rows = append(rows, row...) - } - return rows, nil - } - err = h.TableHandler(columnDefs, printServiceList) - assert.NilError(t, err) - table, err = h.GenerateTable(myksvcList, h.options) - assert.NilError(t, err) - assert.DeepEqual(t, table.Rows[0], expected) - - // Create new human readable printer - h = NewTableGenerator() - assert.NilError(t, h.TableHandler(columnDefs, validPrintFuncErrOutput)) - _, err = h.GenerateTable(myksvc, h.options) - assert.Error(t, err, mockErrorString) -} diff --git a/pkg/printers/tableprinter_test.go b/pkg/printers/tableprinter_test.go deleted file mode 100644 index 5f4d31a78f..0000000000 --- a/pkg/printers/tableprinter_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2021 The Knative 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 printers - -import ( - "bytes" - "os" - "testing" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/client/pkg/util" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -func TestPrintObj(t *testing.T) { - h := NewTablePrinter(PrintOptions{}) - assert.Assert(t, h != nil) - assert.NilError(t, h.PrintObj(nil, nil)) - - myksvc := &servingv1.Service{ - TypeMeta: metav1.TypeMeta{Kind: "Service", APIVersion: "serving.knative.dev/v1"}, - ObjectMeta: metav1.ObjectMeta{Name: "myksvc", Namespace: "default"}, - } - assert.ErrorContains(t, h.PrintObj(myksvc, os.Stdout), "unknown type") - h.TableHandler(columnDefs, validPrintFunc) - var out bytes.Buffer - assert.NilError(t, h.PrintObj(myksvc, &out)) - assert.Assert(t, util.ContainsAll(out.String(), "myksvc")) - h = NewTablePrinter(PrintOptions{}) - h.TableHandler(columnDefs, validPrintFuncErrOutput) - assert.Error(t, h.PrintObj(myksvc, os.Stdout), mockErrorString) -} diff --git a/pkg/kn/root/root.go b/pkg/root/root.go similarity index 87% rename from pkg/kn/root/root.go rename to pkg/root/root.go index 1b3abe1523..9353fca871 100644 --- a/pkg/kn/root/root.go +++ b/pkg/root/root.go @@ -22,31 +22,31 @@ import ( "strings" "text/template" - "knative.dev/client/pkg/kn/commands/secret" + "knative.dev/client/pkg/commands/secret" "github.com/spf13/cobra" // Import & enable all auth providers at once _ "k8s.io/client-go/plugin/pkg/client/auth" - "knative.dev/client/pkg/kn/commands" - "knative.dev/client/pkg/kn/commands/broker" - "knative.dev/client/pkg/kn/commands/channel" - "knative.dev/client/pkg/kn/commands/completion" - "knative.dev/client/pkg/kn/commands/container" - "knative.dev/client/pkg/kn/commands/domain" - "knative.dev/client/pkg/kn/commands/eventtype" - "knative.dev/client/pkg/kn/commands/options" - "knative.dev/client/pkg/kn/commands/plugin" - "knative.dev/client/pkg/kn/commands/revision" - "knative.dev/client/pkg/kn/commands/route" - "knative.dev/client/pkg/kn/commands/service" - "knative.dev/client/pkg/kn/commands/source" - "knative.dev/client/pkg/kn/commands/subscription" - "knative.dev/client/pkg/kn/commands/trigger" - "knative.dev/client/pkg/kn/commands/version" - "knative.dev/client/pkg/kn/config" - "knative.dev/client/pkg/kn/flags" + "knative.dev/client/pkg/commands" + "knative.dev/client/pkg/commands/broker" + "knative.dev/client/pkg/commands/channel" + "knative.dev/client/pkg/commands/completion" + "knative.dev/client/pkg/commands/container" + "knative.dev/client/pkg/commands/domain" + "knative.dev/client/pkg/commands/eventtype" + "knative.dev/client/pkg/commands/options" + "knative.dev/client/pkg/commands/plugin" + "knative.dev/client/pkg/commands/revision" + "knative.dev/client/pkg/commands/route" + "knative.dev/client/pkg/commands/service" + "knative.dev/client/pkg/commands/source" + "knative.dev/client/pkg/commands/subscription" + "knative.dev/client/pkg/commands/trigger" + "knative.dev/client/pkg/commands/version" + "knative.dev/client/pkg/config" + "knative.dev/client/pkg/flags" "knative.dev/client/pkg/templates" ) diff --git a/pkg/kn/root/root_test.go b/pkg/root/root_test.go similarity index 99% rename from pkg/kn/root/root_test.go rename to pkg/root/root_test.go index 52cc4f3a83..a20b490296 100644 --- a/pkg/kn/root/root_test.go +++ b/pkg/root/root_test.go @@ -23,7 +23,7 @@ import ( "github.com/spf13/cobra" "gotest.tools/v3/assert" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func TestNewRootCommand(t *testing.T) { diff --git a/pkg/serving/config_changes_test.go b/pkg/serving/config_changes_test.go deleted file mode 100644 index 1aa21e8302..0000000000 --- a/pkg/serving/config_changes_test.go +++ /dev/null @@ -1,589 +0,0 @@ -// Copyright © 2019 The Knative 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 serving - -import ( - "reflect" - "strconv" - "testing" - - "gotest.tools/v3/assert" - - "knative.dev/pkg/ptr" - "knative.dev/serving/pkg/apis/autoscaling" - - "knative.dev/client/pkg/util" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -func TestUpdateScalingAnnotations(t *testing.T) { - template := &servingv1.RevisionTemplateSpec{} - updateConcurrencyConfiguration(template, 10, 100, 1000, 1000, 50) - annos := template.Annotations - if annos[autoscaling.MinScaleAnnotationKey] != "10" { - t.Error("minScale failed") - } - if annos[autoscaling.MaxScaleAnnotationKey] != "100" { - t.Error("maxScale failed") - } - if annos[autoscaling.TargetAnnotationKey] != "1000" { - t.Error("target failed") - } - if *template.Spec.ContainerConcurrency != int64(1000) { - t.Error("limit failed") - } -} - -func TestUpdateInvalidScalingAnnotations(t *testing.T) { - template := &servingv1.RevisionTemplateSpec{} - updateConcurrencyConfiguration(template, 10, 100, 1000, 1000, 50) - // Update with invalid concurrency options - updateConcurrencyConfiguration(template, -1, -1, 0, -1, 200) - annos := template.Annotations - if annos[autoscaling.MinScaleAnnotationKey] != "10" { - t.Error("minScale failed") - } - if annos[autoscaling.MaxScaleAnnotationKey] != "100" { - t.Error("maxScale failed") - } - if annos[autoscaling.TargetAnnotationKey] != "1000" { - t.Error("target failed") - } - if annos[autoscaling.TargetUtilizationPercentageKey] != "50" { - t.Error("concurrency utilization failed") - } - if *template.Spec.ContainerConcurrency != 1000 { - t.Error("limit failed") - } -} - -type userImageAnnotCase struct { - image string - annot string - result string - set bool -} - -func TestSetUserImageAnnotation(t *testing.T) { - cases := []userImageAnnotCase{ - {"foo/bar", "", "foo/bar", true}, - {"foo/bar@sha256:asdfsf", "", "foo/bar@sha256:asdfsf", true}, - {"foo/bar@sha256:asdf", "foo/bar", "foo/bar", true}, - {"foo/bar", "baz/quux", "foo/bar", true}, - {"foo/bar", "", "", false}, - {"foo/bar", "baz/quux", "", false}, - } - for _, c := range cases { - template, container := getRevisionTemplate() - if c.annot == "" { - template.Annotations = nil - } else { - template.Annotations = map[string]string{ - UserImageAnnotationKey: c.annot, - } - } - container.Image = c.image - if c.set { - UpdateUserImageAnnotation(template) - } else { - UnsetUserImageAnnotation(template) - } - assert.Equal(t, template.Annotations[UserImageAnnotationKey], c.result) - } -} - -func TestPinImageToDigest(t *testing.T) { - template, container := getRevisionTemplate() - revision := &servingv1.Revision{} - revision.Spec = template.Spec - revision.ObjectMeta = template.ObjectMeta - revision.Status.ContainerStatuses = []servingv1.ContainerStatus{ - {Name: "user-container", ImageDigest: "gcr.io/foo/bar@sha256:deadbeef"}, - } - container.Image = "gcr.io/foo/bar:latest" - err := PinImageToDigest(template, revision) - assert.NilError(t, err) - assert.Equal(t, container.Image, "gcr.io/foo/bar@sha256:deadbeef") - - // No base revision --> no-op - err = PinImageToDigest(template, nil) - assert.NilError(t, err) -} - -func TestPinImageToDigestInvalidImages(t *testing.T) { - template, container := getRevisionTemplate() - container.Image = "gcr.io/A" - revision := &servingv1.Revision{ - Spec: servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{ - {Image: "gcr.io/B"}, - }, - }, - }, - } - err := PinImageToDigest(template, revision) - assert.ErrorContains(t, err, "unexpected image") -} - -func TestPinImageToDigestNilContainerStatus(t *testing.T) { - template, _ := getRevisionTemplate() - revision := &servingv1.Revision{} - revision.Spec = template.Spec - revision.ObjectMeta = template.ObjectMeta - revision.Status.ContainerStatuses = nil - err := PinImageToDigest(template, revision) - assert.NilError(t, err) -} - -func TestPinImageToDigestNilContainerSpec(t *testing.T) { - template, _ := getRevisionTemplate() - template.Spec.Containers = nil - revision := &servingv1.Revision{} - revision.Spec = template.Spec - revision.ObjectMeta = template.ObjectMeta - revision.Status.ContainerStatuses = nil - err := PinImageToDigest(template, revision) - assert.ErrorContains(t, err, "no container given in current revision") -} - -func TestPinImageToDigestNilBaseRevisionContainerSpec(t *testing.T) { - template, _ := getRevisionTemplate() - revision := &servingv1.Revision{} - revision.Spec = template.Spec - revision.ObjectMeta = template.ObjectMeta - revision.Status.ContainerStatuses = nil - - revision.Spec.Containers = nil - err := PinImageToDigest(template, revision) - assert.ErrorContains(t, err, "no container found in base revision") -} - -func TestPinImageToDigestImageMismatch(t *testing.T) { - template, _ := getRevisionTemplate() - revision := &servingv1.Revision{} - revision.Spec = template.Spec - revision.ObjectMeta = template.ObjectMeta - revision.Status.ContainerStatuses = nil - - revision.Spec.Containers = []corev1.Container{{Image: "mock-image"}} - err := PinImageToDigest(template, revision) - assert.ErrorContains(t, err, "contains unexpected image") -} - -func TestUpdateTimestampAnnotation(t *testing.T) { - template, _ := getRevisionTemplate() - UpdateTimestampAnnotation(template) - assert.Assert(t, template.Annotations[UpdateTimestampAnnotationKey] != "") -} - -func TestUpdateMinScale(t *testing.T) { - template, _ := getRevisionTemplate() - err := UpdateMinScale(template, 10) - assert.NilError(t, err) - // Verify update is successful or not - checkAnnotationValueInt(t, template, autoscaling.MinScaleAnnotationKey, 10) - // Update with invalid value - err = UpdateMinScale(template, -1) - assert.ErrorContains(t, err, "min-scale") -} - -func TestUpdateMaxScale(t *testing.T) { - template, _ := getRevisionTemplate() - err := UpdateMaxScale(template, 10) - assert.NilError(t, err) - // Verify update is successful or not - checkAnnotationValueInt(t, template, autoscaling.MaxScaleAnnotationKey, 10) - // Update with invalid value - err = UpdateMaxScale(template, -1) - assert.ErrorContains(t, err, "max-scale") -} - -func TestScaleWindow(t *testing.T) { - template, _ := getRevisionTemplate() - err := UpdateScaleWindow(template, "10s") - assert.NilError(t, err) - // Verify update is successful or not - checkAnnotationValue(t, template, autoscaling.WindowAnnotationKey, "10s") - // Update with invalid value - err = UpdateScaleWindow(template, "blub") - assert.Check(t, util.ContainsAll(err.Error(), "invalid duration", "scale-window")) -} - -func TestUpdateConcurrencyTarget(t *testing.T) { - template, _ := getRevisionTemplate() - err := UpdateScaleTarget(template, 10) - assert.NilError(t, err) - // Verify update is successful or not - checkAnnotationValueInt(t, template, autoscaling.TargetAnnotationKey, 10) - // Update with invalid value - err = UpdateScaleTarget(template, -1) - assert.ErrorContains(t, err, "should be at least 0.01") -} - -func TestUpdateConcurrencyLimit(t *testing.T) { - template, _ := getRevisionTemplate() - err := UpdateConcurrencyLimit(template, 10) - assert.NilError(t, err) - // Verify update is successful or not - checkContainerConcurrency(t, template, ptr.Int64(int64(10))) - // Update with invalid value - err = UpdateConcurrencyLimit(template, -1) - assert.ErrorContains(t, err, "invalid") -} - -// func TestUpdateEnvVarsBoth(t *testing.T) { -// template, container := getRevisionTemplate() -// container.Env = []corev1.EnvVar{ -// {Name: "a", Value: "foo"}, -// {Name: "c", Value: "caroline"}, -// {Name: "d", Value: "byebye"}, -// } -// env := map[string]string{ -// "a": "fancy", -// "b": "boo", -// } -// remove := []string{"d"} -// err := UpdateEnvVars(template, env, remove) -// assert.NilError(t, err) - -// expected := []corev1.EnvVar{ -// {Name: "a", Value: "fancy"}, -// {Name: "b", Value: "boo"}, -// {Name: "c", Value: "caroline"}, -// } - -// assert.DeepEqual(t, expected, container.Env) -// } - -func TestUpdateLabelsNew(t *testing.T) { - service, template, _ := getService() - - labels := map[string]string{ - "a": "foo", - "b": "bar", - } - - service.ObjectMeta.Labels = UpdateLabels(service.ObjectMeta.Labels, labels, []string{}) - template.ObjectMeta.Labels = UpdateLabels(template.ObjectMeta.Labels, labels, []string{}) - - actual := service.ObjectMeta.Labels - if !reflect.DeepEqual(labels, actual) { - t.Fatalf("Service labels did not match expected %v found %v", labels, actual) - } - - actual = template.ObjectMeta.Labels - if !reflect.DeepEqual(labels, actual) { - t.Fatalf("Template labels did not match expected %v found %v", labels, actual) - } -} - -func TestUpdateLabelsExisting(t *testing.T) { - service, template, _ := getService() - service.ObjectMeta.Labels = map[string]string{"a": "foo", "b": "bar"} - template.ObjectMeta.Labels = map[string]string{"a": "foo", "b": "bar"} - - labels := map[string]string{ - "a": "notfoo", - "c": "bat", - "d": "", - } - tlabels := map[string]string{ - "a": "notfoo", - "c": "bat", - "d": "", - "r": "poo", - } - - service.ObjectMeta.Labels = UpdateLabels(service.ObjectMeta.Labels, labels, []string{}) - template.ObjectMeta.Labels = UpdateLabels(template.ObjectMeta.Labels, tlabels, []string{}) - - expectedServiceLabel := map[string]string{ - "a": "notfoo", - "b": "bar", - "c": "bat", - "d": "", - } - expectedRevLabel := map[string]string{ - "a": "notfoo", - "b": "bar", - "c": "bat", - "d": "", - "r": "poo", - } - - actual := service.ObjectMeta.Labels - assert.DeepEqual(t, expectedServiceLabel, actual) - - actual = template.ObjectMeta.Labels - assert.DeepEqual(t, expectedRevLabel, actual) -} - -func TestUpdateLabelsRemoveExisting(t *testing.T) { - service, template, _ := getService() - service.ObjectMeta.Labels = map[string]string{"a": "foo", "b": "bar"} - template.ObjectMeta.Labels = map[string]string{"a": "foo", "b": "bar"} - - remove := []string{"b"} - service.ObjectMeta.Labels = UpdateLabels(service.ObjectMeta.Labels, map[string]string{}, remove) - template.ObjectMeta.Labels = UpdateLabels(template.ObjectMeta.Labels, map[string]string{}, remove) - - expected := map[string]string{ - "a": "foo", - } - - actual := service.ObjectMeta.Labels - assert.DeepEqual(t, expected, actual) - - actual = template.ObjectMeta.Labels - assert.DeepEqual(t, expected, actual) -} - -func TestUpdateRevisionTemplateAnnotationsNew(t *testing.T) { - _, template, _ := getService() - - annotations := map[string]string{ - autoscaling.InitialScaleAnnotationKey: "1", - autoscaling.MaxScaleAnnotationKey: "2", - } - err := UpdateRevisionTemplateAnnotations(template, annotations, []string{}) - assert.NilError(t, err) - - actual := template.ObjectMeta.Annotations - assert.DeepEqual(t, annotations, actual) -} - -func TestUpdateRevisionTemplateAnnotationsExisting(t *testing.T) { - _, template, _ := getService() - template.ObjectMeta.Annotations = map[string]string{ - autoscaling.InitialScaleAnnotationKey: "1", - autoscaling.MaxScaleAnnotationKey: "2", - } - - annotations := map[string]string{ - autoscaling.InitialScaleAnnotationKey: "5", - autoscaling.MaxScaleAnnotationKey: "10", - } - err := UpdateRevisionTemplateAnnotations(template, annotations, []string{}) - assert.NilError(t, err) - - actual := template.ObjectMeta.Annotations - assert.DeepEqual(t, annotations, actual) -} - -func TestUpdateRevisionTemplateAnnotationsRemoveExisting(t *testing.T) { - _, template, _ := getService() - template.ObjectMeta.Annotations = map[string]string{ - autoscaling.InitialScaleAnnotationKey: "1", - autoscaling.MaxScaleAnnotationKey: "2", - } - expectedAnnotations := map[string]string{ - autoscaling.InitialScaleAnnotationKey: "1", - } - remove := []string{autoscaling.MaxScaleAnnotationKey} - err := UpdateRevisionTemplateAnnotations(template, map[string]string{}, remove) - assert.NilError(t, err) - - actual := template.ObjectMeta.Annotations - assert.DeepEqual(t, expectedAnnotations, actual) -} - -func TestUpdateAnnotationsNew(t *testing.T) { - service, _, _ := getService() - - annotations := map[string]string{ - "a": "foo", - "b": "bar", - } - err := UpdateServiceAnnotations(service, annotations, []string{}) - assert.NilError(t, err) - - actual := service.ObjectMeta.Annotations - if !reflect.DeepEqual(annotations, actual) { - t.Fatalf("Service annotations did not match expected %v found %v", annotations, actual) - } -} - -func TestUpdateAnnotationsExisting(t *testing.T) { - service, _, _ := getService() - service.ObjectMeta.Annotations = map[string]string{"a": "foo", "b": "bar"} - - annotations := map[string]string{ - "a": "notfoo", - "c": "bat", - "d": "", - } - err := UpdateServiceAnnotations(service, annotations, []string{}) - assert.NilError(t, err) - expected := map[string]string{ - "a": "notfoo", - "b": "bar", - "c": "bat", - "d": "", - } - - actual := service.ObjectMeta.Annotations - assert.DeepEqual(t, expected, actual) -} - -func TestUpdateAnnotationsRemoveExisting(t *testing.T) { - service, _, _ := getService() - service.ObjectMeta.Annotations = map[string]string{"a": "foo", "b": "bar"} - - remove := []string{"b"} - err := UpdateServiceAnnotations(service, map[string]string{}, remove) - assert.NilError(t, err) - expected := map[string]string{ - "a": "foo", - } - - actual := service.ObjectMeta.Annotations - assert.DeepEqual(t, expected, actual) -} - -func TestUpdateScaleMetric(t *testing.T) { - type args struct { - template *servingv1.RevisionTemplateSpec - metric string - } - tests := []struct { - name string - args args - }{ - { - "Update scale metric to rps", - args{ - &servingv1.RevisionTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Name: "template-foo", - Namespace: "default", - Annotations: map[string]string{ - autoscaling.MetricAnnotationKey: "rps", - }, - }, - Spec: servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{{}}, - }, - }, - }, - "rps", - }, - }, - { - "Update scale metric to cpu", - args{ - &servingv1.RevisionTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Name: "template-foo", - Namespace: "default", - Annotations: map[string]string{ - autoscaling.MetricAnnotationKey: "concurrency", - }, - }, - Spec: servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{{}}, - }, - }, - }, - "concurrency", - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualTemplate, _ := getRevisionTemplate() - UpdateScaleMetric(actualTemplate, tt.args.metric) - assert.DeepEqual(t, tt.args.template, actualTemplate) - }) - } -} - -func TestString(t *testing.T) { - vt := ConfigMapVolumeSourceType - assert.Equal(t, "config-map", vt.String()) - vt = -1 - assert.Equal(t, "unknown", vt.String()) -} - -// -// ========================================================================================================= - -func getRevisionTemplate() (*servingv1.RevisionTemplateSpec, *corev1.Container) { - template := &servingv1.RevisionTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Name: "template-foo", - Namespace: "default", - }, - Spec: servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{{}}, - }, - }, - } - return template, &template.Spec.Containers[0] -} - -func getService() (*servingv1.Service, *servingv1.RevisionTemplateSpec, *corev1.Container) { - template, container := getRevisionTemplate() - service := &servingv1.Service{ - TypeMeta: metav1.TypeMeta{ - Kind: "Service", - APIVersion: "serving.knative.dev/v1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "default", - }, - Spec: servingv1.ServiceSpec{ - ConfigurationSpec: servingv1.ConfigurationSpec{ - Template: *template, - }, - }, - } - return service, template, container -} - -func checkAnnotationValueInt(t *testing.T, template *servingv1.RevisionTemplateSpec, key string, value int) { - anno := template.GetAnnotations() - if v, ok := anno[key]; !ok && v != strconv.Itoa(value) { - t.Errorf("Failed to update %s annotation key: got=%s, want=%d", key, v, value) - } -} - -func checkAnnotationValue(t *testing.T, template *servingv1.RevisionTemplateSpec, key string, value string) { - anno := template.GetAnnotations() - if v, ok := anno[key]; !ok && v != value { - t.Errorf("Failed to update %s annotation key: got=%s, want=%s", key, v, value) - } -} - -func checkContainerConcurrency(t *testing.T, template *servingv1.RevisionTemplateSpec, value *int64) { - if got, want := *template.Spec.ContainerConcurrency, *value; got != want { - t.Errorf("Failed to update containerConcurrency value: got=%d, want=%d", got, want) - } -} - -func updateConcurrencyConfiguration(template *servingv1.RevisionTemplateSpec, minScale, maxScale, target, limit, utilization int) { - UpdateMinScale(template, minScale) - UpdateMaxScale(template, maxScale) - UpdateScaleTarget(template, target) - UpdateConcurrencyLimit(template, int64(limit)) - UpdateScaleUtilization(template, utilization) -} diff --git a/pkg/serving/revision_template_test.go b/pkg/serving/revision_template_test.go deleted file mode 100644 index a152719b0e..0000000000 --- a/pkg/serving/revision_template_test.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright © 2019 The Knative 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 serving - -import ( - "testing" - - corev1 "k8s.io/api/core/v1" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "knative.dev/serving/pkg/apis/autoscaling" -) - -type scalingInfoTest struct { - min string - max string - minRes int - maxRes int - e bool -} - -func TestScalingInfo(t *testing.T) { - sentinel := -0xdead - tests := []scalingInfoTest{ - {"3", "4", 3, 4, false}, - {"", "5", sentinel, 5, false}, - {"4", "", 4, sentinel, false}, - {"", "", sentinel, sentinel, false}, - {"", "funtimes", sentinel, sentinel, true}, - } - for _, c := range tests { - m := metav1.ObjectMeta{} - m.Annotations = map[string]string{} - if c.min != "" { - m.Annotations[autoscaling.MinScaleAnnotationKey] = c.min - } - if c.max != "" { - m.Annotations[autoscaling.MaxScaleAnnotationKey] = c.max - } - s, err := ScalingInfo(&m) - if c.e { - assert.Assert(t, err != nil) - continue - } else { - assert.NilError(t, err) - } - if c.minRes != sentinel { - assert.Assert(t, s.Min != nil) - assert.Equal(t, c.minRes, *s.Min) - } else { - assert.Assert(t, s.Min == nil) - } - if c.maxRes != sentinel { - assert.Assert(t, s.Max != nil) - assert.Equal(t, c.maxRes, *s.Max) - } else { - assert.Assert(t, s.Max == nil) - } - - } -} - -func TestContainerIndexOfRevisionSpec(t *testing.T) { - tests := []struct { - name string - revSpec *servingv1.RevisionSpec - want int - }{ - { - "no container", - &servingv1.RevisionSpec{}, - -1, - }, - { - "1 container", - &servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "user-container", - Ports: []corev1.ContainerPort{{ContainerPort: 80}}, - }, - }}}, - 0, - }, - { - "2 containers", - &servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "sidecar-container-1", - }, - { - Name: "user-container", - Ports: []corev1.ContainerPort{{ContainerPort: 80}}, - }, - { - Name: "sidecar-container-2", - }, - }}}, - 1, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := ContainerIndexOfRevisionSpec(tt.revSpec); got != tt.want { - t.Errorf("ContainerIndexOfRevisionSpec() = %v, want %v", got, tt.want) - } - }) - } -} - -func TestAnnotations(t *testing.T) { - m := &metav1.ObjectMeta{} - m.Annotations = map[string]string{UserImageAnnotationKey: "mockImageVal", - autoscaling.TargetAnnotationKey: "1", - autoscaling.TargetUtilizationPercentageKey: "2", - autoscaling.WindowAnnotationKey: "mockWindowVal"} - assert.Equal(t, "mockImageVal", UserImage(m)) - assert.Equal(t, 1, *ConcurrencyTarget(m)) - assert.Equal(t, 2, *ConcurrencyTargetUtilization(m)) - assert.Equal(t, "mockWindowVal", AutoscaleWindow(m)) -} - -func TestPort(t *testing.T) { - revisionSpec := &servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{}, - ContainerConcurrency: new(int64), - TimeoutSeconds: new(int64), - } - assert.Equal(t, (*int32)(nil), Port(revisionSpec)) - revisionSpec.PodSpec.Containers = append(revisionSpec.PodSpec.Containers, corev1.Container{}) - assert.Equal(t, (*int32)(nil), Port(revisionSpec)) - port := corev1.ContainerPort{ContainerPort: 42} - revisionSpec.PodSpec.Containers[0].Ports = []corev1.ContainerPort{port} - assert.Equal(t, (int32)(42), *Port(revisionSpec)) -} - -func TestContainerStatus(t *testing.T) { - tests := []struct { - name string - rev *servingv1.Revision - want *servingv1.ContainerStatus - }{ - { - "no container", - &servingv1.Revision{ - Spec: servingv1.RevisionSpec{}, - Status: servingv1.RevisionStatus{ContainerStatuses: []servingv1.ContainerStatus{ - { - Name: "user-container", - }, - }}, - }, - nil, - }, - { - "1 container", - &servingv1.Revision{ - Spec: servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "user-container", - Ports: []corev1.ContainerPort{{ContainerPort: 80}}, - }, - }, - }, - }, - Status: servingv1.RevisionStatus{ContainerStatuses: []servingv1.ContainerStatus{ - { - Name: "user-container", - }, - }}, - }, - &servingv1.ContainerStatus{ - Name: "user-container", - }, - }, - { - "3 containers", - &servingv1.Revision{ - Spec: servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "sidecar-container-1", - }, - { - Name: "user-container", - Ports: []corev1.ContainerPort{{ContainerPort: 80}}, - }, - { - Name: "sidecar-container-2", - }, - }}}, - Status: servingv1.RevisionStatus{ - ContainerStatuses: []servingv1.ContainerStatus{ - { - Name: "sidecar-container-1", - }, - { - Name: "user-container", - }, - { - Name: "sidecar-container-2", - }, - }, - }}, - &servingv1.ContainerStatus{ - Name: "user-container", - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := ContainerStatus(tt.rev) - assert.DeepEqual(t, got, tt.want) - }) - } -} diff --git a/pkg/serving/service_test.go b/pkg/serving/service_test.go deleted file mode 100644 index 6c942f016c..0000000000 --- a/pkg/serving/service_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2018 The Knative 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 serving - -import ( - "testing" - - "gotest.tools/v3/assert" - - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -type generateNameTest struct { - templ string - result string - err string -} - -func TestGenerateName(t *testing.T) { - revisionNameRand.Seed(1) - someRandomChars := (&revisionTemplContext{}).Random(20) - service := &servingv1.Service{} - service.Name = "foo" - service.Generation = 3 - cases := []generateNameTest{ - {"{{.Service}}-v-{{.Generation}}", "foo-v-4", ""}, - {"foo-asdf", "foo-asdf", ""}, - {"{{.Bad}}", "", "can't evaluate field Bad"}, - {"{{.Service}}-{{.Random 5}}", "foo-" + someRandomChars[0:5], ""}, - {"", "", ""}, - {"andrew", "foo-andrew", ""}, - {"{{.Random 5}}", "foo-" + someRandomChars[0:5], ""}, - } - for _, c := range cases { - revisionNameRand.Seed(1) - name, err := GenerateRevisionName(c.templ, service) - if c.err != "" { - assert.ErrorContains(t, err, c.err) - } else { - assert.Equal(t, name, c.result) - } - } -} diff --git a/pkg/serving/v1/apply_test.go b/pkg/serving/v1/apply_test.go deleted file mode 100644 index c1526f0945..0000000000 --- a/pkg/serving/v1/apply_test.go +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright © 2020 The Knative 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 v1 - -import ( - "context" - "fmt" - "reflect" - "testing" - - "github.com/google/go-cmp/cmp" - "gotest.tools/v3/assert" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - clienttesting "k8s.io/client-go/testing" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "sigs.k8s.io/yaml" - - "knative.dev/client/pkg/util" -) - -func TestApplyServiceWithNoImage(t *testing.T) { - _, client := setup() - serviceFaulty := newService("faulty-service") - _, err := client.ApplyService(context.Background(), serviceFaulty) - assert.Assert(t, err != nil) - assert.Assert(t, util.ContainsAll(err.Error(), "image name")) -} - -func TestApplyServiceCreate(t *testing.T) { - serving, client := setup() - - serviceNew := newServiceWithImage("new-service", "test/image") - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "new-service-fail" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, nil, errors.NewNotFound(servingv1.Resource("service"), name) - }) - - serving.AddReactor("create", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, serviceNew, nil - }) - - hasChanged, err := client.ApplyService(context.Background(), serviceNew) - assert.NilError(t, err) - assert.Assert(t, hasChanged, "service has changed") - - serviceNew = newServiceWithImage("new-service-fail", "test/image") - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - }) - hasChanged, err = client.ApplyService(context.Background(), serviceNew) - assert.ErrorType(t, err, errors.IsInternalError) - assert.Assert(t, !hasChanged) -} - -func TestApplyServiceUpdate(t *testing.T) { - serving, client := setup() - - serviceOld := newServiceWithImage("my-service", "test/image") - serviceNew := newServiceWithImage("my-service", "test/new-image") - serviceConflict := newServiceWithImage("conflict-service", "test/image") - serviceErr := newServiceWithImage("err-service", "test/image") - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - var svc *servingv1.Service - var err error - switch name { - case "my-service": - svc = serviceOld - case "conflict-service": - svc = serviceConflict - case "err-service": - svc = serviceErr - err = errors.NewInternalError(fmt.Errorf("internal error")) - default: - t.FailNow() - } - return true, svc, err - }) - - serving.AddReactor("patch", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - conflictErr := errors.NewConflict(servingv1.Resource("service"), "conflict-service", fmt.Errorf("error patching service")) - if name == "conflict-service" { - return true, serviceConflict, conflictErr - } - if name == "err-service" { - return true, serviceErr, conflictErr - } - serviceNew.Generation = 2 - serviceNew.Status.ObservedGeneration = 1 - return true, serviceNew, nil - }) - - hasChanged, err := client.ApplyService(context.Background(), serviceNew) - assert.NilError(t, err) - assert.Assert(t, hasChanged, "service has changed") - - serviceOld.SetAnnotations(map[string]string{}) - hasChanged, err = client.ApplyService(context.Background(), serviceNew) - assert.NilError(t, err) - assert.Assert(t, hasChanged, "service has changed") - - serviceOld.SetAnnotations(map[string]string{corev1.LastAppliedConfigAnnotation: "never"}) - hasChanged, err = client.ApplyService(context.Background(), serviceNew) - assert.ErrorContains(t, err, "Invalid JSON") - assert.Assert(t, !hasChanged, "service has not changed") - - hasChanged, err = client.ApplyService(context.Background(), serviceConflict) - assert.ErrorType(t, err, errors.IsConflict) - assert.Assert(t, !hasChanged, "service has not changed") - - hasChanged, err = client.ApplyService(context.Background(), serviceErr) - assert.ErrorType(t, err, errors.IsInternalError) - assert.Assert(t, !hasChanged, "service has not changed") -} - -func newServiceWithImage(name string, image string) *servingv1.Service { - svc := newService(name) - svc.Spec = servingv1.ServiceSpec{ - ConfigurationSpec: servingv1.ConfigurationSpec{ - Template: servingv1.RevisionTemplateSpec{ - Spec: servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Image: image, - }, - }, - }, - }, - }, - }, - } - return svc -} - -func TestExtractUserContainer(t *testing.T) { - tests := []struct { - name string - service string - want string - }{ - {"Simple Service", - ` -spec: - template: - spec: - containers: - - image: gcr.io/foo/bar:baz -`, - ` -image: gcr.io/foo/bar:baz -`, - }, - { - "No template", - ` -spec: -`, - "", - }, { - "No template spec", - ` -spec: - template: -`, - "", - }, - { - "No template spec containers", - ` -spec: - template: - spec: -`, - "", - }, - { - "Empty template spec containers", - ` -spec: - template: - spec: - containers: [] -`, - "", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var serviceMap map[string]interface{} - yaml.Unmarshal([]byte(tt.service), &serviceMap) - - got := extractUserContainer(serviceMap) - - if tt.want == "" { - assert.Assert(t, got == nil) - } else { - var expectedMap map[string]interface{} - yaml.Unmarshal([]byte(tt.want), &expectedMap) - if !reflect.DeepEqual(got, expectedMap) { - t.Errorf("extractUserContainer() = %v, want %v", got, expectedMap) - } - } - }) - } -} - -func TestCleanupServiceUnstructured(t *testing.T) { - tests := []struct { - name string - service string - want string - }{ - {"Simple Service with fields to remove", - ` -apiVersion: serving.knative.dev/v1 -kind: Service -metadata: - name: foo - creationTimestamp: "2020-10-22T08:16:37Z" -spec: - template: - metadata: - name: "bar" - creationTimestamp: null - spec: - containers: - - image: gcr.io/foo/bar:baz - name: "bla" - resources: {} -status: - observedGeneration: 1 -`, - ` -apiVersion: serving.knative.dev/v1 -kind: Service -metadata: - name: foo -spec: - template: - metadata: - name: "bar" - spec: - containers: - - image: gcr.io/foo/bar:baz -`, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ud := &unstructured.Unstructured{} - assert.NilError(t, yaml.Unmarshal([]byte(tt.service), ud)) - cleanupServiceUnstructured(ud) - - expectedMap := &unstructured.Unstructured{} - yaml.Unmarshal([]byte(tt.want), &expectedMap) - if !reflect.DeepEqual(ud, expectedMap) { - t.Errorf("cleanupServiceUnstructured(): " + cmp.Diff(ud, expectedMap)) - } - }) - } -} diff --git a/pkg/serving/v1/client_mock_test.go b/pkg/serving/v1/client_mock_test.go deleted file mode 100644 index 2945daae85..0000000000 --- a/pkg/serving/v1/client_mock_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "testing" - "time" - - "knative.dev/serving/pkg/apis/serving" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - - "knative.dev/client/pkg/util/mock" - "knative.dev/client/pkg/wait" -) - -func TestMockKnClient(t *testing.T) { - - client := NewMockKnServiceClient(t) - - recorder := client.Recorder() - - // Record all services - recorder.GetService("hello", nil, nil) - recorder.ListServices(mock.Any(), nil, nil) - recorder.ListServices(mock.Any(), nil, nil) - recorder.CreateService(&servingv1.Service{}, nil) - recorder.UpdateService(&servingv1.Service{}, false, nil) - recorder.ApplyService(&servingv1.Service{}, true, nil) - recorder.DeleteService("hello", time.Duration(10)*time.Second, nil) - recorder.WaitForService("hello", WaitConfig{ - Timeout: time.Duration(10) * time.Second, - ErrorWindow: time.Duration(2) * time.Second, - }, wait.NoopMessageCallback(), nil, 10*time.Second) - recorder.GetRevision("hello", nil, nil) - recorder.ListRevisions(mock.Any(), nil, nil) - recorder.CreateRevision(&servingv1.Revision{}, nil) - recorder.UpdateRevision(&servingv1.Revision{}, nil) - recorder.DeleteRevision("hello", time.Duration(10)*time.Second, nil) - recorder.WaitForRevision("hello", time.Duration(10)*time.Second, wait.NoopMessageCallback(), nil, 10*time.Second) - recorder.GetRoute("hello", nil, nil) - recorder.ListRoutes(mock.Any(), nil, nil) - recorder.GetConfiguration("hello", nil, nil) - - // Call all services - ctx := context.Background() - client.GetService(ctx, "hello") - client.ListServices(ctx, WithName("blub")) - client.ListServices(ctx, WithLabel("foo", "bar")) - client.CreateService(ctx, &servingv1.Service{}) - client.UpdateService(ctx, &servingv1.Service{}) - client.ApplyService(ctx, &servingv1.Service{}) - client.DeleteService(ctx, "hello", time.Duration(10)*time.Second) - client.WaitForService(ctx, "hello", WaitConfig{ - time.Duration(10) * time.Second, - time.Duration(2) * time.Second, - }, wait.NoopMessageCallback()) - client.GetRevision(ctx, "hello") - client.ListRevisions(ctx, WithName("blub")) - client.CreateRevision(ctx, &servingv1.Revision{}) - client.UpdateRevision(ctx, &servingv1.Revision{}) - client.DeleteRevision(ctx, "hello", time.Duration(10)*time.Second) - client.WaitForRevision(ctx, "hello", time.Duration(10)*time.Second, wait.NoopMessageCallback()) - client.GetRoute(ctx, "hello") - client.ListRoutes(ctx, WithName("blub")) - client.GetConfiguration(ctx, "hello") - - // Validate - recorder.Validate() -} - -func TestHasLabelSelector(t *testing.T) { - assertFunction := HasLabelSelector(serving.ServiceLabelKey, "myservice") - listConfig := []ListConfig{ - WithService("myservice"), - } - assertFunction(t, listConfig) -} - -func TestHasFieldSelector(t *testing.T) { - assertFunction := HasFieldSelector("metadata.name", "myname") - listConfig := []ListConfig{ - WithName("myname"), - } - assertFunction(t, listConfig) -} - -func TestHasSelector(t *testing.T) { - assertFunction := HasSelector( - []string{serving.ServiceLabelKey, "myservice"}, - []string{"metadata.name", "myname"}) - listConfig := []ListConfig{ - func(lo *listConfigCollector) { - lo.Labels[serving.ServiceLabelKey] = "myservice" - lo.Fields["metadata.name"] = "myname" - }, - } - assertFunction(t, listConfig) -} diff --git a/pkg/serving/v1/client_test.go b/pkg/serving/v1/client_test.go deleted file mode 100644 index 480b9dfd2f..0000000000 --- a/pkg/serving/v1/client_test.go +++ /dev/null @@ -1,939 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "fmt" - "testing" - "time" - - apierrors "k8s.io/apimachinery/pkg/api/errors" - - "knative.dev/pkg/apis" - duck "knative.dev/pkg/apis/duck/v1" - - "gotest.tools/v3/assert" - "gotest.tools/v3/assert/cmp" - "k8s.io/apimachinery/pkg/fields" - "k8s.io/apimachinery/pkg/watch" - "knative.dev/serving/pkg/apis/serving" - "knative.dev/serving/pkg/client/clientset/versioned/scheme" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - servingv1fake "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/fake" - - "k8s.io/apimachinery/pkg/runtime" - clienttesting "k8s.io/client-go/testing" - - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" -) - -var testNamespace = "test-ns" - -func setup() (serving servingv1fake.FakeServingV1, client KnServingClient) { - serving = servingv1fake.FakeServingV1{Fake: &clienttesting.Fake{}} - client = NewKnServingClient(&serving, testNamespace) - return -} - -func TestNamespace(t *testing.T) { - _, client := setup() - assert.Equal(t, testNamespace, client.Namespace()) -} - -func TestGetService(t *testing.T) { - serving, client := setup() - serviceName := "test-service" - - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - service := newService(serviceName) - name := a.(clienttesting.GetAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == serviceName { - return true, service, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("service"), name) - }) - - t.Run("get known service by name returns service", func(t *testing.T) { - service, err := client.GetService(context.Background(), serviceName) - assert.NilError(t, err) - assert.Equal(t, serviceName, service.Name, "service name should be equal") - validateGroupVersionKind(t, service) - }) - - t.Run("get unknown service name returns error", func(t *testing.T) { - nonExistingServiceName := "service-that-does-not-exist" - service, err := client.GetService(context.Background(), nonExistingServiceName) - assert.Assert(t, service == nil, "no service should be returned") - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingServiceName) - }) -} - -func TestListService(t *testing.T) { - serving, client := setup() - - t.Run("list service returns a list of services", func(t *testing.T) { - labelKey := "labelKey" - labelValue := "labelValue" - labels := map[string]string{labelKey: labelValue} - incorrectLabels := map[string]string{"foo": "bar"} - - service1 := newService("service-1") - service2 := newService("service-2") - service3 := newService("service-3-with-label") - service3.Labels = labels - service4 := newService("service-4-with-label") - service4.Labels = labels - service5 := newService("service-5-with-incorrect-label") - service5.Labels = incorrectLabels - - serving.AddReactor("list", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, &servingv1.ServiceList{Items: []servingv1.Service{*service1, *service2, *service3, *service4, *service5}}, nil - }) - - listServices, err := client.ListServices(context.Background()) - assert.NilError(t, err) - assert.Assert(t, len(listServices.Items) == 5) - assert.Equal(t, listServices.Items[0].Name, "service-1") - assert.Equal(t, listServices.Items[1].Name, "service-2") - validateGroupVersionKind(t, listServices) - validateGroupVersionKind(t, &listServices.Items[0]) - validateGroupVersionKind(t, &listServices.Items[1]) - - listFilteredServices, err := client.ListServices(context.Background(), WithLabel(labelKey, labelValue)) - assert.NilError(t, err) - assert.Assert(t, len(listFilteredServices.Items) == 2) - assert.Equal(t, listFilteredServices.Items[0].Name, "service-3-with-label") - assert.Equal(t, listFilteredServices.Items[1].Name, "service-4-with-label") - validateGroupVersionKind(t, listFilteredServices) - validateGroupVersionKind(t, &listFilteredServices.Items[0]) - validateGroupVersionKind(t, &listFilteredServices.Items[1]) - }) - -} - -func TestListServiceError(t *testing.T) { - serving, client := setup() - - serving.AddReactor("list", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, nil, apierrors.NewInternalError(fmt.Errorf("internal error")) - }) - - listServices, err := client.ListServices(context.Background()) - assert.ErrorType(t, err, apierrors.IsInternalError) - assert.Assert(t, listServices == nil) -} - -func TestCreateService(t *testing.T) { - serving, client := setup() - - serviceNew := newService("new-service") - serving.AddReactor("create", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(clienttesting.CreateAction).GetObject().(metav1.Object).GetName() - if name == serviceNew.Name { - serviceNew.Generation = 2 - return true, serviceNew, nil - } - return true, nil, fmt.Errorf("error while creating service %s", name) - }) - - t.Run("create service without error creates a new service", func(t *testing.T) { - err := client.CreateService(context.Background(), serviceNew) - assert.NilError(t, err) - assert.Equal(t, serviceNew.Generation, int64(2)) - validateGroupVersionKind(t, serviceNew) - }) - - t.Run("create service with an error returns an error object", func(t *testing.T) { - err := client.CreateService(context.Background(), newService("unknown")) - assert.ErrorContains(t, err, "unknown") - }) -} - -func TestUpdateService(t *testing.T) { - serving, client := setup() - serviceUpdate := newService("update-service") - serviceUpdate.ObjectMeta.Generation = 2 - - serving.AddReactor("update", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(clienttesting.UpdateAction).GetObject().(metav1.Object).GetName() - if name == serviceUpdate.Name { - serviceReturn := newService("update-service") - serviceReturn.Generation = 3 - return true, serviceReturn, nil - } - return true, nil, fmt.Errorf("error while updating service %s", name) - }) - - t.Run("updating a service without error", func(t *testing.T) { - changed, err := client.UpdateService(context.Background(), serviceUpdate) - assert.NilError(t, err) - assert.Assert(t, changed) - validateGroupVersionKind(t, serviceUpdate) - }) - - t.Run("updating a service with error", func(t *testing.T) { - _, err := client.UpdateService(context.Background(), newService("unknown")) - assert.ErrorContains(t, err, "unknown") - }) -} - -func TestUpdateServiceWithRetry(t *testing.T) { - serving, client := setup() - serviceUpdate := newService("update-service") - serviceUpdate.ObjectMeta.Generation = 2 - - conflictService := newService("conflict-service") - - serving.AddReactor("update", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(clienttesting.UpdateAction).GetObject().(metav1.Object).GetName() - if name == serviceUpdate.Name { - serviceReturn := newService("update-service") - return true, serviceReturn, nil - } - if name == conflictService.Name { - return true, nil, apierrors.NewConflict(servingv1.Resource("service"), "conflict-service", fmt.Errorf("error updating because of conflict")) - } - return true, nil, fmt.Errorf("error while updating service %s", name) - }) - t.Run("updating a service without error", func(t *testing.T) { - _, err := client.UpdateServiceWithRetry(context.Background(), "update-service", func(svc *servingv1.Service) (*servingv1.Service, error) { - svc.Name = "update-service" - return svc, nil - }, 10) - assert.NilError(t, err) - }) - t.Run("updating a service with conflict error", func(t *testing.T) { - _, err := client.UpdateServiceWithRetry(context.Background(), "update-service", func(svc *servingv1.Service) (*servingv1.Service, error) { - svc.Name = "conflict-service" - return svc, nil - }, 10) - assert.ErrorContains(t, err, "conflict") - }) - - t.Run("updating a service with update func error", func(t *testing.T) { - _, err := client.UpdateServiceWithRetry(context.Background(), "update-service", func(svc *servingv1.Service) (*servingv1.Service, error) { - svc.Name = "update-service" - return svc, fmt.Errorf("update error") - }, 10) - assert.ErrorContains(t, err, "update error") - }) - - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == serviceUpdate.Name { - serviceUpdate.DeletionTimestamp = &metav1.Time{Time: time.Now()} - return true, serviceUpdate, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("service"), name) - }) - - t.Run("updating a service with deletion error", func(t *testing.T) { - _, err := client.UpdateServiceWithRetry(context.Background(), "update-service", func(svc *servingv1.Service) (*servingv1.Service, error) { - svc.Name = "update-service" - return svc, nil - }, 10) - assert.ErrorContains(t, err, "marked for deletion") - }) - - t.Run("updating a service with not found error", func(t *testing.T) { - _, err := client.UpdateServiceWithRetry(context.Background(), "unknown-service", func(svc *servingv1.Service) (*servingv1.Service, error) { - svc.Name = "unknown-service" - return svc, nil - }, 10) - assert.ErrorContains(t, err, "unknown") - }) -} - -func TestDeleteService(t *testing.T) { - serving, client := setup() - const ( - serviceName = "test-service" - nonExistingServiceName = "no-service" - deletedServiceName = "deleted-service" - errServiceName = "err-service" - ) - delErr := fmt.Errorf("failed to delete service") - - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == serviceName || name == errServiceName { - // Don't handle existing service, just continue to next - return false, nil, nil - } - if name == deletedServiceName { - deleted := newService(deletedServiceName) - deleted.DeletionTimestamp = &metav1.Time{Time: time.Now()} - return true, deleted, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("service"), name) - }) - serving.AddReactor("delete", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == serviceName { - return true, nil, nil - } - if name == errServiceName { - return true, nil, delErr - } - return false, nil, nil - }) - serving.AddWatchReactor("services", - func(a clienttesting.Action) (bool, watch.Interface, error) { - watchAction := a.(clienttesting.WatchAction) - name, found := watchAction.GetWatchRestrictions().Fields.RequiresExactMatch("metadata.name") - if !found { - return true, nil, errors.NewNotFound(servingv1.Resource("service"), name) - } - w := wait.NewFakeWatch(getServiceDeleteEvents("test-service")) - w.Start() - return true, w, nil - }) - - t.Run("delete existing service returns no error", func(t *testing.T) { - err := client.DeleteService(context.Background(), serviceName, time.Duration(10)*time.Second) - assert.NilError(t, err) - }) - - t.Run("trying to delete non-existing service returns error", func(t *testing.T) { - err := client.DeleteService(context.Background(), nonExistingServiceName, time.Duration(10)*time.Second) - println(err.Error()) - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingServiceName) - }) - - t.Run("trying to delete service DeletionTimestamp returns error", func(t *testing.T) { - err := client.DeleteService(context.Background(), deletedServiceName, time.Duration(10)*time.Second) - println(err.Error()) - assert.ErrorContains(t, err, "marked for deletion") - assert.ErrorContains(t, err, deletedServiceName) - }) - - t.Run("delete existing service returns an error", func(t *testing.T) { - err := client.DeleteService(context.Background(), errServiceName, time.Duration(10)*time.Second) - assert.ErrorType(t, err, delErr) - }) -} - -func TestDeleteServiceNoWait(t *testing.T) { - serving, client := setup() - const ( - serviceName = "test-service" - nonExistingServiceName = "no-service" - ) - - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == serviceName { - // Don't handle existing service, just continue to next - return false, nil, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("service"), name) - }) - serving.AddReactor("delete", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == serviceName { - return true, nil, nil - } - return false, nil, nil - }) - - t.Run("delete existing service returns no error", func(t *testing.T) { - err := client.DeleteService(context.Background(), serviceName, 0) - assert.NilError(t, err) - }) - - t.Run("trying to delete non-existing service returns error", func(t *testing.T) { - err := client.DeleteService(context.Background(), nonExistingServiceName, 0) - println(err.Error()) - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingServiceName) - }) -} - -func getServiceDeleteEvents(name string) []watch.Event { - return []watch.Event{ - {Type: watch.Added, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")}, - {Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")}, - {Type: watch.Deleted, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")}, - } -} - -func TestGetRevision(t *testing.T) { - serving, client := setup() - - const ( - revisionName = "test-revision" - notExistingRevisionName = "no-revision" - ) - - serving.AddReactor("get", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - revision := newRevision(revisionName) - name := a.(clienttesting.GetAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == revisionName { - return true, revision, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("revision"), name) - }) - - t.Run("get existing revision returns revision and no error", func(t *testing.T) { - revision, err := client.GetRevision(context.Background(), revisionName) - assert.NilError(t, err) - assert.Equal(t, revisionName, revision.Name) - validateGroupVersionKind(t, revision) - }) - - t.Run("trying to get a revision with a name that does not exist returns an error", func(t *testing.T) { - revision, err := client.GetRevision(context.Background(), notExistingRevisionName) - assert.Assert(t, revision == nil) - assert.ErrorContains(t, err, notExistingRevisionName) - assert.ErrorContains(t, err, "not found") - }) -} - -func TestDeleteRevision(t *testing.T) { - serving, client := setup() - const ( - revisionName = "test-revision" - nonExistingRevisionName = "no-revision" - deletedRevisionName = "deleted-revision" - ) - - serving.AddReactor("get", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == revisionName { - // Don't handle existing service, just continue to next - return false, nil, nil - } - if name == deletedRevisionName { - deleted := newRevision(deletedRevisionName) - deleted.DeletionTimestamp = &metav1.Time{Time: time.Now()} - return true, deleted, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("revision"), name) - }) - serving.AddReactor("delete", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == revisionName { - return true, nil, nil - } - return false, nil, nil - }) - serving.AddWatchReactor("revisions", - func(a clienttesting.Action) (bool, watch.Interface, error) { - watchAction := a.(clienttesting.WatchAction) - name, found := watchAction.GetWatchRestrictions().Fields.RequiresExactMatch("metadata.name") - if !found { - return true, nil, errors.NewNotFound(servingv1.Resource("revisions"), name) - } - w := wait.NewFakeWatch(getRevisionDeleteEvents(revisionName)) - w.Start() - return true, w, nil - }) - - t.Run("delete existing revision returns no error", func(t *testing.T) { - err := client.DeleteRevision(context.Background(), revisionName, 0) - assert.NilError(t, err) - }) - - t.Run("deleting revision with timeout returns no error", func(t *testing.T) { - err := client.DeleteRevision(context.Background(), revisionName, time.Second*10) - assert.NilError(t, err) - }) - - t.Run("trying to delete non-existing revision returns error", func(t *testing.T) { - err := client.DeleteRevision(context.Background(), nonExistingRevisionName, 0) - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingRevisionName) - }) - - t.Run("trying to delete revision DeletionTimestamp returns error", func(t *testing.T) { - err := client.DeleteRevision(context.Background(), deletedRevisionName, time.Duration(10)*time.Second) - assert.ErrorContains(t, err, "marked for deletion") - assert.ErrorContains(t, err, deletedRevisionName) - }) -} - -func TestDeleteRevisionNoWait(t *testing.T) { - serving, client := setup() - const ( - revisionName = "test-revision" - nonExistingRevisionName = "no-revision" - ) - - serving.AddReactor("get", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == revisionName { - // Don't handle existing service, just continue to next - return false, nil, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("revision"), name) - }) - serving.AddReactor("delete", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == revisionName { - return true, nil, nil - } - return false, nil, nil - }) - - t.Run("delete existing service returns no error", func(t *testing.T) { - err := client.DeleteRevision(context.Background(), revisionName, 0) - assert.NilError(t, err) - }) - - t.Run("trying to delete non-existing service returns error", func(t *testing.T) { - err := client.DeleteRevision(context.Background(), nonExistingRevisionName, 0) - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingRevisionName) - }) -} - -func getRevisionDeleteEvents(name string) []watch.Event { - return []watch.Event{ - {Type: watch.Added, Object: createTestRevisionWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")}, - {Type: watch.Modified, Object: createTestRevisionWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")}, - {Type: watch.Deleted, Object: createTestRevisionWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")}, - } -} - -func createTestRevisionWithConditions(name string, readyStatus corev1.ConditionStatus, otherReadyStatus corev1.ConditionStatus, reason string, message string, generations ...int64) runtime.Object { - revision := servingv1.Revision{ObjectMeta: metav1.ObjectMeta{Name: name}} - if len(generations) == 2 { - revision.Generation = generations[0] - revision.Status.ObservedGeneration = generations[1] - } else { - revision.Generation = 1 - revision.Status.ObservedGeneration = 1 - } - revision.Status.Conditions = duck.Conditions([]apis.Condition{ - {Type: "RoutesReady", Status: otherReadyStatus}, - {Type: apis.ConditionReady, Status: readyStatus, Reason: reason, Message: message}, - {Type: "ConfigurationsReady", Status: otherReadyStatus}, - }) - return &revision -} - -func TestListRevisions(t *testing.T) { - serving, client := setup() - - revisions := []servingv1.Revision{*newRevision("revision-1"), *newRevision("revision-2")} - serving.AddReactor("list", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, &servingv1.RevisionList{Items: revisions}, nil - }) - - t.Run("list revisions returns a list of revisions and no error", func(t *testing.T) { - - revisions, err := client.ListRevisions(context.Background()) - assert.NilError(t, err) - - assert.Assert(t, len(revisions.Items) == 2) - assert.Equal(t, revisions.Items[0].Name, "revision-1") - assert.Equal(t, revisions.Items[1].Name, "revision-2") - validateGroupVersionKind(t, revisions) - validateGroupVersionKind(t, &revisions.Items[0]) - validateGroupVersionKind(t, &revisions.Items[1]) - }) -} - -func TestListRevisionsError(t *testing.T) { - serving, client := setup() - - serving.AddReactor("list", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, nil, apierrors.NewInternalError(fmt.Errorf("internal error")) - }) - - t.Run("list revisions returns an internal error", func(t *testing.T) { - - revisions, err := client.ListRevisions(context.Background()) - assert.ErrorType(t, err, apierrors.IsInternalError) - assert.Assert(t, revisions == nil) - }) -} - -func TestListRevisionForService(t *testing.T) { - fakeServing, client := setup() - - serviceName := "service" - - fakeServing.AddReactor("list", "revisions", - func(a clienttesting.Action) (bool, runtime.Object, error) { - revisions := []servingv1.Revision{ - *newRevision("revision-1", serving.ServiceLabelKey, "service"), - *newRevision("revision-2"), - } - - lAction := a.(clienttesting.ListAction) - assert.Equal(t, testNamespace, a.GetNamespace()) - restrictions := lAction.GetListRestrictions() - assert.Check(t, restrictions.Fields.Empty()) - servicesLabels := labels.Set{serving.ServiceLabelKey: serviceName} - assert.Check(t, restrictions.Labels.Matches(servicesLabels)) - return true, &servingv1.RevisionList{Items: revisions}, nil - }) - - t.Run("list revisions for a service returns a list of revisions associated with this this service and no error", - func(t *testing.T) { - revisions, err := client.ListRevisions(context.Background(), WithService(serviceName)) - assert.NilError(t, err) - - assert.Assert(t, cmp.Len(revisions.Items, 1)) - assert.Equal(t, revisions.Items[0].Name, "revision-1") - assert.Equal(t, revisions.Items[0].Labels[serving.ServiceLabelKey], "service") - validateGroupVersionKind(t, revisions) - validateGroupVersionKind(t, &revisions.Items[0]) - }) -} - -func TestGetRoute(t *testing.T) { - serving, client := setup() - routeName := "test-route" - - serving.AddReactor("get", "routes", - func(a clienttesting.Action) (bool, runtime.Object, error) { - route := newRoute(routeName) - name := a.(clienttesting.GetAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == routeName { - return true, route, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("route"), name) - }) - - t.Run("get known route by name returns route", func(t *testing.T) { - route, err := client.GetRoute(context.Background(), routeName) - assert.NilError(t, err) - assert.Equal(t, routeName, route.Name, "route name should be equal") - validateGroupVersionKind(t, route) - }) - - t.Run("get unknown route name returns error", func(t *testing.T) { - nonExistingRouteName := "r@ute-that-d$es-n#t-exist" - route, err := client.GetRoute(context.Background(), nonExistingRouteName) - assert.Assert(t, route == nil, "no route should be returned") - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingRouteName) - }) -} - -func TestListRoutes(t *testing.T) { - serving, client := setup() - - singleRouteName := "route-2" - singleRoute := *newRoute(singleRouteName) - routes := []servingv1.Route{*newRoute("route-1"), singleRoute, *newRoute("route-3")} - serving.AddReactor("list", "routes", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - lAction := a.(clienttesting.ListAction) - restrictions := lAction.GetListRestrictions() - assert.Assert(t, restrictions.Labels.Empty()) - if !restrictions.Fields.Empty() { - nameField := fields.Set{"metadata.name": singleRouteName} - assert.Check(t, restrictions.Labels.Matches(nameField)) - return true, &servingv1.RouteList{Items: []servingv1.Route{singleRoute}}, nil - } - return true, &servingv1.RouteList{Items: routes}, nil - }) - - t.Run("list routes returns a list of routes and no error", func(t *testing.T) { - - routes, err := client.ListRoutes(context.Background()) - assert.NilError(t, err) - - assert.Assert(t, len(routes.Items) == 3) - assert.Equal(t, routes.Items[0].Name, "route-1") - assert.Equal(t, routes.Items[1].Name, singleRouteName) - assert.Equal(t, routes.Items[2].Name, "route-3") - validateGroupVersionKind(t, routes) - for i := 0; i < len(routes.Items); i++ { - validateGroupVersionKind(t, &routes.Items[i]) - } - }) - - t.Run("list routes with a name filter a list with one route and no error", func(t *testing.T) { - - routes, err := client.ListRoutes(context.Background(), WithName(singleRouteName)) - assert.NilError(t, err) - - assert.Assert(t, len(routes.Items) == 1) - assert.Equal(t, routes.Items[0].Name, singleRouteName) - validateGroupVersionKind(t, routes) - validateGroupVersionKind(t, &routes.Items[0]) - }) -} - -func TestListRoutesError(t *testing.T) { - serving, client := setup() - - serving.AddReactor("list", "routes", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, nil, apierrors.NewInternalError(fmt.Errorf("internal error")) - }) - - t.Run("list routes returns an internal error", func(t *testing.T) { - - routes, err := client.ListRoutes(context.Background()) - assert.ErrorType(t, err, apierrors.IsInternalError) - assert.Assert(t, routes == nil) - }) -} - -func TestWaitForService(t *testing.T) { - serving, client := setup() - - serviceName := "test-service" - notFoundServiceName := "not-found-service" - internalErrorServiceName := "internal-error-service" - - serving.AddWatchReactor("services", - func(a clienttesting.Action) (bool, watch.Interface, error) { - watchAction := a.(clienttesting.WatchAction) - val, found := watchAction.GetWatchRestrictions().Fields.RequiresExactMatch("metadata.name") - if !found { - return true, nil, fmt.Errorf("no field selector on metadata.name found") - } - w := wait.NewFakeWatch(getServiceEvents(val)) - w.Start() - return true, w, nil - }) - serving.AddReactor("get", "services", - func(a clienttesting.Action) (bool, runtime.Object, error) { - getAction := a.(clienttesting.GetAction) - var err error - var svc *servingv1.Service - switch getAction.GetName() { - case serviceName: - err = nil - svc = newService(serviceName) - case notFoundServiceName: - err = apierrors.NewNotFound(servingv1.Resource("service"), notFoundServiceName) - case internalErrorServiceName: - err = apierrors.NewInternalError(fmt.Errorf(internalErrorServiceName)) - default: - t.Log("Service name didn't match any of the given patterns") - t.FailNow() - } - return true, svc, err - }) - - t.Run("wait on a service to become ready with success", func(t *testing.T) { - err, duration := client.WaitForService(context.Background(), serviceName, WaitConfig{ - Timeout: time.Duration(10) * time.Second, - ErrorWindow: time.Duration(2) * time.Second, - }, wait.NoopMessageCallback()) - assert.NilError(t, err) - assert.Assert(t, duration > 0) - }) - t.Run("wait on a service to become ready with not found error", func(t *testing.T) { - err, duration := client.WaitForService(context.Background(), notFoundServiceName, WaitConfig{ - Timeout: time.Duration(10) * time.Second, - ErrorWindow: time.Duration(2) * time.Second, - }, wait.NoopMessageCallback()) - assert.NilError(t, err) - assert.Assert(t, duration > 0) - }) - t.Run("wait on a service to become ready with internal error", func(t *testing.T) { - err, duration := client.WaitForService(context.Background(), internalErrorServiceName, WaitConfig{ - Timeout: time.Duration(10) * time.Second, - ErrorWindow: time.Duration(2) * time.Second, - }, wait.NoopMessageCallback()) - assert.ErrorType(t, err, apierrors.IsInternalError) - assert.Assert(t, duration == 0) - }) -} - -type baseRevisionCase struct { - templateName string - templateImage string - latestCreated string - requestedRevisionName string - - foundRevisionImage string - errText string -} - -func TestGetBaseRevision(t *testing.T) { - servingFake, client := setup() - cases := []baseRevisionCase{ - {"foo-asdf", "gcr.io/foo/bar", "foo-asdf", "foo-asdf", "gcr.io/foo/bar", ""}, - {"", "gcr.io/foo/bar", "foo-asdf", "foo-asdf", "gcr.io/foo/bar", ""}, - {"foo-qwer", "gcr.io/foo/bar", "foo-asdf", "foo-qwer", "gcr.io/foo/bar", ""}, - {"", "gcr.io/foo/bar", "foo-asdf", "foo-asdf", "gcr.io/foo/baz", "unexpected image"}, - } - var c baseRevisionCase - servingFake.AddReactor("get", "revisions", func(a clienttesting.Action) (bool, runtime.Object, error) { - revision := &servingv1.Revision{ObjectMeta: metav1.ObjectMeta{Name: c.requestedRevisionName, Namespace: testNamespace}} - revision.Spec.Containers = []corev1.Container{{}} - name := a.(clienttesting.GetAction).GetName() - assert.Equal(t, name, c.requestedRevisionName) - - if c.foundRevisionImage != "" { - revision.Spec.Containers[0].Image = c.foundRevisionImage - return true, revision, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("revision"), name) - }) - for _, c = range cases { - service := servingv1.Service{} - service.Spec.Template = servingv1.RevisionTemplateSpec{} - service.Spec.Template.Name = c.templateName - service.Status.LatestCreatedRevisionName = c.latestCreated - service.Spec.Template.Spec.Containers = []corev1.Container{{}} - service.Spec.Template.Spec.Containers[0].Image = c.templateImage - - r, err := client.GetBaseRevision(context.Background(), &service) - if err == nil { - assert.Equal(t, r.Spec.Containers[0].Image, c.foundRevisionImage) - } else { - assert.Assert(t, c.errText != "") - assert.ErrorContains(t, err, c.errText) - } - } -} - -func TestGetConfiguration(t *testing.T) { - serving, client := setup() - - const ( - configName = "test-config" - notExistingConfigurationName = "no-revision" - ) - - serving.AddReactor("get", "configurations", - func(a clienttesting.Action) (bool, runtime.Object, error) { - configuration := &servingv1.Configuration{ObjectMeta: metav1.ObjectMeta{Name: configName, Namespace: testNamespace}} - name := a.(clienttesting.GetAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == configName { - return true, configuration, nil - } - return true, nil, errors.NewNotFound(servingv1.Resource("configuration"), name) - }) - - t.Run("getting existing configuration returns configuration and no error", func(t *testing.T) { - configuration, err := client.GetConfiguration(context.Background(), configName) - assert.NilError(t, err) - assert.Equal(t, configName, configuration.Name) - validateGroupVersionKind(t, configuration) - }) - - t.Run("trying to get a configuration with a name that does not exist returns an error", func(t *testing.T) { - configuration, err := client.GetConfiguration(context.Background(), notExistingConfigurationName) - assert.Assert(t, configuration == nil) - assert.ErrorContains(t, err, notExistingConfigurationName) - assert.ErrorContains(t, err, "not found") - }) -} - -func validateGroupVersionKind(t *testing.T, obj runtime.Object) { - gvkExpected, err := util.GetGroupVersionKind(obj, servingv1.SchemeGroupVersion, scheme.Scheme) - assert.NilError(t, err) - gvkGiven := obj.GetObjectKind().GroupVersionKind() - assert.Equal(t, *gvkExpected, gvkGiven, "GVK should be the same") -} - -func newService(name string) *servingv1.Service { - return &servingv1.Service{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: testNamespace}} -} - -func newRevision(name string, labels ...string) *servingv1.Revision { - rev := &servingv1.Revision{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: testNamespace}} - labelMap := make(map[string]string) - if len(labels) > 0 { - for i := 0; i < len(labels); i += 2 { - labelMap[labels[i]] = labels[i+1] - } - rev.Labels = labelMap - } - return rev -} - -func newRoute(name string) *servingv1.Route { - return &servingv1.Route{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: testNamespace}} -} - -func getServiceEvents(name string) []watch.Event { - return []watch.Event{ - {Type: watch.Added, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")}, - {Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")}, - {Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")}, - } -} - -func TestCreateRevision(t *testing.T) { - _, client := setup() - rev := newRevision("mockRevision") - assert.NilError(t, client.CreateRevision(context.Background(), rev)) - rev.Labels = map[string]string{ - "mockKey": "mockVal", - } - assert.NilError(t, client.UpdateRevision(context.Background(), rev)) -} diff --git a/pkg/serving/v1/gitops_test.go b/pkg/serving/v1/gitops_test.go deleted file mode 100644 index 8095dccceb..0000000000 --- a/pkg/serving/v1/gitops_test.go +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright 2020 The Knative 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 v1 - -import ( - "context" - "path/filepath" - "testing" - "time" - - "gotest.tools/v3/assert" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - servingtest "knative.dev/serving/pkg/testing/v1" - - libtest "knative.dev/client/lib/test" - "knative.dev/pkg/ptr" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -func TestGitOpsOperations(t *testing.T) { - c1TempDir := t.TempDir() - c2TempDir := t.TempDir() - - // create clients - fooclient := NewKnServingGitOpsClient("foo-ns", c1TempDir) - bazclient := NewKnServingGitOpsClient("baz-ns", c1TempDir) - globalclient := NewKnServingGitOpsClient("", c1TempDir) - diffClusterClient := NewKnServingGitOpsClient("", "tmp") - - // set up test services - fooSvc := libtest.BuildServiceWithOptions("foo", servingtest.WithConfigSpec(buildConfiguration())) - barSvc := libtest.BuildServiceWithOptions("bar", servingtest.WithConfigSpec(buildConfiguration())) - fooUpdateSvc := libtest.BuildServiceWithOptions("foo", servingtest.WithConfigSpec(buildConfiguration()), servingtest.WithEnv(corev1.EnvVar{Name: "a", Value: "mouse"})) - mockUpdateSvc := libtest.BuildServiceWithOptions("mock", servingtest.WithConfigSpec(buildConfiguration()), servingtest.WithEnv(corev1.EnvVar{Name: "a", Value: "mouse"})) - - fooserviceList := getServiceList([]servingv1.Service{*barSvc, *fooSvc}) - allServices := getServiceList([]servingv1.Service{*barSvc, *barSvc, *fooSvc}) - - t.Run("get file path for foo service in foo namespace", func(t *testing.T) { - fp := fooclient.(*knServingGitOpsClient).getKsvcFilePath("foo") - assert.Equal(t, filepath.Join(c1TempDir, "foo-ns/ksvc/foo.yaml"), fp) - }) - t.Run("get namespace for bazclient client", func(t *testing.T) { - ns := bazclient.Namespace() - assert.Equal(t, "baz-ns", ns) - }) - t.Run("create service foo in foo namespace", func(t *testing.T) { - err := fooclient.CreateService(context.Background(), fooSvc) - assert.NilError(t, err) - }) - t.Run("wait for foo service in foo namespace", func(t *testing.T) { - err, d := fooclient.WaitForService(context.Background(), "foo", WaitConfig{ - Timeout: time.Duration(5) * time.Second, - ErrorWindow: time.Duration(2) * time.Second, - }, nil) - assert.NilError(t, err) - assert.Equal(t, 1*time.Second, d) - }) - t.Run("get service foo", func(t *testing.T) { - result, err := fooclient.GetService(context.Background(), "foo") - assert.NilError(t, err) - assert.DeepEqual(t, fooSvc, result) - }) - t.Run("create service bar in foo namespace", func(t *testing.T) { - err := fooclient.CreateService(context.Background(), barSvc) - assert.NilError(t, err) - }) - t.Run("create service bar in baz namespace", func(t *testing.T) { - err := bazclient.CreateService(context.Background(), barSvc) - assert.NilError(t, err) - }) - t.Run("list services in foo namespace", func(t *testing.T) { - result, err := fooclient.ListServices(context.Background()) - assert.NilError(t, err) - assert.DeepEqual(t, fooserviceList, result) - }) - t.Run("create service without tmp directory", func(t *testing.T) { - err := diffClusterClient.CreateService(context.Background(), fooSvc) - assert.ErrorContains(t, err, "directory 'tmp' not present, please create the directory and try again") - }) - diffClusterClient = NewKnServingGitOpsClient("", c2TempDir) - t.Run("create service foo in foo namespace in cluster 2", func(t *testing.T) { - err := diffClusterClient.CreateService(context.Background(), fooSvc) - assert.NilError(t, err) - }) - t.Run("list services in all namespaces in cluster 1", func(t *testing.T) { - result, err := globalclient.ListServices(context.Background()) - assert.NilError(t, err) - assert.DeepEqual(t, allServices, result) - }) - t.Run("update service with retry foo", func(t *testing.T) { - changed, err := fooclient.UpdateServiceWithRetry(context.Background(), "foo", func(svc *servingv1.Service) (*servingv1.Service, error) { - return svc, nil - }, 1) - assert.Assert(t, changed) - assert.NilError(t, err) - }) - t.Run("update service foo", func(t *testing.T) { - changed, err := fooclient.UpdateService(context.Background(), fooUpdateSvc) - assert.Assert(t, changed) - assert.NilError(t, err) - }) - t.Run("check updated service foo", func(t *testing.T) { - result, err := fooclient.GetService(context.Background(), "foo") - assert.NilError(t, err) - assert.DeepEqual(t, fooUpdateSvc, result) - }) - t.Run("delete service foo", func(t *testing.T) { - err := fooclient.DeleteService(context.Background(), "foo", 5*time.Second) - assert.NilError(t, err) - }) - t.Run("get service foo", func(t *testing.T) { - _, err := fooclient.GetService(context.Background(), "foo") - assert.ErrorType(t, err, apierrors.IsNotFound) - }) - - t.Run("update service foo", func(t *testing.T) { - _, err := fooclient.UpdateService(context.Background(), mockUpdateSvc) - assert.ErrorType(t, err, apierrors.IsNotFound) - }) -} - -func TestGitOpsSingleFile(t *testing.T) { - tmpDir := t.TempDir() - // create clients - fooclient := NewKnServingGitOpsClient("", filepath.Join(tmpDir, "test.yaml")) - barclient := NewKnServingGitOpsClient("", filepath.Join(tmpDir, "test.yml")) - bazclient := NewKnServingGitOpsClient("", filepath.Join(tmpDir, "test.json")) - mockclient := NewKnServingGitOpsClient("", filepath.Join(tmpDir, "mockfile")) - mockDirclient := NewKnServingGitOpsClient("", tmpDir) - - // set up test services - testSvc := libtest.BuildServiceWithOptions("test", servingtest.WithConfigSpec(buildConfiguration())) - updateSvc := libtest.BuildServiceWithOptions("test", servingtest.WithConfigSpec(buildConfiguration()), servingtest.WithEnv(corev1.EnvVar{Name: "a", Value: "mouse"})) - - svcList := getServiceList([]servingv1.Service{*updateSvc}) - - t.Run("get file path for fooclient", func(t *testing.T) { - fp := fooclient.(*knServingGitOpsClient).getKsvcFilePath("test") - assert.Equal(t, filepath.Join(tmpDir, "test.yaml"), fp) - }) - t.Run("get namespace for fooclient", func(t *testing.T) { - ns := fooclient.Namespace() - assert.Equal(t, "", ns) - }) - t.Run("create service in single file mode in different formats", func(t *testing.T) { - err := fooclient.CreateService(context.Background(), testSvc) - assert.NilError(t, err) - - err = barclient.CreateService(context.Background(), testSvc) - assert.NilError(t, err) - - err = bazclient.CreateService(context.Background(), testSvc) - assert.NilError(t, err) - }) - t.Run("retrieve services", func(t *testing.T) { - result, err := fooclient.GetService(context.Background(), "test") - assert.NilError(t, err) - assert.DeepEqual(t, testSvc, result) - - result, err = barclient.GetService(context.Background(), "test") - assert.NilError(t, err) - assert.DeepEqual(t, testSvc, result) - - result, err = bazclient.GetService(context.Background(), "test") - assert.NilError(t, err) - assert.DeepEqual(t, testSvc, result) - }) - t.Run("update service foo", func(t *testing.T) { - changed, err := fooclient.UpdateService(context.Background(), updateSvc) - assert.NilError(t, err) - assert.Assert(t, changed) - - changed, err = barclient.UpdateService(context.Background(), updateSvc) - assert.NilError(t, err) - assert.Assert(t, changed) - - changed, err = bazclient.UpdateService(context.Background(), updateSvc) - assert.NilError(t, err) - assert.Assert(t, changed) - }) - t.Run("list services", func(t *testing.T) { - result, err := fooclient.ListServices(context.Background()) - assert.NilError(t, err) - assert.DeepEqual(t, svcList, result) - - result, err = barclient.ListServices(context.Background()) - assert.NilError(t, err) - assert.DeepEqual(t, svcList, result) - - result, err = bazclient.ListServices(context.Background()) - assert.NilError(t, err) - assert.DeepEqual(t, svcList, result) - - _, err = mockclient.ListServices(context.Background()) - assert.ErrorContains(t, err, "no such file") - - _, err = mockDirclient.ListServices(context.Background()) - assert.NilError(t, err) - }) - t.Run("delete service foo", func(t *testing.T) { - err := fooclient.DeleteService(context.Background(), "test", 5*time.Second) - assert.NilError(t, err) - - err = barclient.DeleteService(context.Background(), "test", 5*time.Second) - assert.NilError(t, err) - - err = bazclient.DeleteService(context.Background(), "test", 5*time.Second) - assert.NilError(t, err) - }) - t.Run("get service foo", func(t *testing.T) { - _, err := fooclient.GetService(context.Background(), "test") - assert.ErrorType(t, err, apierrors.IsNotFound) - - _, err = barclient.GetService(context.Background(), "test") - assert.ErrorType(t, err, apierrors.IsNotFound) - - _, err = bazclient.GetService(context.Background(), "test") - assert.ErrorType(t, err, apierrors.IsNotFound) - }) -} - -func getServiceList(services []servingv1.Service) *servingv1.ServiceList { - return &servingv1.ServiceList{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "v1", - Kind: "List", - }, - Items: services, - } -} - -func buildConfiguration() *servingv1.ConfigurationSpec { - c := &servingv1.Configuration{ - Spec: servingv1.ConfigurationSpec{ - Template: servingv1.RevisionTemplateSpec{ - Spec: *revisionSpec.DeepCopy(), - }, - }, - } - c.SetDefaults(context.Background()) - return &c.Spec -} - -var revisionSpec = servingv1.RevisionSpec{ - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Image: "busybox", - }}, - EnableServiceLinks: ptr.Bool(false), - }, - TimeoutSeconds: ptr.Int64(300), -} diff --git a/pkg/serving/v1beta1/client_mock_test.go b/pkg/serving/v1beta1/client_mock_test.go deleted file mode 100644 index 277a494b5d..0000000000 --- a/pkg/serving/v1beta1/client_mock_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright © 2021 The Knative 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" - "testing" - - "knative.dev/serving/pkg/apis/serving/v1beta1" -) - -func TestMockKnClient(t *testing.T) { - - client := NewMockKnServiceClient(t) - - recorder := client.Recorder() - - // Record all services - recorder.GetDomainMapping("hello.foo.bar", &v1beta1.DomainMapping{}, nil) - recorder.CreateDomainMapping(&v1beta1.DomainMapping{}, nil) - recorder.DeleteDomainMapping("hello.foo.bar", nil) - recorder.UpdateDomainMapping(&v1beta1.DomainMapping{}, nil) - - recorder.GetDomainMapping("hello.foo.bar", &v1beta1.DomainMapping{}, nil) - recorder.UpdateDomainMapping(&v1beta1.DomainMapping{}, nil) - recorder.ListDomainMappings(&v1beta1.DomainMappingList{}, nil) - - // Call all services - ctx := context.Background() - client.GetDomainMapping(ctx, "hello.foo.bar") - client.CreateDomainMapping(ctx, &v1beta1.DomainMapping{}) - client.DeleteDomainMapping(ctx, "hello.foo.bar") - client.UpdateDomainMapping(ctx, &v1beta1.DomainMapping{}) - client.UpdateDomainMappingWithRetry(ctx, "hello.foo.bar", func(origDomain *v1beta1.DomainMapping) (*v1beta1.DomainMapping, error) { - return origDomain, nil - }, 10) - client.ListDomainMappings(ctx) - - // Validate - recorder.Validate() -} diff --git a/pkg/serving/v1beta1/client_test.go b/pkg/serving/v1beta1/client_test.go deleted file mode 100644 index 8fb03bf5a0..0000000000 --- a/pkg/serving/v1beta1/client_test.go +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright © 2021 The Knative 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" - "testing" - - eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" - - "gotest.tools/v3/assert" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - clienttesting "k8s.io/client-go/testing" - - "knative.dev/client/pkg/util" - duckv1 "knative.dev/pkg/apis/duck/v1" - servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" - "knative.dev/serving/pkg/client/clientset/versioned/scheme" - servingv1beta1fake "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1/fake" -) - -const ( - testNamespace = "test-ns" - domainMappingResource = "domainmappings" -) - -func setup() (serving servingv1beta1fake.FakeServingV1beta1, client KnServingClient) { - serving = servingv1beta1fake.FakeServingV1beta1{Fake: &clienttesting.Fake{}} - client = NewKnServingClient(&serving, testNamespace) - return -} - -func TestGetDomainMapping(t *testing.T) { - serving, client := setup() - serviceName := "foo" - domainName := "foo.bar" - - serving.AddReactor("get", domainMappingResource, - func(a clienttesting.Action) (bool, runtime.Object, error) { - dm := createDomainMapping(domainName, createServiceRef(serviceName, testNamespace)) - name := a.(clienttesting.GetAction).GetName() - - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == domainName { - return true, dm, nil - } - return true, nil, errors.NewNotFound(servingv1beta1.Resource("dm"), name) - }) - - t.Run("get domain mapping by name returns object", func(t *testing.T) { - domainMapping, err := client.GetDomainMapping(context.Background(), domainName) - assert.NilError(t, err) - assert.Equal(t, domainName, domainMapping.Name, "domain mapping name should be equal") - validateGroupVersionKind(t, domainMapping) - }) - - t.Run("get non-existing domain mapping by name returns error", func(t *testing.T) { - nonExistingName := "does-not-exist" - service, err := client.GetDomainMapping(context.Background(), nonExistingName) - assert.Assert(t, service == nil, "no domain mapping should be returned") - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingName) - }) -} - -func TestCreateDomainMapping(t *testing.T) { - serving, client := setup() - serviceName := "foo" - domainName := "foo.bar" - secretName := "tls-secret" - domainMapping := createDomainMapping(domainName, createServiceRef(serviceName, testNamespace)) - serving.AddReactor("create", domainMappingResource, - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(clienttesting.CreateAction).GetObject().(metav1.Object).GetName() - if name == domainMapping.Name { - domainMapping.Generation = 2 - return true, domainMapping, nil - } - return true, nil, fmt.Errorf("error while creating service %s", name) - }) - - t.Run("create domain mapping without error creates a new object", func(t *testing.T) { - err := client.CreateDomainMapping(context.Background(), domainMapping) - assert.NilError(t, err) - assert.Equal(t, domainMapping.Generation, int64(2)) - validateGroupVersionKind(t, domainMapping) - }) - - t.Run("create domain mapping with tls secret without error", func(t *testing.T) { - err := client.CreateDomainMapping(context.Background(), createDomainMappingWithTls(domainName, createServiceRef(serviceName, testNamespace), secretName)) - assert.NilError(t, err) - }) - - t.Run("create domain mapping without tls secret without error", func(t *testing.T) { - err := client.CreateDomainMapping(context.Background(), createDomainMappingWithTls(domainName, createServiceRef(serviceName, testNamespace), "")) - assert.NilError(t, err) - }) - - t.Run("create domain mapping with an error returns an error object", func(t *testing.T) { - err := client.CreateDomainMapping(context.Background(), createDomainMapping("unknown", createServiceRef(serviceName, testNamespace))) - assert.ErrorContains(t, err, "unknown") - }) -} - -func TestUpdateDomainMapping(t *testing.T) { - serving, client := setup() - serviceName := "foo" - domainName := "foo.bar" - domainMappingUpdate := createDomainMapping(domainName, createServiceRef(serviceName, testNamespace)) - domainMappingUpdate.ObjectMeta.Generation = 2 - - serving.AddReactor("update", domainMappingResource, - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(clienttesting.UpdateAction).GetObject().(metav1.Object).GetName() - if name == domainMappingUpdate.Name { - dmResult := createDomainMapping(domainName, createServiceRef(serviceName, testNamespace)) - dmResult.Generation = 3 - return true, dmResult, nil - } - return true, nil, fmt.Errorf("error while updating service %s", name) - }) - - t.Run("update domain mapping without error", func(t *testing.T) { - err := client.UpdateDomainMapping(context.Background(), domainMappingUpdate) - assert.NilError(t, err) - validateGroupVersionKind(t, domainMappingUpdate) - }) - - t.Run("update domain mapping with error", func(t *testing.T) { - err := client.UpdateDomainMapping(context.Background(), createDomainMapping("unknown", createServiceRef(serviceName, testNamespace))) - assert.ErrorContains(t, err, "unknown") - }) -} - -func TestUpdateDomainMappingWithRetry(t *testing.T) { - serving, client := setup() - serviceName := "foo" - domainName := "foo.bar" - - var attemptCount, maxAttempts = 0, 5 - serving.AddReactor("get", "domainmappings", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "deletedDomain" { - domain := createDomainMapping(name, createServiceRef(serviceName, testNamespace)) - now := metav1.Now() - domain.DeletionTimestamp = &now - return true, domain, nil - } - if name == "getErrorDomain" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, createDomainMapping(name, createServiceRef(serviceName, testNamespace)), nil - }) - - serving.AddReactor("update", "domainmappings", - func(a clienttesting.Action) (bool, runtime.Object, error) { - createDomainMapping := a.(clienttesting.UpdateAction).GetObject() - name := createDomainMapping.(metav1.Object).GetName() - - if name == domainName && attemptCount > 0 { - attemptCount-- - return true, nil, errors.NewConflict(eventingv1.Resource(domainMappingResource), "errorDomain", fmt.Errorf("error updating because of conflict")) - } - if name == "errorDomain" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, createDomainMapping, nil - }) - - t.Run("Update domain mapping successfully without any retries", func(t *testing.T) { - err := client.UpdateDomainMappingWithRetry(context.Background(), domainName, func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, nil - }, maxAttempts) - assert.NilError(t, err, "No retries required as no conflict error occurred") - }) - - t.Run("Update domain mapping with retry after max retries", func(t *testing.T) { - attemptCount = maxAttempts - 1 - err := client.UpdateDomainMappingWithRetry(context.Background(), domainName, func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, nil - }, maxAttempts) - assert.NilError(t, err, "Update retried %d times and succeeded", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update domain mapping with retry and fail with conflict after exhausting max retries", func(t *testing.T) { - attemptCount = maxAttempts - err := client.UpdateDomainMappingWithRetry(context.Background(), domainName, func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update domain mapping with retry and fail with conflict after exhausting max retries", func(t *testing.T) { - attemptCount = maxAttempts - err := client.UpdateDomainMappingWithRetry(context.Background(), domainName, func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - }) - - t.Run("Update domain mapping with retry fails with a non conflict error", func(t *testing.T) { - err := client.UpdateDomainMappingWithRetry(context.Background(), "errorDomain", func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - }) - - t.Run("Update domain mapping with retry fails with resource already deleted error", func(t *testing.T) { - err := client.UpdateDomainMappingWithRetry(context.Background(), "deletedDomain", func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, nil - }, maxAttempts) - assert.ErrorContains(t, err, "marked for deletion") - }) - - t.Run("Update domain mapping with retry fails with error from updateFunc", func(t *testing.T) { - err := client.UpdateDomainMappingWithRetry(context.Background(), domainName, func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, fmt.Errorf("error updating object") - }, maxAttempts) - assert.ErrorContains(t, err, "error updating object") - }) - - t.Run("Update domain mapping with retry fails with error from GetDomainMapping", func(t *testing.T) { - err := client.UpdateDomainMappingWithRetry(context.Background(), "getErrorDomain", func(domain *servingv1beta1.DomainMapping) (*servingv1beta1.DomainMapping, error) { - return domain, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - }) -} - -func TestDeleteDomainMapping(t *testing.T) { - serving, client := setup() - domainName := "foo.bar" - - serving.AddReactor("delete", domainMappingResource, - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - assert.Assert(t, name != "") - assert.Equal(t, testNamespace, a.GetNamespace()) - if name == domainName { - return true, nil, nil - } - return true, nil, errors.NewNotFound(servingv1beta1.Resource(domainMappingResource), name) - }) - - t.Run("delete domain mapping returns no error", func(t *testing.T) { - err := client.DeleteDomainMapping(context.Background(), domainName) - assert.NilError(t, err) - }) - - t.Run("delete non-existing domain mapping returns error", func(t *testing.T) { - nonExistingName := "does-not-exist" - err := client.DeleteDomainMapping(context.Background(), nonExistingName) - assert.ErrorContains(t, err, "not found") - assert.ErrorContains(t, err, nonExistingName) - assert.ErrorType(t, err, &errors.StatusError{}) - }) -} - -func TestListDomainMappings(t *testing.T) { - serving, client := setup() - t.Run("list domain mappings returns a list of objects", func(t *testing.T) { - dm1 := createDomainMapping("dm-1", createServiceRef("svc1", testNamespace)) - dm2 := createDomainMapping("dm-2", createServiceRef("svc2", testNamespace)) - dm3 := createDomainMapping("dm-3", createServiceRef("svc3", testNamespace)) - serving.AddReactor("list", domainMappingResource, - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, &servingv1beta1.DomainMappingList{Items: []servingv1beta1.DomainMapping{*dm1, *dm2, *dm3}}, nil - }) - listServices, err := client.ListDomainMappings(context.Background()) - assert.NilError(t, err) - assert.Assert(t, len(listServices.Items) == 3) - assert.Equal(t, listServices.Items[0].Name, "dm-1") - assert.Equal(t, listServices.Items[1].Name, "dm-2") - assert.Equal(t, listServices.Items[2].Name, "dm-3") - validateGroupVersionKind(t, listServices) - validateGroupVersionKind(t, &listServices.Items[0]) - validateGroupVersionKind(t, &listServices.Items[1]) - validateGroupVersionKind(t, &listServices.Items[2]) - }) -} - -func validateGroupVersionKind(t *testing.T, obj runtime.Object) { - gvkExpected, err := util.GetGroupVersionKind(obj, servingv1beta1.SchemeGroupVersion, scheme.Scheme) - assert.NilError(t, err) - gvkGiven := obj.GetObjectKind().GroupVersionKind() - fmt.Println(gvkGiven.String()) - assert.Equal(t, *gvkExpected, gvkGiven, "GVK should be the same") -} - -func createDomainMapping(name string, ref duckv1.KReference) *servingv1beta1.DomainMapping { - return NewDomainMappingBuilder(name).Namespace("default").Reference(ref).Build() -} - -func createDomainMappingWithTls(name string, ref duckv1.KReference, tls string) *servingv1beta1.DomainMapping { - return NewDomainMappingBuilder(name).Namespace("default").Reference(ref).TLS(tls).Build() -} -func createServiceRef(service, namespace string) duckv1.KReference { - return duckv1.KReference{Name: service, - Kind: "Service", - APIVersion: "serving.knative.dev/v1", - Namespace: namespace, - } -} diff --git a/pkg/sources/common_test.go b/pkg/sources/common_test.go deleted file mode 100644 index 5cb1c0e120..0000000000 --- a/pkg/sources/common_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2020 The Knative 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 sources - -import ( - "testing" - - "gotest.tools/v3/assert" - - sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" - sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" -) - -func TestBuiltInSourcesGVks(t *testing.T) { - gvks := BuiltInSourcesGVKs() - for _, each := range gvks { - if each.Kind != "PingSource" { - assert.DeepEqual(t, each.GroupVersion(), sourcesv1.SchemeGroupVersion) - } else { - assert.DeepEqual(t, each.GroupVersion(), sourcesv1beta2.SchemeGroupVersion) - } - } - assert.Equal(t, len(gvks), 4) -} diff --git a/pkg/sources/v1/apiserver_client_mock_test.go b/pkg/sources/v1/apiserver_client_mock_test.go deleted file mode 100644 index 5af02abe1f..0000000000 --- a/pkg/sources/v1/apiserver_client_mock_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "testing" - - v1 "knative.dev/eventing/pkg/apis/sources/v1" -) - -func TestMockKnAPIServerSourceClient(t *testing.T) { - - client := NewMockKnAPIServerSourceClient(t) - - recorder := client.Recorder() - - // Record all services - recorder.GetAPIServerSource("hello", nil, nil) - recorder.CreateAPIServerSource(&v1.ApiServerSource{}, nil) - recorder.UpdateAPIServerSource(&v1.ApiServerSource{}, nil) - recorder.DeleteAPIServerSource("hello", nil) - - // Call all service - ctx := context.Background() - client.GetAPIServerSource(ctx, "hello") - client.CreateAPIServerSource(ctx, &v1.ApiServerSource{}) - client.UpdateAPIServerSource(ctx, &v1.ApiServerSource{}) - client.DeleteAPIServerSource(ctx, "hello") - - // Validate - recorder.Validate() -} diff --git a/pkg/sources/v1/apiserver_client_test.go b/pkg/sources/v1/apiserver_client_test.go deleted file mode 100644 index 62a4ee5b51..0000000000 --- a/pkg/sources/v1/apiserver_client_test.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "fmt" - "testing" - - "gotest.tools/v3/assert" - "k8s.io/apimachinery/pkg/runtime" - v1 "knative.dev/eventing/pkg/apis/sources/v1" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clienttesting "k8s.io/client-go/testing" - fake "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1/fake" - duckv1 "knative.dev/pkg/apis/duck/v1" -) - -var testAPIServerSourceNamespace = "test-ns" - -func setupAPIServerSourcesClient(t *testing.T) (fakeSources fake.FakeSourcesV1, client KnAPIServerSourcesClient) { - fakeSources = fake.FakeSourcesV1{Fake: &clienttesting.Fake{}} - client = NewKnSourcesClient(&fakeSources, testAPIServerSourceNamespace).APIServerSourcesClient() - assert.Equal(t, client.Namespace(), testAPIServerSourceNamespace) - return -} - -func TestDeleteApiServerSource(t *testing.T) { - sourcesServer, client := setupAPIServerSourcesClient(t) - - sourcesServer.AddReactor("delete", "apiserversources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while deleting ApiServer source %s", name) - } - return true, nil, nil - }) - - err := client.DeleteAPIServerSource(context.Background(), "foo") - assert.NilError(t, err) - - err = client.DeleteAPIServerSource(context.Background(), "errorSource") - assert.ErrorContains(t, err, "errorSource") -} - -func TestCreateApiServerSource(t *testing.T) { - sourcesServer, client := setupAPIServerSourcesClient(t) - - sourcesServer.AddReactor("create", "apiserversources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - newSource := a.(clienttesting.CreateAction).GetObject() - name := newSource.(metav1.Object).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while creating ApiServer source %s", name) - } - return true, newSource, nil - }) - err := client.CreateAPIServerSource(context.Background(), newAPIServerSource("foo", "Event")) - assert.NilError(t, err) - - err = client.CreateAPIServerSource(context.Background(), newAPIServerSource("errorSource", "Event")) - assert.ErrorContains(t, err, "errorSource") - -} - -func TestGetApiServerSource(t *testing.T) { - sourcesServer, client := setupAPIServerSourcesClient(t) - - sourcesServer.AddReactor("get", "apiserversources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while getting ApiServer source %s", name) - } - return true, newAPIServerSource(name, "Event"), nil - }) - testsource, err := client.GetAPIServerSource(context.Background(), "foo") - assert.NilError(t, err) - assert.Equal(t, testsource.Name, "foo") - assert.Equal(t, testsource.Spec.Sink.Ref.Name, "foosvc") - - _, err = client.GetAPIServerSource(context.Background(), "errorSource") - assert.ErrorContains(t, err, "errorSource") -} - -func TestUpdateApiServerSource(t *testing.T) { - sourcesServer, client := setupAPIServerSourcesClient(t) - - sourcesServer.AddReactor("update", "apiserversources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - updatedSource := a.(clienttesting.UpdateAction).GetObject() - name := updatedSource.(metav1.Object).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while updating ApiServer source %s", name) - } - return true, NewAPIServerSourceBuilderFromExisting(updatedSource.(*v1.ApiServerSource)).Build(), nil - }) - err := client.UpdateAPIServerSource(context.Background(), newAPIServerSource("foo", "Event")) - assert.NilError(t, err) - - err = client.UpdateAPIServerSource(context.Background(), newAPIServerSource("errorSource", "Event")) - assert.ErrorContains(t, err, "errorSource") -} - -func TestListAPIServerSource(t *testing.T) { - sourcesServer, client := setupAPIServerSourcesClient(t) - - sourcesServer.AddReactor("list", "apiserversources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - cJSource := newAPIServerSource("testsource", "Event") - return true, &v1.ApiServerSourceList{Items: []v1.ApiServerSource{*cJSource}}, nil - }) - - sourceList, err := client.ListAPIServerSource(context.Background()) - assert.NilError(t, err) - assert.Equal(t, len(sourceList.Items), 1) -} - -func newAPIServerSource(name, resource string) *v1.ApiServerSource { - b := NewAPIServerSourceBuilder(name). - ServiceAccount("testsa"). - EventMode("Reference"). - CloudEventOverrides(map[string]string{"type": "foo"}, []string{}). - Sink(duckv1.Destination{ - Ref: &duckv1.KReference{ - Kind: "Service", - Name: "foosvc", - Namespace: "default", - }}) - - if resource != "" { - b.Resources([]v1.APIVersionKindSelector{{ - APIVersion: "v1", - Kind: resource, - }}) - } - return b.Build() -} diff --git a/pkg/sources/v1/binding_client_mock_test.go b/pkg/sources/v1/binding_client_mock_test.go deleted file mode 100644 index d2a5b31420..0000000000 --- a/pkg/sources/v1/binding_client_mock_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "testing" - - v1 "knative.dev/eventing/pkg/apis/sources/v1" -) - -func TestMockKnClient(t *testing.T) { - client := NewMockKnSinkBindingClient(t) - - recorder := client.Recorder() - - // Record all services - recorder.GetSinkBinding("hello", nil, nil) - recorder.CreateSinkBinding(&v1.SinkBinding{}, nil) - recorder.DeleteSinkBinding("hello", nil) - recorder.ListSinkBindings(nil, nil) - recorder.UpdateSinkBinding(&v1.SinkBinding{}, nil) - - // Call all service - ctx := context.Background() - client.GetSinkBinding(ctx, "hello") - client.CreateSinkBinding(ctx, &v1.SinkBinding{}) - client.DeleteSinkBinding(ctx, "hello") - client.ListSinkBindings(ctx) - client.UpdateSinkBinding(ctx, &v1.SinkBinding{}) - - // Validate - recorder.Validate() -} diff --git a/pkg/sources/v1/binding_client_test.go b/pkg/sources/v1/binding_client_test.go deleted file mode 100644 index 78228166d1..0000000000 --- a/pkg/sources/v1/binding_client_test.go +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright © 2019 The Knative 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 v1 - -import ( - "context" - "fmt" - "testing" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - clienttesting "k8s.io/client-go/testing" - v1 "knative.dev/eventing/pkg/apis/sources/v1" - "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1/fake" - duckv1 "knative.dev/pkg/apis/duck/v1" - "knative.dev/pkg/tracker" -) - -var testNamespace = "test-ns" - -func setup() (fakeSvr fake.FakeSourcesV1, client KnSinkBindingClient) { - fakeE := fake.FakeSourcesV1{Fake: &clienttesting.Fake{}} - cli := NewKnSourcesClient(&fakeE, "test-ns").SinkBindingClient() - return fakeE, cli -} - -func TestDeleteSinkBinding(t *testing.T) { - var name = "new-binding" - server, client := setup() - - server.AddReactor("delete", "sinkbindings", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - if name == "errorSinkBinding" { - return true, nil, fmt.Errorf("error while deleting binding %s", name) - } - return true, nil, nil - }) - - err := client.DeleteSinkBinding(context.Background(), name) - assert.NilError(t, err) - - err = client.DeleteSinkBinding(context.Background(), "errorSinkBinding") - assert.ErrorContains(t, err, "errorSinkBinding") -} - -func TestCreateSinkBinding(t *testing.T) { - var name = "new-binding" - server, client := setup() - - objNew := newSinkBinding(name, "mysvc", "myping") - - server.AddReactor("create", "sinkbindings", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - name := a.(clienttesting.CreateAction).GetObject().(metav1.Object).GetName() - if name == objNew.Name { - objNew.Generation = 2 - return true, objNew, nil - } - return true, nil, fmt.Errorf("error while creating binding %s", name) - }) - - t.Run("create binding without error", func(t *testing.T) { - err := client.CreateSinkBinding(context.Background(), objNew) - assert.NilError(t, err) - }) - - t.Run("create binding with an error returns an error object", func(t *testing.T) { - err := client.CreateSinkBinding(context.Background(), newSinkBinding("unknown", "mysvc", "mypings")) - assert.ErrorContains(t, err, "unknown") - }) -} - -func TestGetSinkBinding(t *testing.T) { - var name = "mysinkbinding" - server, client := setup() - - server.AddReactor("get", "sinkbindings", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "errorSinkBinding" { - return true, nil, fmt.Errorf("error while getting binding %s", name) - } - return true, newSinkBinding(name, "mysvc", "myping"), nil - }) - - binding, err := client.GetSinkBinding(context.Background(), name) - assert.NilError(t, err) - assert.Equal(t, binding.Name, name) - assert.Equal(t, binding.Spec.Sink.Ref.Name, "mysvc") - assert.Equal(t, binding.Spec.Subject.Name, "myping") - - _, err = client.GetSinkBinding(context.Background(), "errorSinkBinding") - assert.ErrorContains(t, err, "errorSinkBinding") -} - -func TestListSinkBinding(t *testing.T) { - serving, client := setup() - - t.Run("list binding returns a list of sink-bindings", func(t *testing.T) { - binding1 := newSinkBinding("binding-1", "mysvc-1", "myping") - binding2 := newSinkBinding("binding-2", "mysvc-2", "myping") - - serving.AddReactor("list", "sinkbindings", - func(a clienttesting.Action) (bool, runtime.Object, error) { - assert.Equal(t, testNamespace, a.GetNamespace()) - return true, &v1.SinkBindingList{Items: []v1.SinkBinding{*binding1, *binding2}}, nil - }) - - listSinkBindings, err := client.ListSinkBindings(context.Background()) - assert.NilError(t, err) - assert.Assert(t, len(listSinkBindings.Items) == 2) - assert.Equal(t, listSinkBindings.Items[0].Name, "binding-1") - assert.Equal(t, listSinkBindings.Items[0].Spec.Sink.Ref.Name, "mysvc-1") - assert.Equal(t, listSinkBindings.Items[0].Spec.Subject.Name, "myping") - assert.Equal(t, listSinkBindings.Items[1].Name, "binding-2") - assert.Equal(t, listSinkBindings.Items[1].Spec.Sink.Ref.Name, "mysvc-2") - assert.Equal(t, listSinkBindings.Items[1].Spec.Subject.Name, "myping") - - }) -} - -func TestSinkBindingBuilderCloudEventOverrides(t *testing.T) { - aBuilder := NewSinkBindingBuilder("testsinkbinding") - aBuilder.CloudEventOverrides(map[string]string{"type": "foo"}, []string{}) - a, err := aBuilder.Build() - assert.NilError(t, err) - - t.Run("update bindings", func(t *testing.T) { - bBuilder := NewSinkBindingBuilderFromExisting(a) - b, err := bBuilder.Build() - assert.NilError(t, err) - assert.DeepEqual(t, b, a) - bBuilder.CloudEventOverrides(map[string]string{"type": "new"}, []string{}) - expected := &duckv1.CloudEventOverrides{ - Extensions: map[string]string{ - "type": "new", - }, - } - - assert.DeepEqual(t, expected, b.Spec.CloudEventOverrides) - }) - - t.Run("update bindings with both new entry and old entry", func(t *testing.T) { - bBuilder := NewSinkBindingBuilderFromExisting(a) - b, err := bBuilder.Build() - assert.NilError(t, err) - assert.DeepEqual(t, b, a) - bBuilder.CloudEventOverrides(map[string]string{"source": "bar"}, []string{}) - expected := &duckv1.CloudEventOverrides{ - Extensions: map[string]string{ - "type": "foo", - "source": "bar", - }, - } - assert.DeepEqual(t, expected, b.Spec.CloudEventOverrides) - }) - - t.Run("update bindings with new entry and removed entry", func(t *testing.T) { - bBuilder := NewSinkBindingBuilderFromExisting(a) - c, err := bBuilder.Build() - assert.NilError(t, err) - assert.DeepEqual(t, c, a) - bBuilder.CloudEventOverrides(map[string]string{"new": "entry"}, []string{"type"}) - expected := &duckv1.CloudEventOverrides{ - Extensions: map[string]string{ - "new": "entry", - }, - } - assert.DeepEqual(t, expected, c.Spec.CloudEventOverrides) - }) - -} - -func TestSinkBindingBuilderForSubjectError(t *testing.T) { - - b, err := NewSinkBindingBuilder("test").SubjectName("bla").Build() - assert.Assert(t, b == nil) - assert.ErrorContains(t, err, "group") - assert.ErrorContains(t, err, "version") - assert.ErrorContains(t, err, "kind") - - b, err = NewSinkBindingBuilder("test"). - SubjectGVK(&schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}). - SubjectName("foo"). - AddSubjectMatchLabel("bla", "blub"). - Build() - assert.ErrorContains(t, err, "label selector") - assert.ErrorContains(t, err, "name") - assert.ErrorContains(t, err, "subject") - assert.Assert(t, b == nil) - -} - -func TestSinkBindingBuilderForSubject(t *testing.T) { - gvk := schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"} - - b, err := NewSinkBindingBuilder("test"). - SubjectGVK(&gvk). - SubjectName("foo"). - Build() - assert.NilError(t, err) - subject := b.Spec.Subject - assert.Equal(t, subject.Name, "foo") - assert.Assert(t, subject.Selector == nil) - assert.DeepEqual(t, subject.GroupVersionKind(), gvk) - - b, err = NewSinkBindingBuilder("test"). - SubjectGVK(&schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}). - AddSubjectMatchLabel("bla", "blub"). - AddSubjectMatchLabel("foo", "bar"). - Build() - - assert.NilError(t, err) - subject = b.Spec.Subject - assert.Equal(t, subject.Name, "") - assert.DeepEqual(t, subject.GroupVersionKind(), gvk) - selector := map[string]string{ - "bla": "blub", - "foo": "bar", - } - assert.DeepEqual(t, subject.Selector.MatchLabels, selector) -} - -func TestSinkBindingBuilderForSubjectDirect(t *testing.T) { - - subject := tracker.Reference{ - Name: "direct", - } - b, err := NewSinkBindingBuilder("test"). - Subject(&subject). - SubjectName("nope"). // should be ignored - AddSubjectMatchLabel("bla", "blub"). // should be ignored - Build() - assert.NilError(t, err) - subject = b.Spec.Subject - assert.Equal(t, subject.Name, "direct") - assert.Assert(t, subject.Selector == nil) -} - -func newSinkBinding(name, sinkService, pingName string) *v1.SinkBinding { - sink := &duckv1.Destination{ - Ref: &duckv1.KReference{Name: sinkService, Kind: "Service", Namespace: "default", APIVersion: "serving.knative.dev/v1"}, - } - b, _ := NewSinkBindingBuilder(name). - Namespace(testNamespace). - Sink(sink). - SubjectGVK(&schema.GroupVersionKind{Group: "batch", Version: "v1beta1", Kind: "CronJob"}). - SubjectName(pingName). - CloudEventOverrides(map[string]string{"type": "foo"}, []string{}). - Build() - return b -} diff --git a/pkg/sources/v1/container_client_mock_test.go b/pkg/sources/v1/container_client_mock_test.go deleted file mode 100644 index 020a63aba1..0000000000 --- a/pkg/sources/v1/container_client_mock_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2020 The Knative 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 v1 - -import ( - "context" - "testing" - - v1 "knative.dev/eventing/pkg/apis/sources/v1" -) - -func TestMockKnConatinerSourceClient(t *testing.T) { - client := NewMockKnContainerSourceClient(t) - - recorder := client.Recorder() - - // Record all services - recorder.GetContainerSource("hello", nil, nil) - recorder.CreateContainerSource(&v1.ContainerSource{}, nil) - recorder.DeleteContainerSource("hello", nil) - recorder.ListContainerSources(nil, nil) - recorder.UpdateContainerSource(&v1.ContainerSource{}, nil) - - recorder.GetContainerSource("hello", &v1.ContainerSource{}, nil) - recorder.UpdateContainerSource(&v1.ContainerSource{}, nil) - - // Call all service - ctx := context.Background() - client.GetContainerSource(ctx, "hello") - client.CreateContainerSource(ctx, &v1.ContainerSource{}) - client.DeleteContainerSource("hello", ctx) - client.ListContainerSources(ctx) - client.UpdateContainerSource(ctx, &v1.ContainerSource{}) - client.UpdateContainerSourceWithRetry(ctx, "hello", func(source *v1.ContainerSource) (*v1.ContainerSource, error) { - return source, nil - }, 10) - - // Validate - recorder.Validate() -} diff --git a/pkg/sources/v1/container_client_test.go b/pkg/sources/v1/container_client_test.go deleted file mode 100644 index 33f7633ad3..0000000000 --- a/pkg/sources/v1/container_client_test.go +++ /dev/null @@ -1,238 +0,0 @@ -/* -Copyright 2020 The Knative 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 v1 - -import ( - "context" - "fmt" - "testing" - - "k8s.io/apimachinery/pkg/api/errors" - eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" - - "gotest.tools/v3/assert" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - clienttesting "k8s.io/client-go/testing" - v1 "knative.dev/eventing/pkg/apis/sources/v1" - fake "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1/fake" - duckv1 "knative.dev/pkg/apis/duck/v1" -) - -func setupFakeContainerSourcesClient() (fakeSvr fake.FakeSourcesV1, client KnContainerSourcesClient) { - fakeE := fake.FakeSourcesV1{Fake: &clienttesting.Fake{}} - cli := NewKnSourcesClient(&fakeE, "test-ns").ContainerSourcesClient() - return fakeE, cli -} - -func TestDeleteContainerSourceSource(t *testing.T) { - sourcesServer, client := setupFakeContainerSourcesClient() - - sourcesServer.AddReactor("delete", "containersources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - fmt.Printf("name=%s \n", name) - if name == "errorSource" { - return true, nil, fmt.Errorf("error while deleting ContainerSource source %s", name) - } - return true, nil, nil - }) - - err := client.DeleteContainerSource("foo", context.Background()) - assert.NilError(t, err) - - err = client.DeleteContainerSource("errorSource", context.Background()) - assert.ErrorContains(t, err, "errorSource") -} - -func TestCreateContainerSourceSource(t *testing.T) { - sourcesServer, client := setupFakeContainerSourcesClient() - - sourcesServer.AddReactor("create", "containersources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - newSource := a.(clienttesting.CreateAction).GetObject() - name := newSource.(metav1.Object).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while creating ContainerSource source %s", name) - } - return true, newSource, nil - }) - err := client.CreateContainerSource(context.Background(), newContainerSource("foo", "Event")) - assert.NilError(t, err) - - err = client.CreateContainerSource(context.Background(), newContainerSource("errorSource", "Event")) - assert.ErrorContains(t, err, "errorSource") - -} - -func TestGetContainerSource(t *testing.T) { - sourcesServer, client := setupFakeContainerSourcesClient() - - sourcesServer.AddReactor("get", "containersources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while getting Container source %s", name) - } - return true, newContainerSource(name, "Event"), nil - }) - testsource, err := client.GetContainerSource(context.Background(), "foo") - assert.NilError(t, err) - assert.Equal(t, testsource.Name, "foo") - assert.Equal(t, testsource.Spec.Sink.Ref.Name, "foosvc") - - _, err = client.GetContainerSource(context.Background(), "errorSource") - assert.ErrorContains(t, err, "errorSource") -} - -func TestUpdateContainerSource(t *testing.T) { - sourcesServer, client := setupFakeContainerSourcesClient() - - sourcesServer.AddReactor("update", "containersources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - updatedSource := a.(clienttesting.UpdateAction).GetObject() - name := updatedSource.(metav1.Object).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while updating Container source %s", name) - } - return true, NewContainerSourceBuilderFromExisting(updatedSource.(*v1.ContainerSource)).Build(), nil - }) - err := client.UpdateContainerSource(context.Background(), newContainerSource("foo", "Event")) - assert.NilError(t, err) - - err = client.UpdateContainerSource(context.Background(), newContainerSource("errorSource", "Event")) - assert.ErrorContains(t, err, "errorSource") -} - -func TestUpdateContainerSourceWithRetry(t *testing.T) { - serving, client := setupFakeContainerSourcesClient() - - sourceName := "foo" - - var attemptCount, maxAttempts = 0, 5 - serving.AddReactor("get", "containersources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "deletedDomain" { - domain := newContainerSource(name, "Event") - now := metav1.Now() - domain.DeletionTimestamp = &now - return true, domain, nil - } - if name == "getErrorSource" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, newContainerSource(name, "Event"), nil - }) - - serving.AddReactor("update", "containersources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - newContainerSource := a.(clienttesting.UpdateAction).GetObject() - name := newContainerSource.(metav1.Object).GetName() - - if name == sourceName && attemptCount > 0 { - attemptCount-- - return true, nil, errors.NewConflict(eventingv1.Resource("containersources"), "errorDomain", fmt.Errorf("error updating because of conflict")) - } - if name == "errorDomain" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, newContainerSource, nil - }) - - // Update container source successfully without any retries - err := client.UpdateContainerSourceWithRetry(context.Background(), sourceName, func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, nil - }, maxAttempts) - assert.NilError(t, err, "No retries required as no conflict error occurred") - - // Update container source with retry after max retries - attemptCount = maxAttempts - 1 - err = client.UpdateContainerSourceWithRetry(context.Background(), sourceName, func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, nil - }, maxAttempts) - assert.NilError(t, err, "Update retried %d times and succeeded", maxAttempts) - assert.Equal(t, attemptCount, 0) - - // Update container source with retry and fail with conflict after exhausting max retries - attemptCount = maxAttempts - err = client.UpdateContainerSourceWithRetry(context.Background(), sourceName, func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - - // Update container source with retry and fail with conflict after exhausting max retries - attemptCount = maxAttempts - err = client.UpdateContainerSourceWithRetry(context.Background(), sourceName, func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - - // Update container source with retry fails with a non conflict error - err = client.UpdateContainerSourceWithRetry(context.Background(), "errorDomain", func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - - // Update container source with retry fails with resource already deleted error - err = client.UpdateContainerSourceWithRetry(context.Background(), "deletedDomain", func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, nil - }, maxAttempts) - assert.ErrorContains(t, err, "marked for deletion") - - // Update container source with retry fails with error from updateFunc - err = client.UpdateContainerSourceWithRetry(context.Background(), sourceName, func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, fmt.Errorf("error updating object") - }, maxAttempts) - assert.ErrorContains(t, err, "error updating object") - - // Update container source with retry fails with error from GetContainerSource - err = client.UpdateContainerSourceWithRetry(context.Background(), "getErrorSource", func(container *v1.ContainerSource) (*v1.ContainerSource, error) { - return container, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) -} - -func TestListContainerSource(t *testing.T) { - sourcesServer, client := setupFakeContainerSourcesClient() - - sourcesServer.AddReactor("list", "containersources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - cJSource := newContainerSource("testsource", "Event") - return true, &v1.ContainerSourceList{Items: []v1.ContainerSource{*cJSource}}, nil - }) - - sourceList, err := client.ListContainerSources(context.Background()) - assert.NilError(t, err) - assert.Equal(t, len(sourceList.Items), 1) -} - -func newContainerSource(name, container string) *v1.ContainerSource { - b := NewContainerSourceBuilder(name). - PodSpec(corev1.PodSpec{}). - Sink(duckv1.Destination{ - Ref: &duckv1.KReference{ - Kind: "Service", - Name: "foosvc", - Namespace: "default", - }}) - - return b.Build() -} diff --git a/pkg/sources/v1beta2/ping_client_mock_test.go b/pkg/sources/v1beta2/ping_client_mock_test.go deleted file mode 100644 index 205d4313b6..0000000000 --- a/pkg/sources/v1beta2/ping_client_mock_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright © 2019 The Knative 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 v1beta2 - -import ( - "context" - "testing" - - sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" -) - -func TestMockKnPingSourceClient(t *testing.T) { - - client := NewMockKnPingSourceClient(t) - - recorder := client.Recorder() - - // Record all services - recorder.GetPingSource("hello", nil, nil) - recorder.CreatePingSource(&sourcesv1beta2.PingSource{}, nil) - recorder.UpdatePingSource(&sourcesv1beta2.PingSource{}, nil) - - recorder.GetPingSource("hello", &sourcesv1beta2.PingSource{}, nil) - recorder.UpdatePingSource(&sourcesv1beta2.PingSource{}, nil) - - recorder.DeletePingSource("hello", nil) - - // Call all service - ctx := context.Background() - client.GetPingSource(ctx, "hello") - client.CreatePingSource(ctx, &sourcesv1beta2.PingSource{}) - client.UpdatePingSource(ctx, &sourcesv1beta2.PingSource{}) - client.UpdatePingSourceWithRetry(ctx, "hello", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - return origSource, nil - }, 10) - client.DeletePingSource(ctx, "hello") - - // Validate - recorder.Validate() -} diff --git a/pkg/sources/v1beta2/ping_client_test.go b/pkg/sources/v1beta2/ping_client_test.go deleted file mode 100644 index e8aabb9b0f..0000000000 --- a/pkg/sources/v1beta2/ping_client_test.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright © 2019 The Knative 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 v1beta2 - -import ( - "context" - "fmt" - "testing" - - "k8s.io/apimachinery/pkg/api/errors" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - clienttesting "k8s.io/client-go/testing" - sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" - "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1beta2/fake" - duckv1 "knative.dev/pkg/apis/duck/v1" -) - -func setupPingSourcesClient(t *testing.T) (sources fake.FakeSourcesV1beta2, client KnPingSourcesClient) { - sources = fake.FakeSourcesV1beta2{Fake: &clienttesting.Fake{}} - client = NewKnSourcesClient(&sources, "test-ns").PingSourcesClient() - assert.Equal(t, client.Namespace(), "test-ns") - return -} - -func TestCreatePingSource(t *testing.T) { - sourcesServer, client := setupPingSourcesClient(t) - - sourcesServer.AddReactor("create", "pingsources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - newSource := a.(clienttesting.CreateAction).GetObject() - name := newSource.(metav1.Object).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while creating pingsource %s", name) - } - return true, newSource, nil - }) - - err := client.CreatePingSource(context.Background(), newPingSource("testsource", "mysvc")) - assert.NilError(t, err) - - err = client.CreatePingSource(context.Background(), newPingSource("testsource", "")) - assert.ErrorContains(t, err, "sink") - assert.ErrorContains(t, err, "required") - - err = client.CreatePingSource(context.Background(), newPingSource("errorSource", "mysvc")) - assert.ErrorContains(t, err, "errorSource") -} - -func TestUpdatePingSource(t *testing.T) { - sourcesServer, client := setupPingSourcesClient(t) - - sourcesServer.AddReactor("update", "pingsources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - newSource := a.(clienttesting.UpdateAction).GetObject() - name := newSource.(metav1.Object).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while updating pingsource %s", name) - } - return true, NewPingSourceBuilderFromExisting(newSource.(*sourcesv1beta2.PingSource)).Build(), nil - }) - - err := client.UpdatePingSource(context.Background(), newPingSource("testsource", "")) - assert.NilError(t, err) - - err = client.UpdatePingSource(context.Background(), newPingSource("errorSource", "")) - assert.ErrorContains(t, err, "errorSource") -} - -func TestUpdatePingSourceWithRetry(t *testing.T) { - sourcesServer, client := setupPingSourcesClient(t) - - var attemptCount, maxAttempts = 0, 5 - var newData = "newData" - sourcesServer.AddReactor("get", "pingsources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "deletedSource" { - source := newPingSource(name, "mysvc") - now := metav1.Now() - source.DeletionTimestamp = &now - return true, source, nil - } - if name == "getErrorSource" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, newPingSource(name, "mysvc"), nil - }) - - sourcesServer.AddReactor("update", "pingsources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - newSource := a.(clienttesting.UpdateAction).GetObject() - name := newSource.(metav1.Object).GetName() - - if name == "testSource" && attemptCount > 0 { - attemptCount-- - return true, nil, errors.NewConflict(sourcesv1beta2.Resource("pingsource"), "errorSource", fmt.Errorf("error updating because of conflict")) - } - if name == "errorSource" { - return true, nil, errors.NewInternalError(fmt.Errorf("mock internal error")) - } - return true, NewPingSourceBuilderFromExisting(newSource.(*sourcesv1beta2.PingSource)).Build(), nil - }) - - err := client.UpdatePingSourceWithRetry(context.Background(), "testSource", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - origSource.Spec.Data = newData - return origSource, nil - }, maxAttempts) - assert.NilError(t, err, "No retries required as no conflict error occurred") - - attemptCount = maxAttempts - 1 - err = client.UpdatePingSourceWithRetry(context.Background(), "testSource", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - origSource.Spec.Data = newData - return origSource, nil - }, maxAttempts) - assert.NilError(t, err, "Update retried %d times and succeeded", maxAttempts) - assert.Equal(t, attemptCount, 0) - - attemptCount = maxAttempts - err = client.UpdatePingSourceWithRetry(context.Background(), "testSource", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - origSource.Spec.Data = newData - return origSource, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsConflict, "Update retried %d times and failed", maxAttempts) - assert.Equal(t, attemptCount, 0) - - err = client.UpdatePingSourceWithRetry(context.Background(), "errorSource", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - origSource.Spec.Data = newData - return origSource, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) - - err = client.UpdatePingSourceWithRetry(context.Background(), "deletedSource", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - origSource.Spec.Data = newData - return origSource, nil - }, maxAttempts) - assert.ErrorContains(t, err, "marked for deletion") - - err = client.UpdatePingSourceWithRetry(context.Background(), "testSource", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - origSource.Spec.Data = newData - return origSource, fmt.Errorf("error updating object") - }, maxAttempts) - assert.ErrorContains(t, err, "error updating object") - - err = client.UpdatePingSourceWithRetry(context.Background(), "getErrorSource", func(origSource *sourcesv1beta2.PingSource) (*sourcesv1beta2.PingSource, error) { - origSource.Spec.Data = newData - return origSource, nil - }, maxAttempts) - assert.ErrorType(t, err, errors.IsInternalError) -} - -func TestDeletePingSource(t *testing.T) { - sourcesServer, client := setupPingSourcesClient(t) - - sourcesServer.AddReactor("delete", "pingsources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.DeleteAction).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while updating pingsource %s", name) - } - return true, nil, nil - }) - - err := client.DeletePingSource(context.Background(), "testsource") - assert.NilError(t, err) - - err = client.DeletePingSource(context.Background(), "errorSource") - assert.ErrorContains(t, err, "errorSource") -} - -func TestGetPingSource(t *testing.T) { - sourcesServer, client := setupPingSourcesClient(t) - - sourcesServer.AddReactor("get", "pingsources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - name := a.(clienttesting.GetAction).GetName() - if name == "errorSource" { - return true, nil, fmt.Errorf("error while updating pingsource %s", name) - } - return true, newPingSource(name, "mysvc"), nil - }) - - source, err := client.GetPingSource(context.Background(), "testsource") - assert.NilError(t, err) - assert.Equal(t, source.Name, "testsource") - assert.Equal(t, source.Spec.Sink.Ref.Name, "mysvc") - - _, err = client.GetPingSource(context.Background(), "errorSource") - assert.ErrorContains(t, err, "errorSource") -} - -func TestListPingSource(t *testing.T) { - sourcesServer, client := setupPingSourcesClient(t) - - sourcesServer.AddReactor("list", "pingsources", - func(a clienttesting.Action) (bool, runtime.Object, error) { - cJSource := newPingSource("testsource", "mysvc") - return true, &sourcesv1beta2.PingSourceList{Items: []sourcesv1beta2.PingSource{*cJSource}}, nil - }) - - sourceList, err := client.ListPingSource(context.Background()) - assert.NilError(t, err) - assert.Equal(t, len(sourceList.Items), 1) -} - -func newPingSource(name string, sink string) *sourcesv1beta2.PingSource { - b := NewPingSourceBuilder(name). - Schedule("* * * * *"). - Data("mydata"). - CloudEventOverrides(map[string]string{"type": "foo"}, []string{}) - - if sink != "" { - b.Sink( - duckv1.Destination{ - Ref: &duckv1.KReference{ - Kind: "Service", - Name: sink, - Namespace: "default", - }, - }) - } - return b.Build() -} diff --git a/pkg/templates/command_groups_test.go b/pkg/templates/command_groups_test.go index 0b7fcae66f..7e11c9d6d7 100644 --- a/pkg/templates/command_groups_test.go +++ b/pkg/templates/command_groups_test.go @@ -22,8 +22,8 @@ import ( "github.com/spf13/cobra" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) var groups = CommandGroups{ diff --git a/pkg/templates/template_engine_test.go b/pkg/templates/template_engine_test.go index 4d5b4722c8..d8b250a7f6 100644 --- a/pkg/templates/template_engine_test.go +++ b/pkg/templates/template_engine_test.go @@ -23,8 +23,8 @@ import ( "github.com/spf13/cobra" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) type testData struct { diff --git a/pkg/kn/traffic/compute.go b/pkg/traffic/compute.go similarity index 99% rename from pkg/kn/traffic/compute.go rename to pkg/traffic/compute.go index 2a0caa443b..65724ccbe1 100644 --- a/pkg/kn/traffic/compute.go +++ b/pkg/traffic/compute.go @@ -20,11 +20,11 @@ import ( "strings" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands/revision" + "knative.dev/client/pkg/commands/revision" "knative.dev/pkg/ptr" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands/flags" ) var latestRevisionRef = "@latest" diff --git a/pkg/kn/traffic/compute_test.go b/pkg/traffic/compute_test.go similarity index 99% rename from pkg/kn/traffic/compute_test.go rename to pkg/traffic/compute_test.go index bd0067894c..1ce3f4262d 100644 --- a/pkg/kn/traffic/compute_test.go +++ b/pkg/traffic/compute_test.go @@ -18,14 +18,14 @@ import ( "gotest.tools/v3/assert" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/client/pkg/kn/commands/revision" + "knative.dev/client/pkg/commands/revision" servingv1 "knative.dev/serving/pkg/apis/serving/v1" "testing" "github.com/spf13/cobra" - "knative.dev/client/pkg/kn/commands/flags" + "knative.dev/client/pkg/commands/flags" ) type trafficTestCase struct { diff --git a/pkg/util/compare_test.go b/pkg/util/compare_test.go deleted file mode 100644 index 261cf83765..0000000000 --- a/pkg/util/compare_test.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright © 2019 The Knative 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 util - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "gotest.tools/v3/assert" - "gotest.tools/v3/assert/cmp" -) - -type containsAllTestCase struct { - target string - substrings []string - success bool - missing []string -} - -type containsNoneTestCase struct { - target string - substrings []string - success bool - contains []string -} - -func TestContainsAll(t *testing.T) { - for i, tc := range []containsAllTestCase{ - { - target: "NAME SERVICE AGE CONDITIONS READY REASON", - substrings: []string{"REASON", "AGE"}, - success: true, - }, - { - "No resources found.", - []string{"NAME", "AGE"}, - false, - []string{"NAME", "AGE"}, - }, - { - "NAME SERVICE AGE CONDITIONS READY REASON", - []string{"NAME", "URL", "DOMAIN", "READY"}, - false, - []string{"URL", "DOMAIN"}, - }, - { - target: "Sword!", - substrings: []string{}, - success: true, - }, - } { - result := ContainsAll(tc.target, tc.substrings...)() - if result.Success() != tc.success { - t.Errorf("%d: Expecting %s to contain %s", i, tc.target, tc.substrings) - } - if !tc.success { - message := fmt.Sprintf("\nActual output: %s\nMissing strings: %s", tc.target, strings.Join(tc.missing[:], ", ")) - if !reflect.DeepEqual(result, cmp.ResultFailure(message)) { - t.Errorf("%d: Incorrect error message returned\nGot: %v\nExpecting: %s", i, result, message) - } - } - } -} - -func TestContainsIgnoreCase(t *testing.T) { - for i, tc := range []containsAllTestCase{ - { - target: "NAME SERVICE AGE CONDITIONS READY REASON", - substrings: []string{"reason", "age"}, - success: true, - }, - { - "No resources found.", - []string{"NAME", "AGE"}, - false, - []string{"name", "age"}, - }, - { - "NAME SERVICE AGE CONDITIONS READY REASON", - []string{"name", "url", "domain", "ready"}, - false, - []string{"url", "domain"}, - }, - } { - result := ContainsAllIgnoreCase(tc.target, tc.substrings...)() - if result.Success() != tc.success { - t.Errorf("%d: Expecting %s to contain %s", i, tc.target, tc.substrings) - } - if !tc.success { - message := fmt.Sprintf("\nActual output (lower-cased): %s\nMissing strings (lower-cased): %s", strings.ToLower(tc.target), strings.ToLower(strings.Join(tc.missing[:], ", "))) - if !reflect.DeepEqual(result, cmp.ResultFailure(message)) { - t.Errorf("%d: Incorrect error message returned\n. Got: %v\nExpecting: %s", i, result, message) - } - } - } -} - -func TestContainsNone(t *testing.T) { - for i, tc := range []containsNoneTestCase{ - { - target: "NAME SERVICE AGE CONDITIONS", - substrings: []string{"REASON", "READY", "foo", "bar"}, - success: true, - }, - { - "NAME SERVICE AGE CONDITIONS READY REASON", - []string{"foo", "bar", "NAME", "AGE"}, - false, - []string{"NAME", "AGE"}, - }, - { - "No resources found", - []string{"NAME", "URL", "DOMAIN", "READY", "resources"}, - false, - []string{"resources"}, - }, - { - target: "Sword!", - substrings: []string{}, - success: true, - }, - } { - comparison := ContainsNone(tc.target, tc.substrings...) - result := comparison() - if result.Success() != tc.success { - t.Errorf("%d: Expecting %s to contain %s", i, tc.target, tc.substrings) - } - if !tc.success { - message := fmt.Sprintf("\nActual output: %s\nContains strings: %s", tc.target, strings.Join(tc.contains[:], ", ")) - if !reflect.DeepEqual(result, cmp.ResultFailure(message)) { - t.Errorf("%d: Incorrect error message returned\nExpecting: %s", i, message) - } - } - } -} - -func TestSliceContainsIgnoreCase(t *testing.T) { - assert.Equal(t, - SliceContainsIgnoreCase([]string{"FOO", "bar"}, "foo"), - true) - assert.Equal(t, - SliceContainsIgnoreCase([]string{"BAR", "bar"}, "foo"), - false) -} diff --git a/pkg/util/corev1_helper_test.go b/pkg/util/corev1_helper_test.go deleted file mode 100644 index 52e4bfbd32..0000000000 --- a/pkg/util/corev1_helper_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2020 The Knative 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 util - -import ( - "testing" - - "gotest.tools/v3/assert" -) - -func TestGenerateVolumeName(t *testing.T) { - actual := []string{ - "Ab12~`!@#$%^&*()-=_+[]{}|/\\<>,./?:;\"'xZ", - "/Ab12~`!@#$%^&*()-=_+[]{}|/\\<>,./?:;\"'xZ/", - "", - "/", - "/path.mypath/", - "/.path.mypath", - } - - expected := []string{ - "ab12---------------------------------xz", - "ab12---------------------------------xz-", - "k-", - "k-", - "path-mypath-", - "k--path-mypath", - } - - for i := range actual { - actualName := GenerateVolumeName(actual[i]) - expectedName := appendCheckSum(expected[i], actual[i]) - assert.Equal(t, actualName, expectedName) - } - - // 63 char limit case, no need to append the checksum in expected string - expName_63 := "k---ab12---------------------------------xz-ab12--------------n" - assert.Equal(t, len(expName_63), 63) - assert.Equal(t, GenerateVolumeName("/./Ab12~`!@#$%^&*()-=_+[]{}|/\\<>,./?:;\"'xZ/Ab12~`!@#$%^&*()-=_+[]{}|/\\<>,./?:;\"'xZ/"), expName_63) -} diff --git a/pkg/util/logging_http_transport_test.go b/pkg/util/logging_http_transport_test.go deleted file mode 100644 index 915024715c..0000000000 --- a/pkg/util/logging_http_transport_test.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright © 2019 The Knative 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 util - -import ( - "bytes" - "errors" - "fmt" - "io" - "net/http" - "net/http/httputil" - "strings" - "testing" - - "gotest.tools/v3/assert" -) - -type fakeTransport struct { - requestDump string -} - -func (d *fakeTransport) RoundTrip(r *http.Request) (*http.Response, error) { - dump, err := httputil.DumpRequest(r, true) - if err != nil { - return nil, fmt.Errorf("dumping request: %w", err) - } - d.requestDump = string(dump) - return &http.Response{ - Status: "200 OK", - StatusCode: 200, - Proto: "HTTP/1.0", - Body: io.NopCloser(strings.NewReader("")), - }, nil -} - -type errorTransport struct{} - -func (d *errorTransport) RoundTrip(r *http.Request) (*http.Response, error) { - return nil, errors.New("This is an error") -} - -func TestWritesRequestResponse(t *testing.T) { - out := &bytes.Buffer{} - dt := &fakeTransport{} - transport := NewLoggingTransportWithStream(dt, out) - - body := "{this: is, the: body, of: [the, request]}" - req, _ := http.NewRequest("POST", "http://example.com", strings.NewReader(body)) - nonRedacted := "this string will be logged" - redacted := "this string will be redacted" - req.Header.Add("non-redacted", nonRedacted) - req.Header.Add(sensitiveRequestHeaders.List()[0], redacted) - - _, e := transport.RoundTrip(req) - assert.NilError(t, e) - s := out.String() - assert.Assert(t, strings.Contains(s, "REQUEST")) - assert.Assert(t, strings.Contains(s, "RESPONSE")) - assert.Assert(t, strings.Contains(s, body)) - assert.Assert(t, strings.Contains(s, nonRedacted)) - assert.Assert(t, !strings.Contains(s, redacted)) - - assert.Assert(t, strings.Contains(dt.requestDump, body)) - assert.Assert(t, strings.Contains(dt.requestDump, nonRedacted)) - assert.Assert(t, strings.Contains(dt.requestDump, redacted)) -} - -func TestElideAuthorizationHeader(t *testing.T) { - out := &bytes.Buffer{} - transport := NewLoggingTransportWithStream(&fakeTransport{}, out) - req, _ := http.NewRequest("GET", "http://example.com", nil) - req.Header.Set("X-Normal-Header", "la la normal text") - req.Header.Set("Authorization", "Bearer: SECRET") - _, e := transport.RoundTrip(req) - assert.NilError(t, e) - s := out.String() - assert.Assert(t, strings.Contains(s, "REQUEST")) - assert.Assert(t, strings.Contains(s, "Authorization")) - assert.Assert(t, strings.Contains(s, "********")) - assert.Assert(t, strings.Contains(s, "la la normal text")) - assert.Assert(t, !strings.Contains(s, "SECRET")) - assert.Assert(t, strings.Contains(s, "RESPONSE")) -} - -func TestWritesRequestError(t *testing.T) { - out := &bytes.Buffer{} - transport := NewLoggingTransportWithStream(&errorTransport{}, out) - req, _ := http.NewRequest("GET", "http://example.com", nil) - transport.RoundTrip(req) - s := out.String() - assert.Assert(t, strings.Contains(s, "REQUEST")) - assert.Assert(t, strings.Contains(s, "ERROR")) -} diff --git a/pkg/util/orderedmap_test.go b/pkg/util/orderedmap_test.go deleted file mode 100644 index 0475406dcf..0000000000 --- a/pkg/util/orderedmap_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright © 2019 The Knative 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 util - -import ( - "testing" - - "gotest.tools/v3/assert" -) - -func TestOrderedMapCreate(t *testing.T) { - initial := [][]string{{"1", "v1"}, {"2", "v2"}, {"3", "v3"}} - o := NewOrderedMapWithKVStrings(initial) - it := o.Iterator() - - assert.Equal(t, o.Len(), len(initial)) - i := 0 - - for k, v, ok := it.NextString(); ok; k, v, ok = it.NextString() { - assert.Equal(t, k, initial[i][0]) - assert.Equal(t, v, initial[i][1]) - i++ - } -} - -func TestOrderedMapSet(t *testing.T) { - initial := [][]string{{"1", "v1"}, {"2", "v2"}, {"3", "v3"}} - o := NewOrderedMapWithKVStrings(initial) - o.Set("4", "v4") - o.Set("2", "v2-1") - - expected := [][]string{{"1", "v1"}, {"2", "v2-1"}, {"3", "v3"}, {"4", "v4"}} - assert.Equal(t, o.Len(), len(expected)) - - i := 0 - it := o.Iterator() - - for k, v, ok := it.NextString(); ok; k, v, ok = it.NextString() { - assert.Equal(t, k, expected[i][0]) - assert.Equal(t, v, expected[i][1]) - i++ - } -} - -func TestOrderedMapGet(t *testing.T) { - initial := [][]string{{"1", "v1"}, {"2", "v2"}, {"3", "v3"}} - o := NewOrderedMapWithKVStrings(initial) - o.Set("4", "v4") - o.Set("2", "v2-1") - - expected := [][]string{{"1", "v1"}, {"2", "v2-1"}, {"3", "v3"}, {"4", "v4"}} - assert.Equal(t, o.Len(), len(expected)) - - for i := 0; i < len(expected); i++ { - assert.Equal(t, o.GetStringWithDefault(expected[i][0], ""), expected[i][1]) - } -} - -func TestOrderedMapDelete(t *testing.T) { - initial := [][]string{{"1", "v1"}, {"2", "v2"}, {"3", "v3"}} - o := NewOrderedMapWithKVStrings(initial) - o.Set("4", "v4") - o.Set("2", "v2-1") - o.Delete("3") - o.Delete("1") - - expected := [][]string{{"2", "v2-1"}, {"4", "v4"}} - assert.Equal(t, o.Len(), len(expected)) - - i := 0 - it := o.Iterator() - - for k, v, ok := it.NextString(); ok; k, v, ok = it.NextString() { - assert.Equal(t, k, expected[i][0]) - assert.Equal(t, v, expected[i][1]) - i++ - } -} diff --git a/pkg/util/parsing_helper_test.go b/pkg/util/parsing_helper_test.go deleted file mode 100644 index 60532ca852..0000000000 --- a/pkg/util/parsing_helper_test.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright © 2019 The Knative 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 util - -import ( - "fmt" - "os" - "testing" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/tracker" -) - -func TestMapFromArray(t *testing.T) { - testMapFromArray(t, []string{"good=value"}, "=", map[string]string{"good": "value"}) - testMapFromArray(t, []string{"multi=value", "other=value"}, "=", map[string]string{"multi": "value", "other": "value"}) - testMapFromArray(t, []string{"only,split,once", "just,once,"}, ",", map[string]string{"only": "split,once", "just": "once,"}) - testMapFromArray(t, []string{"empty="}, "=", map[string]string{"empty": ""}) -} - -func testMapFromArray(t *testing.T, input []string, delimiter string, expected map[string]string) { - actual, err := MapFromArray(input, delimiter) - assert.NilError(t, err) - assert.DeepEqual(t, expected, actual) -} - -func TestKeyValuePairListAndRemovalListFromArray(t *testing.T) { - testKeyValuePairListAndRemovalListFromArray(t, []string{"add=value"}, "=", [][]string{{"add", "value"}}, []string{}) - testKeyValuePairListAndRemovalListFromArray(t, []string{"add=value", "remove-"}, "=", [][]string{{"add", "value"}}, []string{"remove"}) -} - -func testKeyValuePairListAndRemovalListFromArray(t *testing.T, input []string, delimiter string, expectedKVList [][]string, expectedList []string) { - actualKVList, actualList, err := OrderedMapAndRemovalListFromArray(input, delimiter) - assert.NilError(t, err) - assert.DeepEqual(t, NewOrderedMapWithKVStrings(expectedKVList), actualKVList) - assert.DeepEqual(t, expectedList, actualList) -} - -func TestMapFromArrayNoDelimiter(t *testing.T) { - input := []string{"badvalue"} - _, err := MapFromArray(input, "+") - assert.ErrorContains(t, err, "Argument requires") - assert.ErrorContains(t, err, "+") -} - -func TestMapFromArrayNoDelimiterAllowingSingles(t *testing.T) { - input := []string{"okvalue"} - actual, err := MapFromArrayAllowingSingles(input, "+") - expected := map[string]string{"okvalue": ""} - assert.NilError(t, err) - assert.DeepEqual(t, expected, actual) -} - -func TestMapFromArrayEmptyValueEmptyDelimiter(t *testing.T) { - input := []string{""} - _, err := MapFromArray(input, "") - assert.ErrorContains(t, err, "Argument requires") -} - -func TestMapFromArrayEmptyValueEmptyDelimiterAllowingSingles(t *testing.T) { - input := []string{""} - _, err := MapFromArrayAllowingSingles(input, "") - assert.ErrorContains(t, err, "Argument requires") -} - -func TestMapFromArrayMapRepeat(t *testing.T) { - input := []string{"a1=b1", "a1=b2"} - _, err := MapFromArrayAllowingSingles(input, "=") - assert.ErrorContains(t, err, "duplicate") -} - -func TestMapFromArrayMapKeyEmpty(t *testing.T) { - input := []string{"=a1"} - _, err := MapFromArrayAllowingSingles(input, "=") - assert.ErrorContains(t, err, "empty") -} - -func TestParseMinusSuffix(t *testing.T) { - inputMap := map[string]string{"a1": "b1", "a2-": ""} - expectedMap := map[string]string{"a1": "b1"} - expectedStringToRemove := []string{"a2"} - stringToRemove := ParseMinusSuffix(inputMap) - assert.DeepEqual(t, expectedMap, inputMap) - assert.DeepEqual(t, expectedStringToRemove, stringToRemove) -} - -func TestStringMap(t *testing.T) { - inputMap := StringMap{"a1": "b1", "a2": "b2"} - mergedMap := map[string]string{"a1": "b1-new", "a3": "b3"} - removedKeys := []string{"a2", "a4"} - - inputMap.Merge(mergedMap).Remove(removedKeys) - expectedMap := StringMap{"a1": "b1-new", "a3": "b3"} - assert.DeepEqual(t, expectedMap, inputMap) -} - -func TestAddedAndRemovalListFromArray(t *testing.T) { - addList, removeList := AddedAndRemovalListsFromArray([]string{"addvalue1", "remove1-", "addvalue2", "remove2-"}) - assert.DeepEqual(t, []string{"addvalue1", "addvalue2"}, addList) - assert.DeepEqual(t, []string{"remove1", "remove2"}, removeList) - - addList, removeList = AddedAndRemovalListsFromArray([]string{"remove1-"}) - assert.DeepEqual(t, []string{}, addList) - assert.DeepEqual(t, []string{"remove1"}, removeList) - - addList, removeList = AddedAndRemovalListsFromArray([]string{"addvalue1"}) - assert.DeepEqual(t, []string{"addvalue1"}, addList) - assert.DeepEqual(t, []string{}, removeList) -} - -func TestToTrackerReference(t *testing.T) { - testToTrackerReference(t, - "Broker:eventing.knative.dev/v1:default", "demo", - &tracker.Reference{ - APIVersion: "eventing.knative.dev/v1", - Kind: "Broker", - Namespace: "demo", - Name: "default", - Selector: nil, - }, nil) - testToTrackerReference(t, - "Broker:eventing.knative.dev/v1:default", "", - &tracker.Reference{ - APIVersion: "eventing.knative.dev/v1", - Kind: "Broker", - Namespace: "", - Name: "default", - Selector: nil, - }, nil) - testToTrackerReference(t, - "Job:batch/v1:app=heartbeat-cron,priority=high", "demo", - &tracker.Reference{ - APIVersion: "batch/v1", - Kind: "Job", - Namespace: "demo", - Name: "", - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "heartbeat-cron", - "priority": "high", - }, - }, - }, nil) - testToTrackerReference(t, "", "demo", nil, - funcRef(func(t *testing.T, err error) { - assert.ErrorContains(t, err, "not in format kind:api/version:nameOrSelector") - })) - testToTrackerReference(t, "Job:batch/v1:app=acme,cmea", "demo", nil, - funcRef(func(t *testing.T, err error) { - assert.ErrorContains(t, err, "expected format: key1=value,key2=value") - })) - testToTrackerReference(t, "Job:batch/v1/next:acme", "demo", nil, - funcRef(func(t *testing.T, err error) { - assert.ErrorContains(t, err, "unexpected GroupVersion string") - })) -} - -func testToTrackerReference(t *testing.T, input, namespace string, expected *tracker.Reference, errMatch *func(*testing.T, error)) { - t.Helper() - t.Run(fmt.Sprintf("%s:%s", input, namespace), func(t *testing.T) { - ref, err := ToTrackerReference(input, namespace) - if err != nil { - if errMatch != nil { - m := *errMatch - m(t, err) - } else { - assert.NilError(t, err, "unexpected error") - } - } - assert.DeepEqual(t, expected, ref) - }) -} - -func funcRef(ref func(t *testing.T, err error)) *func(*testing.T, error) { - return &ref -} - -func TestGetEnvsFromFile(t *testing.T) { - file, err := os.CreateTemp("", "test-1") - assert.NilError(t, err) - file.WriteString(` -name=service-1 - -target=hello-world - -`) - defer os.Remove(file.Name()) - - envs, err := GetEnvsFromFile(file.Name(), "=") - assert.NilError(t, err) - assert.DeepEqual(t, envs, []string{"name=service-1", "target=hello-world"}) -} - -func TestGetEnvsFromFileErrorNotFound(t *testing.T) { - envs, err := GetEnvsFromFile("/tmp/somerandom/path/bla/bla", "=") - assert.ErrorContains(t, err, "no such file or directory") - assert.DeepEqual(t, envs, []string{}) -} diff --git a/pkg/util/schema_handling_test.go b/pkg/util/schema_handling_test.go deleted file mode 100644 index 861a43900a..0000000000 --- a/pkg/util/schema_handling_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2019 The Knative 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 util - -import ( - "testing" - - "k8s.io/apimachinery/pkg/runtime/schema" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/serving/pkg/client/clientset/versioned/scheme" -) - -func TestGVKUpdate(t *testing.T) { - service := servingv1.Service{} - err := UpdateGroupVersionKindWithScheme(&service, servingv1.SchemeGroupVersion, scheme.Scheme) - if err != nil { - t.Fatalf("cannot update GVK to a service %v", err) - } - if service.Kind != "Service" { - t.Fatalf("wrong kind '%s'", service.Kind) - } - if service.APIVersion != servingv1.SchemeGroupVersion.Group+"/"+servingv1.SchemeGroupVersion.Version { - t.Fatalf("wrong version '%s'", service.APIVersion) - } -} - -func TestGVKUpdateNegative(t *testing.T) { - service := servingv1.Service{} - err := UpdateGroupVersionKindWithScheme(&service, schema.GroupVersion{Group: "bla", Version: "blub"}, scheme.Scheme) - if err == nil { - t.Fatal("expect an error for an unregistered group version") - } -} diff --git a/pkg/util/unstructured_test.go b/pkg/util/unstructured_test.go deleted file mode 100644 index 0b9af60fda..0000000000 --- a/pkg/util/unstructured_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright © 2019 The Knative 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 util - -import ( - "testing" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -func TestToUnstructuredList(t *testing.T) { - serviceList := servingv1.ServiceList{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "v1", - Kind: "List", - }, - Items: []servingv1.Service{createService("s1"), createService("s2")}, - } - expectedList := &unstructured.UnstructuredList{ - Object: map[string]interface{}{ - "apiVersion": "v1", - "kind": "List", - }, - } - expectedList.Items = []unstructured.Unstructured{createUnstructured("s1"), createUnstructured("s2")} - unstructuredList, err := ToUnstructuredList(&serviceList) - assert.NilError(t, err) - assert.DeepEqual(t, unstructuredList, expectedList) - - service1 := createService("s3") - expectedList = &unstructured.UnstructuredList{} - expectedList.Items = []unstructured.Unstructured{createUnstructured("s3")} - unstructuredList, err = ToUnstructuredList(&service1) - assert.NilError(t, err) - assert.DeepEqual(t, unstructuredList, expectedList) -} - -func createService(name string) servingv1.Service { - service := servingv1.Service{ - TypeMeta: metav1.TypeMeta{ - Kind: "Service", - APIVersion: "serving.knative.dev/v1", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: "default", - }, - } - return service -} - -func createUnstructured(name string) unstructured.Unstructured { - return unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": "serving.knative.dev/v1", - "kind": "Service", - "metadata": map[string]interface{}{ - "namespace": "default", - "name": name, - "creationTimestamp": nil, - }, - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "metadata": map[string]interface{}{"creationTimestamp": nil}, - "spec": map[string]interface{}{"containers": nil}, - }, - }, - "status": map[string]interface{}{}, - }, - } -} diff --git a/pkg/wait/poll_watcher_test.go b/pkg/wait/poll_watcher_test.go deleted file mode 100644 index 707c8d1fbe..0000000000 --- a/pkg/wait/poll_watcher_test.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright © 2019 The Knative 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 wait - -import ( - "context" - "fmt" - "sync" - "testing" - "time" - - "gotest.tools/v3/assert" - api_errors "k8s.io/apimachinery/pkg/api/errors" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/watch" - - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -type fakePollInterval struct { - c chan time.Time -} - -func (f *fakePollInterval) PollChan() <-chan time.Time { - return f.c -} - -func (f *fakePollInterval) Stop() {} - -func newFakePollInterval(n int) PollInterval { - c := make(chan time.Time, n) - t := time.Now() - for i := 0; i < n; i++ { - c <- t.Add(time.Duration(i) * time.Second) - } - return &fakePollInterval{c} -} - -func newWatcherForTest(pollResults []runtime.Object) watch.Interface { - i := 0 - poll := func() (runtime.Object, error) { - defer func() { i++ }() - if pollResults[i] == nil { - // 404 - return nil, api_errors.NewNotFound(schema.GroupResource{Group: "thing", Resource: "stuff"}, "eggs") - } - return pollResults[i], nil - } - ret := &pollingWatcher{nil, "", "", "", time.Minute, make(chan bool), make(chan watch.Event), &sync.WaitGroup{}, - newFakePollInterval(len(pollResults)), poll} - ret.start() - return ret -} - -var a, aa, b, bb, c, cc, z, zz runtime.Object - -func init() { - a = &servingv1.Service{ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "a", UID: "one"}} - aa = a.DeepCopyObject() - b = &servingv1.Service{ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "b", UID: "one"}} - bb = b.DeepCopyObject() - c = &servingv1.Service{ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "c", UID: "one"}} - cc = c.DeepCopyObject() - z = &servingv1.Service{ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "z", UID: "two"}} - zz = z.DeepCopyObject() -} - -type testCase struct { - pollResults []runtime.Object - watchResults []watch.Event -} - -func TestNewWatcherWithVersion(t *testing.T) { - w, err := NewWatcherWithVersion(context.Background(), watchF(func(context.Context, metav1.ListOptions) (watch.Interface, error) { - return NewFakeWatch([]watch.Event{}), nil - }), nil, "mockNamespace", "resourceName", "mockName", "v1", 5*time.Second) - w.Stop() - assert.NilError(t, err) - w, err = NewWatcherWithVersion(context.Background(), watchF(func(context.Context, metav1.ListOptions) (watch.Interface, error) { - return NewFakeWatch([]watch.Event{}), fmt.Errorf("mockErrMsg") - }), nil, "mockNamespace", "resourceName", "mockName", "v1", 5*time.Second) - w.Stop() - assert.NilError(t, err) -} - -func TestPollWatcher(t *testing.T) { - cases := []testCase{ - // Doesn't exist for a while, then does for a while. - {[]runtime.Object{nil, nil, a, aa, nil}, []watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Deleted, Object: a}}}, - // Changes. - {[]runtime.Object{a, b}, []watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Modified, Object: b}}}, - // Changes but stays the same a couple times too. - {[]runtime.Object{a, aa, b, bb, c, cc, nil}, - []watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Modified, Object: b}, {Type: watch.Modified, Object: c}, {Type: watch.Deleted, Object: c}}}, - // Deleted and recreated between polls. - {[]runtime.Object{a, z}, []watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Deleted, Object: a}, {Type: watch.Added, Object: z}}}, - } - for _, c := range cases { - w := newWatcherForTest(c.pollResults) - for _, expected := range c.watchResults { - actual := <-w.ResultChan() - assert.Equal(t, actual.Type, expected.Type) - if actual.Type == watch.Added || actual.Type == watch.Modified || actual.Type == watch.Deleted { - fmt.Printf("expected, %v, actual %v\n", expected, actual) - assert.Equal(t, actual.Object.(metav1.Object).GetResourceVersion(), expected.Object.(metav1.Object).GetResourceVersion()) - assert.Equal(t, actual.Object.(metav1.Object).GetUID(), expected.Object.(metav1.Object).GetUID()) - } - } - w.Stop() - } -} diff --git a/pkg/wait/wait_for_ready_test.go b/pkg/wait/wait_for_ready_test.go deleted file mode 100644 index a6cdc40aed..0000000000 --- a/pkg/wait/wait_for_ready_test.go +++ /dev/null @@ -1,429 +0,0 @@ -// Copyright © 2019 The Knative 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 wait - -import ( - "bytes" - "context" - "errors" - "fmt" - "testing" - "time" - - "gotest.tools/v3/assert" - "gotest.tools/v3/assert/cmp" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - "knative.dev/client/pkg/util" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - servingv1 "knative.dev/serving/pkg/apis/serving/v1" -) - -type waitForReadyTestCase struct { - testcase string - events []watch.Event - timeout time.Duration - errorText string - messagesExpected []string -} - -func TestWaitCancellation(t *testing.T) { - fakeWatchApi := NewFakeWatch([]watch.Event{}) - fakeWatchApi.Start() - wfe := NewWaitForEvent("foobar", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return fakeWatchApi, nil - }, - func(e *watch.Event) bool { - return false - }) - - timeout := time.Second * 5 - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go func() { - time.Sleep(time.Millisecond * 500) - cancel() - }() - err, _ := wfe.Wait(ctx, "foobar", "", Options{Timeout: &timeout}, NoopMessageCallback()) - assert.Assert(t, errors.Is(err, context.Canceled)) - - ctx, cancel = context.WithCancel(context.Background()) - defer cancel() - go func() { - time.Sleep(time.Millisecond * 500) - cancel() - }() - wfr := NewWaitForReady( - "blub", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return fakeWatchApi, nil - }, - func(obj runtime.Object) (apis.Conditions, error) { - return apis.Conditions(obj.(*servingv1.Service).Status.Conditions), nil - }) - window := 2 * time.Second - err, _ = wfr.Wait(ctx, "foobar", "", Options{Timeout: nil, ErrorWindow: &window}, NoopMessageCallback()) - assert.Assert(t, errors.Is(err, context.Canceled)) -} - -func TestAddWaitForReady(t *testing.T) { - - for _, tc := range prepareTestCases(t, "test-service") { - tc := tc - t.Run(tc.testcase, func(t *testing.T) { - - fakeWatchApi := NewFakeWatch(tc.events) - waitForReady := NewWaitForReady( - "blub", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return fakeWatchApi, nil - }, - conditionsFor) - fakeWatchApi.Start() - msgs := make([]string, 0) - err, _ := waitForReady.Wait(context.Background(), "foobar", "", Options{Timeout: &tc.timeout}, func(_ time.Duration, msg string) { - msgs = append(msgs, msg) - }) - close(fakeWatchApi.eventChan) - - if tc.errorText == "" && err != nil { - t.Errorf("Error received %v", err) - return - } - if tc.errorText != "" { - if err == nil { - t.Error("No error but expected one") - } else { - assert.ErrorContains(t, err, tc.errorText) - } - } - - // check messages - assert.Assert(t, cmp.DeepEqual(tc.messagesExpected, msgs), "Messages expected to be equal") - - if fakeWatchApi.StopCalled != 1 { - t.Errorf("Exactly one 'stop' should be called, but got %d", fakeWatchApi.StopCalled) - } - - }) - } -} - -func TestAddWaitForReadyWithChannelClose(t *testing.T) { - for _, tc := range prepareTestCases(t, "test-service") { - tc := tc - t.Run(tc.testcase, func(t *testing.T) { - - fakeWatchApi := NewFakeWatch(tc.events) - counter := 0 - waitForReady := NewWaitForReady( - "blub", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - if counter == 0 { - close(fakeWatchApi.eventChan) - counter++ - return fakeWatchApi, nil - } - fakeWatchApi.eventChan = make(chan watch.Event) - fakeWatchApi.Start() - return fakeWatchApi, nil - }, - conditionsFor) - msgs := make([]string, 0) - - err, _ := waitForReady.Wait(context.Background(), "foobar", "", Options{Timeout: &tc.timeout}, func(_ time.Duration, msg string) { - msgs = append(msgs, msg) - }) - close(fakeWatchApi.eventChan) - - if tc.errorText == "" && err != nil { - t.Errorf("Error received %v", err) - return - } - if tc.errorText != "" { - if err == nil { - t.Error("No error but expected one") - } else { - assert.ErrorContains(t, err, tc.errorText) - } - } - - // check messages - assert.Assert(t, cmp.DeepEqual(tc.messagesExpected, msgs), "Messages expected to be equal") - - if fakeWatchApi.StopCalled != 2 { - t.Errorf("Exactly one 'stop' should be called, but got %d", fakeWatchApi.StopCalled) - } - - }) - } -} - -func TestWaitTimeout(t *testing.T) { - fakeWatchApi := NewFakeWatch([]watch.Event{}) - timeout := time.Second * 3 - wfe := NewWaitForEvent("foobar", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return fakeWatchApi, nil - }, - func(e *watch.Event) bool { - return false - }) - - err, _ := wfe.Wait(context.Background(), "foobar", "", Options{Timeout: &timeout}, NoopMessageCallback()) - assert.ErrorContains(t, err, "not ready") - assert.Assert(t, fakeWatchApi.StopCalled == 1) - - fakeWatchApi = NewFakeWatch([]watch.Event{}) - wfr := NewWaitForReady( - "blub", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return fakeWatchApi, nil - }, - conditionsFor) - err, _ = wfr.Wait(context.Background(), "foobar", "", Options{Timeout: &timeout}, NoopMessageCallback()) - assert.ErrorContains(t, err, "not ready") - assert.Assert(t, fakeWatchApi.StopCalled == 1) -} - -func TestWaitWatchError(t *testing.T) { - timeout := time.Second * 3 - wfe := NewWaitForEvent("foobar", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return nil, fmt.Errorf("error creating watcher") - }, - func(e *watch.Event) bool { - return false - }) - - err, _ := wfe.Wait(context.Background(), "foobar", "", Options{Timeout: &timeout}, NoopMessageCallback()) - assert.ErrorContains(t, err, "error creating watcher") - - wfr := NewWaitForReady( - "blub", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return nil, fmt.Errorf("error creating watcher") - }, - func(obj runtime.Object) (apis.Conditions, error) { - return apis.Conditions(obj.(*servingv1.Service).Status.Conditions), nil - }) - err, _ = wfr.Wait(context.Background(), "foobar", "", Options{Timeout: &timeout}, NoopMessageCallback()) - assert.ErrorContains(t, err, "error creating watcher") -} - -func TestAddWaitForDelete(t *testing.T) { - for _, tc := range prepareDeleteTestCases("test-service") { - tc := tc - t.Run(tc.testcase, func(t *testing.T) { - - fakeWatchAPI := NewFakeWatch(tc.events) - - waitForEvent := NewWaitForEvent( - "blub", - func(ctx context.Context, name string, initialVersion string, timeout time.Duration) (watch.Interface, error) { - return fakeWatchAPI, nil - }, - func(evt *watch.Event) bool { return evt.Type == watch.Deleted }) - fakeWatchAPI.Start() - - err, _ := waitForEvent.Wait(context.Background(), "foobar", "", Options{Timeout: &tc.timeout}, NoopMessageCallback()) - close(fakeWatchAPI.eventChan) - - if tc.errorText == "" && err != nil { - t.Errorf("Error received %v", err) - return - } - if tc.errorText != "" { - if err == nil { - t.Error("No error but expected one") - } else { - assert.ErrorContains(t, err, tc.errorText) - } - } - - if fakeWatchAPI.StopCalled != 1 { - t.Errorf("Exactly one 'stop' should be called, but got %d", fakeWatchAPI.StopCalled) - } - - }) - } -} - -func TestSimpleMessageCallback(t *testing.T) { - var out bytes.Buffer - callback := SimpleMessageCallback(&out) - callback(5*time.Second, "hello") - assert.Assert(t, util.ContainsAll(out.String(), "hello")) - callback(5*time.Second, "hello") - assert.Assert(t, util.ContainsAll(out.String(), "...")) -} - -// Test cases which consists of a series of events to send and the expected behaviour. -func prepareTestCases(tb testing.TB, name string) []waitForReadyTestCase { - return []waitForReadyTestCase{ - errorTest(name), - tc("peNormal", peNormal, name, 5*time.Second, ""), - tc("peUnstructured", peUnstructured(tb), name, 5*time.Second, - ""), - tc("peWrongGeneration", peWrongGeneration, name, 5*time.Second, - "timeout"), - tc("peMissingGeneration", peMissingGeneration(tb), name, 5*time.Second, - "no field 'generation' in metadata"), - tc("peTimeout", peTimeout, name, 5*time.Second, "timeout"), - tc("peReadyFalseWithinErrorWindow", peReadyFalseWithinErrorWindow, - name, 5*time.Second, ""), - } -} - -func prepareDeleteTestCases(name string) []waitForReadyTestCase { - return []waitForReadyTestCase{ - tc("deNormal", deNormal, name, time.Second, ""), - tc("peTimeout", peTimeout, name, 10*time.Second, "timeout"), - } -} - -func errorTest(name string) waitForReadyTestCase { - events := []watch.Event{ - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")}, - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionFalse, corev1.ConditionTrue, "FakeError", "Test Error")}, - } - - return waitForReadyTestCase{ - testcase: "errorTest", - events: events, - timeout: 5 * time.Second, - errorText: "FakeError", - messagesExpected: []string{"msg1", "Test Error"}, - } -} - -func tc(testcase string, f func(name string) (evts []watch.Event, nrMessages int), name string, timeout time.Duration, errorTxt string) waitForReadyTestCase { - events, nrMsgs := f(name) - return waitForReadyTestCase{ - testcase, - events, - timeout, - errorTxt, - pMessages(nrMsgs), - } -} - -func pMessages(max int) []string { - return []string{ - "msg1", "msg2", "msg3", "msg4", "msg5", "msg6", - }[:max] -} - -// ============================================================================= - -func peNormal(name string) ([]watch.Event, int) { - messages := pMessages(2) - return []watch.Event{ - {Type: watch.Added, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0], 1, 2)}, - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0], 2, 2)}, - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", messages[1], 2, 2)}, - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "", 2, 2)}, - }, len(messages) -} - -func peUnstructured(tb testing.TB) func(name string) ([]watch.Event, int) { - return func(name string) ([]watch.Event, int) { - events, msgLen := peNormal(name) - for i, event := range events { - unC, err := runtime.DefaultUnstructuredConverter.ToUnstructured(event.Object) - if err != nil { - tb.Fatal(err) - } - if event.Type == watch.Added { - delete(unC, "status") - } - un := unstructured.Unstructured{Object: unC} - events[i] = watch.Event{ - Type: event.Type, - Object: &un, - } - } - return events, msgLen - } -} - -func peTimeout(name string) ([]watch.Event, int) { - messages := pMessages(1) - return []watch.Event{ - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])}, - }, len(messages) -} - -func peWrongGeneration(name string) ([]watch.Event, int) { - messages := pMessages(1) - return []watch.Event{ - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])}, - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "", 1, 2)}, - }, len(messages) -} - -func peMissingGeneration(tb testing.TB) func(name string) ([]watch.Event, int) { - return func(name string) ([]watch.Event, int) { - svc := CreateTestServiceWithConditions(name, - corev1.ConditionUnknown, corev1.ConditionUnknown, - "", "") - unC, err := runtime.DefaultUnstructuredConverter.ToUnstructured(svc) - if err != nil { - tb.Fatal(err) - } - metadata, ok := unC["metadata"].(map[string]interface{}) - assert.Check(tb, ok) - delete(metadata, "generation") - un := unstructured.Unstructured{Object: unC} - return []watch.Event{ - {Type: watch.Modified, Object: &un}, - }, 0 - } -} - -func peReadyFalseWithinErrorWindow(name string) ([]watch.Event, int) { - messages := pMessages(1) - return []watch.Event{ - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionFalse, corev1.ConditionFalse, "Route not ready", messages[0])}, - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "Route ready", "")}, - }, len(messages) -} - -func deNormal(name string) ([]watch.Event, int) { - messages := pMessages(2) - return []watch.Event{ - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])}, - {Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", messages[1])}, - {Type: watch.Deleted, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")}, - }, len(messages) -} - -func conditionsFor(obj runtime.Object) (apis.Conditions, error) { - if un, ok := obj.(*unstructured.Unstructured); ok { - kresource := duckv1.KResource{} - err := runtime.DefaultUnstructuredConverter. - FromUnstructured(un.UnstructuredContent(), &kresource) - if err != nil { - return nil, err - } - return kresource.GetStatus().GetConditions(), nil - } - return apis.Conditions(obj.(duckv1.KRShaped).GetStatus().Conditions), nil -} diff --git a/test/common.sh b/test/common.sh index e2d7960386..cb824b598f 100755 --- a/test/common.sh +++ b/test/common.sh @@ -14,7 +14,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -source $(dirname $0)/../vendor/knative.dev/hack/e2e-tests.sh +# shellcheck disable=SC1090 +source "$(go run knative.dev/hack/cmd/script e2e-tests.sh)" export INGRESS_CLASS=${INGRESS_CLASS:-istio.ingress.networking.knative.dev} diff --git a/test/e2e/basic_workflow_test.go b/test/e2e/basic_workflow_test.go index 199b285624..87a1b5a5c1 100644 --- a/test/e2e/basic_workflow_test.go +++ b/test/e2e/basic_workflow_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestBasicWorkflow(t *testing.T) { diff --git a/test/e2e/broker_test.go b/test/e2e/broker_test.go index 461dfad848..85b4ed0dbf 100644 --- a/test/e2e/broker_test.go +++ b/test/e2e/broker_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestBroker(t *testing.T) { diff --git a/test/e2e/channels_test.go b/test/e2e/channels_test.go index b3ad947b1f..bc002da9cf 100644 --- a/test/e2e/channels_test.go +++ b/test/e2e/channels_test.go @@ -21,8 +21,8 @@ import ( "testing" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) const ( diff --git a/test/e2e/domain_mapping_test.go b/test/e2e/domain_mapping_test.go index e6f9f0ef87..73e5cfa1cd 100644 --- a/test/e2e/domain_mapping_test.go +++ b/test/e2e/domain_mapping_test.go @@ -32,11 +32,11 @@ import ( "testing" "time" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" ) func TestDomain(t *testing.T) { diff --git a/test/e2e/eventtype_test.go b/test/e2e/eventtype_test.go index 9172391067..cc8c079322 100644 --- a/test/e2e/eventtype_test.go +++ b/test/e2e/eventtype_test.go @@ -21,8 +21,8 @@ import ( "testing" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) const ( diff --git a/test/e2e/extra_containers_test.go b/test/e2e/extra_containers_test.go index 4d09ddfad8..464f92e9e4 100644 --- a/test/e2e/extra_containers_test.go +++ b/test/e2e/extra_containers_test.go @@ -26,12 +26,12 @@ import ( "strings" "testing" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" pkgtest "knative.dev/pkg/test" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" ) func TestMultiContainers(t *testing.T) { diff --git a/test/e2e/ping_test.go b/test/e2e/ping_test.go index 80fa0b4202..bf168a8ec1 100644 --- a/test/e2e/ping_test.go +++ b/test/e2e/ping_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestSourcePing(t *testing.T) { diff --git a/test/e2e/plugins_test.go b/test/e2e/plugins_test.go index f4404d75e6..9048b3f0de 100644 --- a/test/e2e/plugins_test.go +++ b/test/e2e/plugins_test.go @@ -26,8 +26,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) const ( diff --git a/test/e2e/revision_test.go b/test/e2e/revision_test.go index fd9fb9a340..3c06b5c087 100644 --- a/test/e2e/revision_test.go +++ b/test/e2e/revision_test.go @@ -22,7 +22,7 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" ) func TestRevision(t *testing.T) { diff --git a/test/e2e/route_test.go b/test/e2e/route_test.go index 8880f9582b..bcc3b5167e 100644 --- a/test/e2e/route_test.go +++ b/test/e2e/route_test.go @@ -24,8 +24,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestRoute(t *testing.T) { diff --git a/test/e2e/service_apply_test.go b/test/e2e/service_apply_test.go index 64c9ca4e36..077764b028 100644 --- a/test/e2e/service_apply_test.go +++ b/test/e2e/service_apply_test.go @@ -24,8 +24,8 @@ import ( pkgtest "knative.dev/pkg/test" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestServiceApply(t *testing.T) { diff --git a/test/e2e/service_export_test.go b/test/e2e/service_export_test.go index f787329f0d..0371e130c2 100644 --- a/test/e2e/service_export_test.go +++ b/test/e2e/service_export_test.go @@ -26,10 +26,10 @@ import ( "sigs.k8s.io/yaml" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" corev1 "k8s.io/api/core/v1" - clientv1alpha1 "knative.dev/client/pkg/apis/client/v1alpha1" + clientv1alpha1 "knative.dev/client-pkg/pkg/apis/client/v1alpha1" pkgtest "knative.dev/pkg/test" servingv1 "knative.dev/serving/pkg/apis/serving/v1" servingtest "knative.dev/serving/pkg/testing/v1" diff --git a/test/e2e/service_file_test.go b/test/e2e/service_file_test.go index 266c84b29c..0115dd6558 100644 --- a/test/e2e/service_file_test.go +++ b/test/e2e/service_file_test.go @@ -26,8 +26,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" pkgtest "knative.dev/pkg/test" ) diff --git a/test/e2e/service_import_test.go b/test/e2e/service_import_test.go index 9bbf343c0a..7db9015b88 100644 --- a/test/e2e/service_import_test.go +++ b/test/e2e/service_import_test.go @@ -23,8 +23,8 @@ import ( "testing" "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestServiceImport(t *testing.T) { diff --git a/test/e2e/service_options_test.go b/test/e2e/service_options_test.go index ce1962c499..1052fc1ce1 100644 --- a/test/e2e/service_options_test.go +++ b/test/e2e/service_options_test.go @@ -30,8 +30,8 @@ import ( "gotest.tools/v3/assert" corev1 "k8s.io/api/core/v1" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" pkgtest "knative.dev/pkg/test" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/test/e2e/service_test.go b/test/e2e/service_test.go index 62e3c402c0..0d17712b87 100644 --- a/test/e2e/service_test.go +++ b/test/e2e/service_test.go @@ -26,8 +26,8 @@ import ( "gotest.tools/v3/assert" v1 "k8s.io/api/core/v1" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" network "knative.dev/networking/pkg/apis/networking" pkgtest "knative.dev/pkg/test" "knative.dev/serving/pkg/apis/serving" diff --git a/test/e2e/sink_test.go b/test/e2e/sink_test.go index 118a7f8196..4c9cedc35b 100644 --- a/test/e2e/sink_test.go +++ b/test/e2e/sink_test.go @@ -22,7 +22,7 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" ) func TestSink(t *testing.T) { diff --git a/test/e2e/sinkprefix_test.go b/test/e2e/sinkprefix_test.go index bfaa55feac..63c9edfd08 100644 --- a/test/e2e/sinkprefix_test.go +++ b/test/e2e/sinkprefix_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) const ( diff --git a/test/e2e/source_apiserver_test.go b/test/e2e/source_apiserver_test.go index d7db394163..ed513076f9 100644 --- a/test/e2e/source_apiserver_test.go +++ b/test/e2e/source_apiserver_test.go @@ -24,8 +24,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) const ( diff --git a/test/e2e/source_binding_test.go b/test/e2e/source_binding_test.go index c41894607c..4e6339a44a 100644 --- a/test/e2e/source_binding_test.go +++ b/test/e2e/source_binding_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestSourceBinding(t *testing.T) { diff --git a/test/e2e/source_container_test.go b/test/e2e/source_container_test.go index 973d417472..6064236ef3 100644 --- a/test/e2e/source_container_test.go +++ b/test/e2e/source_container_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" pkgtest "knative.dev/pkg/test" ) diff --git a/test/e2e/source_list_crd_test.go b/test/e2e/source_list_crd_test.go index 988a815827..9151c0ad6f 100644 --- a/test/e2e/source_list_crd_test.go +++ b/test/e2e/source_list_crd_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) // This test requires cluster admin permissions due to working with CustomResourceDefinitions. diff --git a/test/e2e/source_list_test.go b/test/e2e/source_list_test.go index d5660cc595..ebb9c27a44 100644 --- a/test/e2e/source_list_test.go +++ b/test/e2e/source_list_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestSourceListTypes(t *testing.T) { diff --git a/test/e2e/subscription_test.go b/test/e2e/subscription_test.go index 3242563145..26116ec70c 100644 --- a/test/e2e/subscription_test.go +++ b/test/e2e/subscription_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestSubscriptions(t *testing.T) { diff --git a/test/e2e/tekton_test.go b/test/e2e/tekton_test.go index 4d375e956d..695ea68c1c 100644 --- a/test/e2e/tekton_test.go +++ b/test/e2e/tekton_test.go @@ -27,8 +27,8 @@ import ( "gotest.tools/v3/assert" "k8s.io/apimachinery/pkg/util/wait" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) const ( diff --git a/test/e2e/traffic_split_test.go b/test/e2e/traffic_split_test.go index 46d0204fcd..13522cff30 100644 --- a/test/e2e/traffic_split_test.go +++ b/test/e2e/traffic_split_test.go @@ -25,7 +25,7 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" + "knative.dev/client-pkg/pkg/util/test" ) var targetsSeparator = "|" diff --git a/test/e2e/trigger_test.go b/test/e2e/trigger_test.go index df037117ea..a1d8968d84 100644 --- a/test/e2e/trigger_test.go +++ b/test/e2e/trigger_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestBrokerTrigger(t *testing.T) { diff --git a/test/e2e/version_test.go b/test/e2e/version_test.go index cd83696569..8edb612268 100644 --- a/test/e2e/version_test.go +++ b/test/e2e/version_test.go @@ -22,8 +22,8 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/lib/test" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/util/test" ) func TestVersion(t *testing.T) { diff --git a/test/local-e2e-tests.sh b/test/local-e2e-tests.sh index 8f1f7fd255..65d8e79de3 100755 --- a/test/local-e2e-tests.sh +++ b/test/local-e2e-tests.sh @@ -24,4 +24,4 @@ base=$(cd "$dir/.." && pwd) export KN_E2E_NAMESPACE=kne2etests echo "🧪 Testing" -go test -mod=vendor ${base}/test/e2e/ -test.v -tags "e2e ${E2E_TAGS}" "$@" +go test ${base}/test/e2e/ -test.v -tags "e2e ${E2E_TAGS}" "$@" diff --git a/test/presubmit-tests.sh b/test/presubmit-tests.sh index 0ab1ffe86b..6ba788cb77 100755 --- a/test/presubmit-tests.sh +++ b/test/presubmit-tests.sh @@ -36,8 +36,10 @@ export PRESUBMIT_TEST_FAIL_FAST=1 export GO111MODULE=on export KNATIVE_SERVING_VERSION=${KNATIVE_SERVING_VERSION:-latest} export KNATIVE_EVENTING_VERSION=${KNATIVE_EVENTING_VERSION:-latest} -source $(dirname $0)/../vendor/knative.dev/hack/presubmit-tests.sh -source $(dirname $0)/common.sh + +# shellcheck disable=SC1090 +source "$(go run knative.dev/hack/cmd/script presubmit-tests.sh)" +source "$(dirname "$0")/common.sh" # Run cross platform build to ensure kn compiles for Linux, macOS and Windows function post_build_tests() { @@ -50,11 +52,10 @@ function post_build_tests() { fi } -# Run the unit tests with an additional flag '-mod=vendor' to avoid -# downloading the deps in unit tests CI job +# Run the unit tests function unit_tests() { - report_go_test -race -mod=vendor ./... || failed=1 + report_go_test -race ./... || failed=1 } # We use the default build and integration test runners. -main $@ +main "$@" diff --git a/test/upload-test-images.sh b/test/upload-test-images.sh index 7a98422e7e..16d22ffabd 100755 --- a/test/upload-test-images.sh +++ b/test/upload-test-images.sh @@ -22,7 +22,7 @@ function upload_test_images() { # to pickup .ko.yaml cd "$( dirname "$0")/.." local image_dir="test/test_images" - local vendor_image_dir="vendor/knative.dev/serving/test/test_images" + local serving_image_dir="knative.dev/serving/test/test_images" local docker_tag=$1 local tag_option="" if [ -n "${docker_tag}" ]; then @@ -42,8 +42,8 @@ function upload_test_images() { # We limit the number of concurrent builds (jobs) to avoid OOMs. ko resolve --jobs=4 ${platform} ${tag_option} -RBf "${image_dir}" > /dev/null - #build and publish images from vendor directory - ko resolve --jobs=4 ${platform} ${tag_option} -RBf "${vendor_image_dir}" > /dev/null + #build and publish images from serving + ko resolve --jobs=4 ${platform} ${tag_option} -RBf "${serving_image_dir}" > /dev/null } : ${KO_DOCKER_REPO:?"You must set 'KO_DOCKER_REPO'"} diff --git a/tools/knb/pkg/plugin/distro.go b/tools/knb/pkg/plugin/distro.go index 55fe244899..83ef00176b 100644 --- a/tools/knb/pkg/plugin/distro.go +++ b/tools/knb/pkg/plugin/distro.go @@ -80,7 +80,7 @@ func NewDistroGenerateCmd() *cobra.Command { return fmt.Errorf("update-deps.sh failed failed: %w", err) } } else { - fmt.Println("⚠️ hack/update-dep.sh script doesn't exist, make sure to update vendor/ dir") + fmt.Println("⚠️ hack/update-dep.sh script doesn't exist, make sure to update code") } return nil }, diff --git a/tools/knb/pkg/plugin/templates.go b/tools/knb/pkg/plugin/templates.go index c5a42af943..f8ef8068a1 100644 --- a/tools/knb/pkg/plugin/templates.go +++ b/tools/knb/pkg/plugin/templates.go @@ -53,7 +53,7 @@ import ( {{if .PluginImportPath}}"{{.PluginImportPath }}"{{else}}//TODO: add plugin import{{end}} - "knative.dev/client/pkg/kn/plugin" + "knative.dev/client/pkg/plugin" ) func init() { diff --git a/pkg/apis/client/register.go b/vendor/knative.dev/client-pkg/pkg/apis/client/register.go similarity index 100% rename from pkg/apis/client/register.go rename to vendor/knative.dev/client-pkg/pkg/apis/client/register.go diff --git a/pkg/apis/client/v1alpha1/doc.go b/vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/doc.go similarity index 89% rename from pkg/apis/client/v1alpha1/doc.go rename to vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/doc.go index 967f24dc42..f81c13dbad 100644 --- a/pkg/apis/client/v1alpha1/doc.go +++ b/vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/doc.go @@ -18,4 +18,4 @@ limitations under the License. // +groupName=client.knative.dev // Package v1alpha1 is the v1alpha1 version of the API. -package v1alpha1 // import "knative.dev/client/pkg/apis/client/serving/v1alpha1" +package v1alpha1 // import "knative.dev/client-pkg/pkg/apis/client/v1alpha1" diff --git a/pkg/apis/client/v1alpha1/export_types.go b/vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/export_types.go similarity index 100% rename from pkg/apis/client/v1alpha1/export_types.go rename to vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/export_types.go diff --git a/pkg/apis/client/v1alpha1/register.go b/vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/register.go similarity index 97% rename from pkg/apis/client/v1alpha1/register.go rename to vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/register.go index a05b3398ec..19ff9232a0 100644 --- a/pkg/apis/client/v1alpha1/register.go +++ b/vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/register.go @@ -21,7 +21,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/client/pkg/apis/client" + "knative.dev/client-pkg/pkg/apis/client" ) // SchemeGroupVersion is group version used to register these objects diff --git a/pkg/apis/client/v1alpha1/zz_generated.deepcopy.go b/vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/zz_generated.deepcopy.go similarity index 100% rename from pkg/apis/client/v1alpha1/zz_generated.deepcopy.go rename to vendor/knative.dev/client-pkg/pkg/apis/client/v1alpha1/zz_generated.deepcopy.go diff --git a/vendor/knative.dev/client-pkg/pkg/commands/completion_helper.go b/vendor/knative.dev/client-pkg/pkg/commands/completion_helper.go new file mode 100644 index 0000000000..398ff24202 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/completion_helper.go @@ -0,0 +1,458 @@ +// Copyright © 2021 The Knative 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 commands + +import ( + "strings" + + "github.com/spf13/cobra" +) + +type completionConfig struct { + params *KnParams + command *cobra.Command + args []string + toComplete string +} + +var ( + resourceToFuncMap = map[string]func(config *completionConfig) []string{ + "apiserver": completeApiserverSource, + "binding": completeBindingSource, + "broker": completeBroker, + "channel": completeChannel, + "container": completeContainerSource, + "domain": completeDomain, + "ping": completePingSource, + "revision": completeRevision, + "route": completeRoute, + "service": completeService, + "subscription": completeSubscription, + "trigger": completeTrigger, + "eventtype": completeEventtype, + } +) + +// ResourceNameCompletionFunc will return a function that will autocomplete the name of +// the resource based on the subcommand +func ResourceNameCompletionFunc(p *KnParams) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + + var use string + if cmd.Parent() != nil { + use = cmd.Parent().Name() + } + config := completionConfig{ + p, + cmd, + args, + toComplete, + } + return config.getCompletion(use), cobra.ShellCompDirectiveNoFileComp + } +} + +func (config *completionConfig) getCompletion(parent string) []string { + completionFunc := resourceToFuncMap[parent] + if completionFunc == nil { + return []string{} + } + return completionFunc(config) +} + +func getTargetFlagValue(cmd *cobra.Command) string { + flag := cmd.Flag("target") + if flag == nil { + return "" + } + return flag.Value.String() +} + +func completeGitOps(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewGitopsServingClient(namespace, getTargetFlagValue(config.command)) + if err != nil { + return + } + serviceList, err := client.ListServices(config.command.Context()) + if err != nil { + return + } + for _, sug := range serviceList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeService(config *completionConfig) (suggestions []string) { + if getTargetFlagValue(config.command) != "" { + return completeGitOps(config) + } + + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewServingClient(namespace) + if err != nil { + return + } + serviceList, err := client.ListServices(config.command.Context()) + if err != nil { + return + } + for _, sug := range serviceList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeBroker(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewEventingClient(namespace) + if err != nil { + return + } + brokerList, err := client.ListBrokers(config.command.Context()) + if err != nil { + return + } + for _, sug := range brokerList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeRevision(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewServingClient(namespace) + if err != nil { + return + } + revisionList, err := client.ListRevisions(config.command.Context()) + if err != nil { + return + } + for _, sug := range revisionList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeRoute(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewServingClient(namespace) + if err != nil { + return + } + routeList, err := client.ListRoutes(config.command.Context()) + if err != nil { + return + } + for _, sug := range routeList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeDomain(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewServingV1beta1Client(namespace) + if err != nil { + return + } + domainMappingList, err := client.ListDomainMappings(config.command.Context()) + if err != nil { + return + } + for _, sug := range domainMappingList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeTrigger(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewEventingClient(namespace) + if err != nil { + return + } + triggerList, err := client.ListTriggers(config.command.Context()) + if err != nil { + return + } + for _, sug := range triggerList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeContainerSource(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewSourcesClient(namespace) + if err != nil { + return + } + containerSourceList, err := client.ContainerSourcesClient().ListContainerSources(config.command.Context()) + if err != nil { + return + } + for _, sug := range containerSourceList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeApiserverSource(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewSourcesClient(namespace) + if err != nil { + return + } + apiServerSourceList, err := client.APIServerSourcesClient().ListAPIServerSource(config.command.Context()) + if err != nil { + return + } + for _, sug := range apiServerSourceList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeBindingSource(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + client, err := config.params.NewSourcesClient(namespace) + if err != nil { + return + } + bindingList, err := client.SinkBindingClient().ListSinkBindings(config.command.Context()) + if err != nil { + return + } + for _, sug := range bindingList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completePingSource(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + + client, err := config.params.NewSourcesV1beta2Client(namespace) + if err != nil { + return + } + pingSourcesClient := client.PingSourcesClient() + + pingSourceList, err := pingSourcesClient.ListPingSource(config.command.Context()) + if err != nil { + return + } + for _, sug := range pingSourceList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeChannel(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + + client, err := config.params.NewMessagingClient(namespace) + if err != nil { + return + } + + channelList, err := client.ChannelsClient().ListChannel(config.command.Context()) + if err != nil { + return + } + for _, sug := range channelList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeSubscription(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + + client, err := config.params.NewMessagingClient(namespace) + if err != nil { + return + } + + subscriptionList, err := client.SubscriptionsClient().ListSubscription(config.command.Context()) + if err != nil { + return + } + for _, sug := range subscriptionList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} + +func completeEventtype(config *completionConfig) (suggestions []string) { + suggestions = make([]string, 0) + if len(config.args) != 0 { + return + } + namespace, err := config.params.GetNamespace(config.command) + if err != nil { + return + } + + client, err := config.params.NewEventingV1beta2Client(namespace) + if err != nil { + return + } + + eventTypeList, err := client.ListEventtypes(config.command.Context()) + if err != nil { + return + } + for _, sug := range eventTypeList.Items { + if !strings.HasPrefix(sug.Name, config.toComplete) { + continue + } + suggestions = append(suggestions, sug.Name) + } + return +} diff --git a/vendor/knative.dev/client-pkg/pkg/commands/describe.go b/vendor/knative.dev/client-pkg/pkg/commands/describe.go new file mode 100644 index 0000000000..89bfdeaf2c --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/describe.go @@ -0,0 +1,222 @@ +// Copyright © 2019 The Knative 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 commands + +import ( + "fmt" + "sort" + "strconv" + "strings" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/duration" + "knative.dev/client-pkg/pkg/printers" + "knative.dev/pkg/apis" +) + +// Max length When to truncate long strings (when not "all" mode switched on) +const TruncateAt = 100 + +func WriteMetadata(dw printers.PrefixWriter, m *metav1.ObjectMeta, printDetails bool) { + dw.WriteAttribute("Name", m.Name) + dw.WriteAttribute("Namespace", m.Namespace) + WriteMapDesc(dw, m.Labels, "Labels", printDetails) + WriteMapDesc(dw, m.Annotations, "Annotations", printDetails) + dw.WriteAttribute("Age", Age(m.CreationTimestamp.Time)) +} + +var boringDomains = map[string]bool{ + "serving.knative.dev": true, + "client.knative.dev": true, + "kubectl.kubernetes.io": true, +} + +func keyIsBoring(k string) bool { + parts := strings.Split(k, "/") + return len(parts) > 1 && boringDomains[parts[0]] +} + +// Write a map either compact in a single line (possibly truncated) or, if printDetails is set, +// over multiple line, one line per key-value pair. The output is sorted by keys. +func WriteMapDesc(dw printers.PrefixWriter, m map[string]string, label string, details bool) { + if len(m) == 0 { + return + } + + var keys []string + for k := range m { + if details || !keyIsBoring(k) { + keys = append(keys, k) + } + } + if len(keys) == 0 { + return + } + sort.Strings(keys) + + if details { + for i, key := range keys { + l := "" + if i == 0 { + l = printers.Label(label) + } + dw.WriteColsLn(l, key+"="+m[key]) + } + return + } + + dw.WriteColsLn(printers.Label(label), joinAndTruncate(keys, m, TruncateAt-len(label)-2)) +} + +func Age(t time.Time) string { + if t.IsZero() { + return "" + } + return duration.ShortHumanDuration(time.Since(t)) +} + +func formatConditionType(condition apis.Condition) string { + return string(condition.Type) +} + +// Status in ASCII format +func formatStatus(c apis.Condition) string { + switch c.Status { + case corev1.ConditionTrue: + return "++" + case corev1.ConditionFalse: + switch c.Severity { + case apis.ConditionSeverityError: + return "!!" + case apis.ConditionSeverityWarning: + return " W" + case apis.ConditionSeverityInfo: + return " I" + default: + return " !" + } + default: + return "??" + } +} + +// Used for conditions table to do own formatting for the table, +// as the tabbed writer doesn't work nicely with colors +func getMaxTypeLen(conditions []apis.Condition) int { + max := 0 + for _, condition := range conditions { + if len(condition.Type) > max { + max = len(condition.Type) + } + } + return max +} + +// Sort conditions: Ready first, followed by error, then Warning, then Info +func sortConditions(conditions []apis.Condition) []apis.Condition { + // Don't change the orig slice + ret := make([]apis.Condition, len(conditions)) + copy(ret, conditions) + sort.SliceStable(ret, func(i, j int) bool { + ic := &ret[i] + jc := &ret[j] + // Ready first + if ic.Type == apis.ConditionReady { + return jc.Type != apis.ConditionReady + } + if jc.Type == apis.ConditionReady { + return false + } + // Among conditions of the same Severity, sort by Type + if ic.Severity == jc.Severity { + return ic.Type < jc.Type + } + // Error < Warning < Info + switch ic.Severity { + case apis.ConditionSeverityError: + return true + case apis.ConditionSeverityWarning: + return jc.Severity == apis.ConditionSeverityInfo + case apis.ConditionSeverityInfo: + return false + default: + return false + } + }) + return ret +} + +// Print out a table with conditions. +func WriteConditions(dw printers.PrefixWriter, conditions []apis.Condition, printMessage bool) { + section := dw.WriteAttribute("Conditions", "") + conditions = sortConditions(conditions) + maxLen := getMaxTypeLen(conditions) + formatHeader := "%-2s %-" + strconv.Itoa(maxLen) + "s %6s %-s\n" + formatRow := "%-2s %-" + strconv.Itoa(maxLen) + "s %6s %-s\n" + section.Writef(formatHeader, "OK", "TYPE", "AGE", "REASON") + for _, condition := range conditions { + ok := formatStatus(condition) + reason := condition.Reason + if printMessage && reason != "" { + reason = fmt.Sprintf("%s (%s)", reason, condition.Message) + } + section.Writef(formatRow, ok, formatConditionType(condition), Age(condition.LastTransitionTime.Inner.Time), reason) + } +} + +// Writer a slice compact (printDetails == false) in one line, or over multiple line +// with key-value line-by-line (printDetails == true) +func WriteSliceDesc(dw printers.PrefixWriter, s []string, label string, printDetails bool) { + + if len(s) == 0 { + return + } + + if printDetails { + for i, value := range s { + if i == 0 { + dw.WriteColsLn(printers.Label(label), value) + } else { + dw.WriteColsLn("", value) + } + } + return + } + + joined := strings.Join(s, ", ") + if len(joined) > TruncateAt { + joined = joined[:TruncateAt-4] + " ..." + } + dw.WriteAttribute(label, joined) +} + +// Join to key=value pair, comma separated, and truncate if longer than a limit +func joinAndTruncate(sortedKeys []string, m map[string]string, width int) string { + ret := "" + for _, key := range sortedKeys { + ret += fmt.Sprintf("%s=%s, ", key, m[key]) + if len(ret) > width { + break + } + } + // cut of two latest chars + ret = strings.TrimRight(ret, ", ") + if len(ret) <= width { + return ret + } + return ret[:width-4] + " ..." +} diff --git a/vendor/knative.dev/client-pkg/pkg/commands/flags/list/print.go b/vendor/knative.dev/client-pkg/pkg/commands/flags/list/print.go new file mode 100644 index 0000000000..6f59b26a1c --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/flags/list/print.go @@ -0,0 +1,103 @@ +/* + Copyright 2024 The Knative 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 list + +import ( + "io" + + "github.com/spf13/cobra" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/cli-runtime/pkg/genericclioptions" + "knative.dev/client-pkg/pkg/commands" + + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/client-pkg/pkg/util" +) + +// PrintFlags composes common printer flag structs used in the list command. +type PrintFlags struct { + GenericPrintFlags *genericclioptions.PrintFlags + HumanReadableFlags *commands.HumanPrintFlags + PrinterHandler func(h hprinters.PrintHandler) +} + +// AllowedFormats is the list of formats in which data can be displayed +func (f *PrintFlags) AllowedFormats() []string { + formats := f.GenericPrintFlags.AllowedFormats() + formats = append(formats, f.HumanReadableFlags.AllowedFormats()...) + return formats +} + +// ToPrinter attempts to find a composed set of ListTypesFlags suitable for +// returning a printer based on current flag values. +func (f *PrintFlags) ToPrinter() (hprinters.ResourcePrinter, error) { + // if there are flags specified for generic printing + if f.GenericPrintFlags.OutputFlagSpecified() { + p, err := f.GenericPrintFlags.ToPrinter() + if err != nil { + return nil, err + } + return p, nil + } + + p, err := f.HumanReadableFlags.ToPrinter(f.PrinterHandler) + if err != nil { + return nil, err + } + return p, nil +} + +// Print is to print an Object to a Writer +func (f *PrintFlags) Print(obj runtime.Object, w io.Writer) error { + printer, err := f.ToPrinter() + if err != nil { + return err + } + + if f.GenericPrintFlags.OutputFlagSpecified() { + unstructuredList, err := util.ToUnstructuredList(obj) + if err != nil { + return err + } + return printer.PrintObj(unstructuredList, w) + } + + return printer.PrintObj(obj, w) +} + +// AddFlags receives a *cobra.Command reference and binds +// flags related to humanreadable and template printing. +func (f *PrintFlags) AddFlags(cmd *cobra.Command) { + f.GenericPrintFlags.AddFlags(cmd) + f.HumanReadableFlags.AddFlags(cmd) +} + +// NewPrintFlags returns flags associated with humanreadable, template, and +// "name" printing, with default values set. +func NewPrintFlags(printer func(h hprinters.PrintHandler)) *PrintFlags { + return &PrintFlags{ + GenericPrintFlags: genericclioptions.NewPrintFlags(""), + HumanReadableFlags: commands.NewHumanPrintFlags(), + PrinterHandler: printer, + } +} + +// EnsureWithNamespace ensures that humanreadable flags return +// a printer capable of printing with a "namespace" column. +func (f *PrintFlags) EnsureWithNamespace() { + f.HumanReadableFlags.EnsureWithNamespace() +} diff --git a/pkg/kn/commands/flags/sink.go b/vendor/knative.dev/client-pkg/pkg/commands/flags/sink/flag.go similarity index 81% rename from pkg/kn/commands/flags/sink.go rename to vendor/knative.dev/client-pkg/pkg/commands/flags/sink/flag.go index 5bcd4254a8..ba03e58664 100644 --- a/pkg/kn/commands/flags/sink.go +++ b/vendor/knative.dev/client-pkg/pkg/commands/flags/sink/flag.go @@ -1,18 +1,20 @@ -// Copyright © 2019 The Knative 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 flags +/* + Copyright 2024 The Knative 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 sink import ( "context" @@ -22,28 +24,29 @@ import ( "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/client-pkg/pkg/config" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" - clientdynamic "knative.dev/client/pkg/dynamic" - "knative.dev/client/pkg/kn/config" + clientdynamic "knative.dev/client-pkg/pkg/dynamic" ) -type SinkFlags struct { +// Flag holds the sink flag and its mappings +type Flag struct { Sink string SinkMappings map[string]schema.GroupVersionResource } -// NewSinkFlag is a constructor function to create SinkFlags from provided map -func NewSinkFlag(mapping map[string]schema.GroupVersionResource) *SinkFlags { - return &SinkFlags{ +// NewFlag is a constructor function to create Flag from provided map +func NewFlag(mapping map[string]schema.GroupVersionResource) *Flag { + return &Flag{ SinkMappings: mapping, } } // AddWithFlagName configures Sink flag with given flag name and a short flag name // pass empty short flag name if you don't want to set one -func (i *SinkFlags) AddWithFlagName(cmd *cobra.Command, fname, short string) { +func (i *Flag) AddWithFlagName(cmd *cobra.Command, fname, short string) { flag := "--" + fname if short == "" { cmd.Flags().StringVar(&i.Sink, fname, "", "") @@ -74,7 +77,7 @@ func (i *SinkFlags) AddWithFlagName(cmd *cobra.Command, fname, short string) { } // Add configures Sink flag with name 'Sink' amd short name 's' -func (i *SinkFlags) Add(cmd *cobra.Command) { +func (i *Flag) Add(cmd *cobra.Command) { i.AddWithFlagName(cmd, "sink", "s") } @@ -100,7 +103,7 @@ var defaultSinkMappings = map[string]schema.GroupVersionResource{ // ResolveSink returns the Destination referred to by the flags in the acceptor. // It validates that any object the user is referring to exists. -func (i *SinkFlags) ResolveSink(ctx context.Context, knclient clientdynamic.KnDynamicClient, namespace string) (*duckv1.Destination, error) { +func (i *Flag) ResolveSink(ctx context.Context, knclient clientdynamic.KnDynamicClient, namespace string) (*duckv1.Destination, error) { client := knclient.RawClient() if i.Sink == "" { return nil, nil diff --git a/vendor/knative.dev/client-pkg/pkg/commands/human_readable_flags.go b/vendor/knative.dev/client-pkg/pkg/commands/human_readable_flags.go new file mode 100644 index 0000000000..faa477e2d6 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/human_readable_flags.go @@ -0,0 +1,121 @@ +// Copyright © 2019 The Knative 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 commands + +import ( + "fmt" + "time" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/duration" + hprinters "knative.dev/client-pkg/pkg/printers" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +// HumanPrintFlags provides default flags necessary for printing. +// Given the following flag values, a printer can be requested that knows +// how to handle printing based on these values. +type HumanPrintFlags struct { + WithNamespace bool + NoHeaders bool + //TODO: Add more flags as required +} + +// AllowedFormats returns more customized formating options +func (f *HumanPrintFlags) AllowedFormats() []string { + // TODO: Add more formats eg: wide + return []string{"no-headers"} +} + +// ToPrinter receives returns a printer capable of +// handling human-readable output. +func (f *HumanPrintFlags) ToPrinter(getHandlerFunc func(h hprinters.PrintHandler)) (hprinters.ResourcePrinter, error) { + p := hprinters.NewTablePrinter(hprinters.PrintOptions{AllNamespaces: f.WithNamespace, NoHeaders: f.NoHeaders}) + getHandlerFunc(p) + return p, nil +} + +// AddFlags receives a *cobra.Command reference and binds +// flags related to human-readable printing to it +func (f *HumanPrintFlags) AddFlags(c *cobra.Command) { + c.Flags().BoolVar(&f.NoHeaders, "no-headers", false, "When using the default output format, don't print headers (default: print headers).") + //TODO: Add more flags as required +} + +// NewHumanPrintFlags returns flags associated with +// human-readable printing, with default values set. +func NewHumanPrintFlags() *HumanPrintFlags { + return &HumanPrintFlags{} +} + +// EnsureWithNamespace sets the "WithNamespace" humanreadable option to true. +func (f *HumanPrintFlags) EnsureWithNamespace() { + f.WithNamespace = true +} + +// conditionsValue returns the True conditions count among total conditions +func ConditionsValue(conditions duckv1.Conditions) string { + var ok int + for _, condition := range conditions { + if condition.Status == "True" { + ok++ + } + } + return fmt.Sprintf("%d OK / %d", ok, len(conditions)) +} + +// readyCondition returns status of resource's Ready type condition +func ReadyCondition(conditions duckv1.Conditions) string { + for _, condition := range conditions { + if condition.Type == apis.ConditionReady { + return string(condition.Status) + } + } + return "" +} + +// NonReadyConditionReason returns formatted string of +// reason and message for non ready conditions +func NonReadyConditionReason(conditions duckv1.Conditions) string { + for _, condition := range conditions { + if condition.Type == apis.ConditionReady { + if string(condition.Status) == "True" { + return "" + } + if condition.Message != "" { + return fmt.Sprintf("%s : %s", condition.Reason, condition.Message) + } + return condition.Reason + } + } + return "" +} + +// translateTimestampSince returns the elapsed time since timestamp in +// human-readable approximation. +func TranslateTimestampSince(timestamp metav1.Time) string { + if timestamp.IsZero() { + return "" + } + return duration.HumanDuration(time.Since(timestamp.Time)) +} + +// AddGitOpsFlags adds flags to enable gitops mode +func AddGitOpsFlags(flags *pflag.FlagSet) { + flags.String("target", "", "Work on local directory instead of a remote cluster (experimental)") +} diff --git a/vendor/knative.dev/client-pkg/pkg/commands/namespaced.go b/vendor/knative.dev/client-pkg/pkg/commands/namespaced.go new file mode 100644 index 0000000000..3b7b90128a --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/namespaced.go @@ -0,0 +1,92 @@ +// Copyright © 2019 The Knative 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 commands + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "k8s.io/client-go/tools/clientcmd" +) + +// AddNamespaceFlags adds the namespace-related flags: +// * --namespace +// * --all-namespaces +func AddNamespaceFlags(flags *pflag.FlagSet, allowAll bool) { + flags.StringP( + "namespace", + "n", + "", + "Specify the namespace to operate in.", + ) + + if allowAll { + flags.BoolP( + "all-namespaces", + "A", + false, + "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.", + ) + } +} + +// GetNamespace returns namespace from command specified by flag +func (params *KnParams) GetNamespace(cmd *cobra.Command) (string, error) { + namespaceFlag := cmd.Flag("namespace") + if namespaceFlag == nil { + return "", fmt.Errorf("command %s doesn't have --namespace flag", cmd.Name()) + } + namespace := namespaceFlag.Value.String() + // check value of all-namespaces only if its defined + if cmd.Flags().Lookup("all-namespaces") != nil { + all, err := cmd.Flags().GetBool("all-namespaces") + if err != nil { + return "", err + } else if all { // if all-namespaces=True + // namespace = "" <-- all-namespaces representation + return "", nil + } + } + // if all-namespaces=False or namespace not given, use default namespace + if namespace == "" { + var err error + namespace, err = params.CurrentNamespace() + if err != nil { + if !clientcmd.IsEmptyConfig(err) { + return "", err + } + // If no current namespace is set use "default" + namespace = "default" + } + } + return namespace, nil +} + +// CurrentNamespace returns the current namespace which is either provided as option or picked up from kubeconfig +func (params *KnParams) CurrentNamespace() (string, error) { + var err error + if params.fixedCurrentNamespace != "" { + return params.fixedCurrentNamespace, nil + } + if params.ClientConfig == nil { + params.ClientConfig, err = params.GetClientConfig() + if err != nil { + return "", err + } + } + name, _, err := params.ClientConfig.Namespace() + return name, err +} diff --git a/vendor/knative.dev/client-pkg/pkg/commands/testing_helper.go b/vendor/knative.dev/client-pkg/pkg/commands/testing_helper.go new file mode 100644 index 0000000000..8582febda8 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/testing_helper.go @@ -0,0 +1,98 @@ +// Copyright © 2018 The Knative 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 commands + +import ( + "bytes" + + "knative.dev/client-pkg/pkg/dynamic/fake" + "knative.dev/client-pkg/pkg/flags" + + "github.com/spf13/cobra" + "k8s.io/apimachinery/pkg/runtime" + clienttesting "k8s.io/client-go/testing" + servingv1fake "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/fake" + + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + v1 "knative.dev/client-pkg/pkg/sources/v1" + + sourcesv1fake "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1/fake" + + clientdynamic "knative.dev/client-pkg/pkg/dynamic" +) + +const FakeNamespace = "current" + +// CreateTestKnCommand helper for creating test commands +func CreateTestKnCommand(cmd *cobra.Command, knParams *KnParams) (*cobra.Command, *servingv1fake.FakeServingV1, *bytes.Buffer) { + buf := new(bytes.Buffer) + fakeServing := &servingv1fake.FakeServingV1{Fake: &clienttesting.Fake{}} + knParams.Output = buf + knParams.NewServingClient = func(namespace string) (clientservingv1.KnServingClient, error) { + return clientservingv1.NewKnServingClient(fakeServing, FakeNamespace), nil + } + knParams.fixedCurrentNamespace = FakeNamespace + knCommand := NewTestCommand(cmd, knParams) + return knCommand, fakeServing, buf +} + +// CreateSourcesTestKnCommand helper for creating test commands +func CreateSourcesTestKnCommand(cmd *cobra.Command, knParams *KnParams) (*cobra.Command, *sourcesv1fake.FakeSourcesV1, *bytes.Buffer) { + buf := new(bytes.Buffer) + // create fake serving client because the sink of source depends on serving client + fakeServing := &servingv1fake.FakeServingV1{Fake: &clienttesting.Fake{}} + knParams.NewServingClient = func(namespace string) (clientservingv1.KnServingClient, error) { + return clientservingv1.NewKnServingClient(fakeServing, FakeNamespace), nil + } + // create fake sources client + fakeEventing := &sourcesv1fake.FakeSourcesV1{Fake: &clienttesting.Fake{}} + knParams.Output = buf + knParams.NewSourcesClient = func(namespace string) (v1.KnSourcesClient, error) { + return v1.NewKnSourcesClient(fakeEventing, FakeNamespace), nil + } + knParams.fixedCurrentNamespace = FakeNamespace + knCommand := NewTestCommand(cmd, knParams) + return knCommand, fakeEventing, buf +} + +// CreateDynamicTestKnCommand helper for creating test commands using dynamic client +func CreateDynamicTestKnCommand(cmd *cobra.Command, knParams *KnParams, objects ...runtime.Object) (*cobra.Command, *clientdynamic.KnDynamicClient, *bytes.Buffer) { + buf := new(bytes.Buffer) + fakeDynamic := fake.CreateFakeKnDynamicClient(FakeNamespace, objects...) + knParams.Output = buf + knParams.NewDynamicClient = func(namespace string) (clientdynamic.KnDynamicClient, error) { + return fakeDynamic, nil + } + + knParams.fixedCurrentNamespace = FakeNamespace + knCommand := NewTestCommand(cmd, knParams) + return knCommand, &fakeDynamic, buf + +} + +// NewTestCommand can be used by tes +func NewTestCommand(subCommand *cobra.Command, params *KnParams) *cobra.Command { + rootCmd := &cobra.Command{ + Use: "kn", + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + return flags.ReconcileBoolFlags(cmd.Flags()) + }, + } + if params.Output != nil { + rootCmd.SetOut(params.Output) + } + rootCmd.AddCommand(subCommand) + return rootCmd +} diff --git a/vendor/knative.dev/client-pkg/pkg/commands/types.go b/vendor/knative.dev/client-pkg/pkg/commands/types.go new file mode 100644 index 0000000000..c792b8b61e --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/types.go @@ -0,0 +1,289 @@ +// Copyright © 2018 The Knative 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 commands + +import ( + "fmt" + "io" + "os" + "path/filepath" + + "k8s.io/client-go/kubernetes" + + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + eventingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1" + eventingv1beta2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta2" + messagingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" + sourcesv1client "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1" + sourcesv1beta2client "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1beta2" + servingv1client "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1" + servingv1beta1client "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1" + + "knative.dev/client-pkg/pkg/util" + + clientdynamic "knative.dev/client-pkg/pkg/dynamic" + knerrors "knative.dev/client-pkg/pkg/errors" + clienteventingv1 "knative.dev/client-pkg/pkg/eventing/v1" + clienteventingv1beta2 "knative.dev/client-pkg/pkg/eventing/v1beta2" + clientmessagingv1 "knative.dev/client-pkg/pkg/messaging/v1" + clientservingv1 "knative.dev/client-pkg/pkg/serving/v1" + clientservingv1beta1 "knative.dev/client-pkg/pkg/serving/v1beta1" + clientsourcesv1 "knative.dev/client-pkg/pkg/sources/v1" + clientsourcesv1beta2 "knative.dev/client-pkg/pkg/sources/v1beta2" +) + +// KnParams for creating commands. Useful for inserting mocks for testing. +type KnParams struct { + Output io.Writer + KubeCfgPath string + KubeContext string + KubeCluster string + KubeAsUser string + KubeAsUID string + KubeAsGroup []string + ClientConfig clientcmd.ClientConfig + NewKubeClient func() (kubernetes.Interface, error) + NewServingClient func(namespace string) (clientservingv1.KnServingClient, error) + NewServingV1beta1Client func(namespace string) (clientservingv1beta1.KnServingClient, error) + NewGitopsServingClient func(namespace string, dir string) (clientservingv1.KnServingClient, error) + NewSourcesClient func(namespace string) (clientsourcesv1.KnSourcesClient, error) + NewSourcesV1beta2Client func(namespace string) (clientsourcesv1beta2.KnSourcesClient, error) + NewEventingClient func(namespace string) (clienteventingv1.KnEventingClient, error) + NewMessagingClient func(namespace string) (clientmessagingv1.KnMessagingClient, error) + NewDynamicClient func(namespace string) (clientdynamic.KnDynamicClient, error) + NewEventingV1beta2Client func(namespace string) (clienteventingv1beta2.KnEventingV1Beta2Client, error) + + // General global options + LogHTTP bool + + // Set this if you want to nail down the namespace + fixedCurrentNamespace string +} + +func (params *KnParams) Initialize() { + if params.NewKubeClient == nil { + params.NewKubeClient = params.newKubeClient + } + + if params.NewServingClient == nil { + params.NewServingClient = params.newServingClient + } + + if params.NewServingV1beta1Client == nil { + params.NewServingV1beta1Client = params.newServingClientV1beta1 + } + + if params.NewGitopsServingClient == nil { + params.NewGitopsServingClient = params.newGitopsServingClient + } + + if params.NewSourcesClient == nil { + params.NewSourcesClient = params.newSourcesClient + } + + if params.NewEventingClient == nil { + params.NewEventingClient = params.newEventingClient + } + + if params.NewMessagingClient == nil { + params.NewMessagingClient = params.newMessagingClient + } + + if params.NewDynamicClient == nil { + params.NewDynamicClient = params.newDynamicClient + } + + if params.NewSourcesV1beta2Client == nil { + params.NewSourcesV1beta2Client = params.newSourcesClientV1beta2 + } + + if params.NewEventingV1beta2Client == nil { + params.NewEventingV1beta2Client = params.newEventingV1Beta2Client + } +} + +func (params *KnParams) newKubeClient() (kubernetes.Interface, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, err := kubernetes.NewForConfig(restConfig) + if err != nil { + return nil, err + } + + return client, nil +} + +func (params *KnParams) newServingClient(namespace string) (clientservingv1.KnServingClient, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, err := servingv1client.NewForConfig(restConfig) + if err != nil { + return nil, err + } + return clientservingv1.NewKnServingClient(client, namespace), nil +} + +func (params *KnParams) newServingClientV1beta1(namespace string) (clientservingv1beta1.KnServingClient, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, err := servingv1beta1client.NewForConfig(restConfig) + if err != nil { + return nil, err + } + return clientservingv1beta1.NewKnServingClient(client, namespace), nil +} + +func (params *KnParams) newGitopsServingClient(namespace string, dir string) (clientservingv1.KnServingClient, error) { + return clientservingv1.NewKnServingGitOpsClient(namespace, dir), nil +} + +func (params *KnParams) newSourcesClient(namespace string) (clientsourcesv1.KnSourcesClient, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, _ := sourcesv1client.NewForConfig(restConfig) + return clientsourcesv1.NewKnSourcesClient(client, namespace), nil +} + +func (params *KnParams) newSourcesClientV1beta2(namespace string) (clientsourcesv1beta2.KnSourcesClient, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, _ := sourcesv1beta2client.NewForConfig(restConfig) + return clientsourcesv1beta2.NewKnSourcesClient(client, namespace), nil +} + +func (params *KnParams) newEventingClient(namespace string) (clienteventingv1.KnEventingClient, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, _ := eventingv1.NewForConfig(restConfig) + return clienteventingv1.NewKnEventingClient(client, namespace), nil +} + +func (params *KnParams) newEventingV1Beta2Client(namespace string) (clienteventingv1beta2.KnEventingV1Beta2Client, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, _ := eventingv1beta2.NewForConfig(restConfig) + return clienteventingv1beta2.NewKnEventingV1Beta2Client(client, namespace), nil +} + +func (params *KnParams) newMessagingClient(namespace string) (clientmessagingv1.KnMessagingClient, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, _ := messagingv1.NewForConfig(restConfig) + return clientmessagingv1.NewKnMessagingClient(client, namespace), nil +} + +func (params *KnParams) newDynamicClient(namespace string) (clientdynamic.KnDynamicClient, error) { + restConfig, err := params.RestConfig() + if err != nil { + return nil, err + } + + client, _ := dynamic.NewForConfig(restConfig) + return clientdynamic.NewKnDynamicClient(client, namespace), nil +} + +// RestConfig returns REST config, which can be to use to create specific clientset +func (params *KnParams) RestConfig() (*rest.Config, error) { + var err error + + if params.ClientConfig == nil { + params.ClientConfig, err = params.GetClientConfig() + if err != nil { + return nil, knerrors.GetError(err) + } + } + + config, err := params.ClientConfig.ClientConfig() + if err != nil { + return nil, knerrors.GetError(err) + } + if params.LogHTTP { + config.Wrap(util.NewLoggingTransport) + } + // Override client-go's warning handler to give us nicely printed warnings. + config.WarningHandler = rest.NewWarningWriter(os.Stderr, rest.WarningWriterOptions{ + // only print a given warning the first time we receive it + Deduplicate: true, + }) + + return config, nil +} + +// GetClientConfig gets ClientConfig from KubeCfgPath +func (params *KnParams) GetClientConfig() (clientcmd.ClientConfig, error) { + loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() + configOverrides := &clientcmd.ConfigOverrides{} + if params.KubeContext != "" { + configOverrides.CurrentContext = params.KubeContext + } + if params.KubeCluster != "" { + configOverrides.Context.Cluster = params.KubeCluster + } + if params.KubeAsUser != "" { + configOverrides.AuthInfo.Impersonate = params.KubeAsUser + } + if params.KubeAsUID != "" { + configOverrides.AuthInfo.ImpersonateUID = params.KubeAsUID + } + if len(params.KubeAsGroup) > 0 { + configOverrides.AuthInfo.ImpersonateGroups = params.KubeAsGroup + } + if len(params.KubeCfgPath) == 0 { + return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides), nil + } + + _, err := os.Stat(params.KubeCfgPath) + if err == nil { + loadingRules.ExplicitPath = params.KubeCfgPath + return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides), nil + } + + if !os.IsNotExist(err) { + return nil, err + } + + paths := filepath.SplitList(params.KubeCfgPath) + if len(paths) > 1 { + return nil, fmt.Errorf("can not find config file. '%s' looks like a path. "+ + "Please use the env var KUBECONFIG if you want to check for multiple configuration files", params.KubeCfgPath) + } + return nil, fmt.Errorf("config file '%s' can not be found", params.KubeCfgPath) +} diff --git a/vendor/knative.dev/client-pkg/pkg/commands/wait_flags.go b/vendor/knative.dev/client-pkg/pkg/commands/wait_flags.go new file mode 100644 index 0000000000..3ae3e4deb7 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/commands/wait_flags.go @@ -0,0 +1,59 @@ +// Copyright © 2019 The Knative 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 commands + +import ( + "fmt" + + "github.com/spf13/cobra" + + knflags "knative.dev/client-pkg/pkg/flags" +) + +// Default time out to use when waiting for reconciliation. It is deliberately very long as it is expected that +// the service doesn't stay in `Unknown` status very long and eventually ends up as `False` or `True` in a timely +// manner +const WaitDefaultTimeout = 600 + +// Flags for tuning wait behaviour +type WaitFlags struct { + // Timeout in seconds for how long to wait for a command to return + TimeoutInSeconds int + // If set then apply resources and wait for completion + Wait bool + // Duration in seconds for waiting between intermediate false ready conditions + ErrorWindowInSeconds int +} + +// Add flags which influence the wait/no-wait behaviour when creating, updating, waiting for +// resources. If the action is not `wait`, set `waitDefault` argument if the default behaviour is synchronous. +// Use `what` for describing what is waited for. +func (p *WaitFlags) AddConditionWaitFlags(command *cobra.Command, waitTimeoutDefault int, action, what, until string) { + if action != "wait" { + waitUsage := fmt.Sprintf("Wait for '%s %s' operation to be completed.", what, action) + waitDefault := true + // Special-case 'delete' command so it comes back to the user immediately + if action == "delete" { + waitDefault = false + } + + knflags.AddBothBoolFlagsUnhidden(command.Flags(), &p.Wait, "wait", "", waitDefault, waitUsage) + } + timeoutUsage := fmt.Sprintf("Seconds to wait before giving up on waiting for %s to be %s.", what, until) + command.Flags().IntVar(&p.TimeoutInSeconds, "wait-timeout", waitTimeoutDefault, timeoutUsage) + + windowUsage := fmt.Sprintf("Seconds to wait for %s to be %s after a false ready condition is returned", what, until) + command.Flags().IntVar(&p.ErrorWindowInSeconds, "wait-window", 2, windowUsage) +} diff --git a/vendor/knative.dev/client-pkg/pkg/config/config.go b/vendor/knative.dev/client-pkg/pkg/config/config.go new file mode 100644 index 0000000000..8f548bfe38 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/config/config.go @@ -0,0 +1,285 @@ +/* + Copyright 2024 The Knative 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 ( + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + + "github.com/mitchellh/go-homedir" + flag "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +// bootstrapDefaults are the defaults values to use +type defaultConfig struct { + configFile string + pluginsDir string + lookupPluginsInPath bool +} + +// Initialize defaults +var bootstrapDefaults = initDefaults() + +const configContentDefaults = `# Taken from https://github.com/knative/client/blob/main/docs/README.md#options +# +#plugins: +# directory: ~/.config/kn/plugins +#eventing: +# sink-mappings: +# - prefix: svc +# group: core +# version: v1 +# resource: services +# channel-type-mappings: +# - alias: Kafka +# group: messaging.knative.dev +# version: v1alpha1 +# kind: KafkaChannel +` + +// config contains the variables for the Kn config +type config struct { + // configFile is the config file location + configFile string + + // sinkMappings is a list of sink mapping + sinkMappings []SinkMapping + + // channelTypeMappings is a list of channel type mapping + channelTypeMappings []ChannelTypeMapping +} + +// ConfigFile returns the config file which is either the default XDG conform +// config file location or the one set with --config +func (c *config) ConfigFile() string { + if c.configFile != "" { + return c.configFile + } + return bootstrapDefaults.configFile +} + +// PluginsDir returns the plugins' directory +func (c *config) PluginsDir() string { + if viper.IsSet(keyPluginsDirectory) { + return viper.GetString(keyPluginsDirectory) + } else if viper.IsSet(legacyKeyPluginsDirectory) { + // Remove that branch if legacy option is switched off + return viper.GetString(legacyKeyPluginsDirectory) + } else { + return bootstrapDefaults.pluginsDir + } +} + +// LookupPluginsInPath returns true if plugins should be also checked in the pat +func (c *config) LookupPluginsInPath() bool { + return bootstrapDefaults.lookupPluginsInPath +} + +func (c *config) SinkMappings() []SinkMapping { + return c.sinkMappings +} + +func (c *config) ChannelTypeMappings() []ChannelTypeMapping { + return c.channelTypeMappings +} + +// Config used for flag binding +var globalConfig = config{} + +// GlobalConfig is the global configuration available for every sub-command +var GlobalConfig Config = &globalConfig + +// BootstrapConfig reads in config file and bootstrap options if set. +func BootstrapConfig() error { + + // Create a new FlagSet for the bootstrap flags and parse those. This will + // initialize the config file to use (obtained via GlobalConfig.ConfigFile()) + bootstrapFlagSet := flag.NewFlagSet("kn", flag.ContinueOnError) + AddBootstrapFlags(bootstrapFlagSet) + bootstrapFlagSet.ParseErrorsWhitelist = flag.ParseErrorsWhitelist{UnknownFlags: true} // wokeignore:rule=whitelist // TODO(#1031) + bootstrapFlagSet.Usage = func() {} + err := bootstrapFlagSet.Parse(os.Args) + if err != nil && !errors.Is(err, flag.ErrHelp) { + return err + } + + // Bind flags so that options that have been provided have priority. + // Important: Always read options via GlobalConfig methods + err = viper.BindPFlag(keyPluginsDirectory, bootstrapFlagSet.Lookup(flagPluginsDir)) + if err != nil { + return err + } + + viper.SetConfigFile(GlobalConfig.ConfigFile()) + configFile := GlobalConfig.ConfigFile() + _, err = os.Lstat(configFile) + if err != nil { + if !os.IsNotExist(err) { + return fmt.Errorf("cannot stat configfile %s: %w", configFile, err) + } + if err := os.MkdirAll(filepath.Dir(viper.ConfigFileUsed()), 0775); err != nil { + // Can't create config directory, proceed silently without reading the config + return nil + } + if err := os.WriteFile(viper.ConfigFileUsed(), []byte(configContentDefaults), 0600); err != nil { + // Can't create config file, proceed silently without reading the config + return nil + } + } + + viper.AutomaticEnv() // read in environment variables that match + + // Defaults are taken from the parsed flags, which in turn have bootstrap defaults + // TODO: Re-enable when legacy handling for plugin config has been removed + // For now default handling is happening directly in the getter of GlobalConfig + // viper.SetDefault(keyPluginsDirectory, bootstrapDefaults.pluginsDir) + + // If a config file is found, read it in. + err = viper.ReadInConfig() + if err != nil { + return err + } + + // Deserialize sink mappings if configured + err = parseSinkMappings() + if err != nil { + return err + } + + // Deserialize channel type mappings if configured + err = parseChannelTypeMappings() + return err +} + +// Add bootstrap flags use in a separate bootstrap proceeds +func AddBootstrapFlags(flags *flag.FlagSet) { + flags.StringVar(&globalConfig.configFile, "config", "", fmt.Sprintf("kn configuration file (default: %s)", defaultConfigFileForUsageMessage())) + flags.String(flagPluginsDir, "", "Directory holding kn plugins") + + // Let's try that and mark the flags as hidden: (as those configuration is a permanent choice of operation) + flags.MarkHidden(flagPluginsDir) +} + +// =========================================================================================================== + +// Initialize defaults. This happens lazily go allow to change the +// home directory for e.g. tests +func initDefaults() *defaultConfig { + return &defaultConfig{ + configFile: defaultConfigLocation("config.yaml"), + pluginsDir: defaultConfigLocation("plugins"), + lookupPluginsInPath: true, + } +} + +func defaultConfigLocation(subpath string) string { + var base string + if runtime.GOOS == "windows" { + base = defaultConfigDirWindows() + } else { + base = defaultConfigDirUnix() + } + return filepath.Join(base, subpath) +} + +func defaultConfigDirUnix() string { + home, err := homedir.Dir() + if err != nil { + home = "~" + } + + // Check the deprecated path first and fallback to it, add warning to error message + if configHome := filepath.Join(home, ".kn"); dirExists(configHome) { + migrationPath := filepath.Join(home, ".config", "kn") + fmt.Fprintf(os.Stderr, "WARNING: deprecated kn config directory '%s' detected. Please move your configuration to '%s'\n", configHome, migrationPath) + return configHome + } + + // Respect XDG_CONFIG_HOME if set + if xdgHome := os.Getenv("XDG_CONFIG_HOME"); xdgHome != "" { + return filepath.Join(xdgHome, "kn") + } + // Fallback to XDG default for both Linux and macOS + // ~/.config/kn + return filepath.Join(home, ".config", "kn") +} + +func defaultConfigDirWindows() string { + home, err := homedir.Dir() + if err != nil { + // Check the deprecated path first and fallback to it, add warning to error message + if configHome := filepath.Join(home, ".kn"); dirExists(configHome) { + migrationPath := filepath.Join(os.Getenv("APPDATA"), "kn") + fmt.Fprintf(os.Stderr, "WARNING: deprecated kn config directory '%s' detected. Please move your configuration to '%s'\n", configHome, migrationPath) + return configHome + } + } + + return filepath.Join(os.Getenv("APPDATA"), "kn") +} + +func dirExists(path string) bool { + if _, err := os.Stat(path); !os.IsNotExist(err) { + return true + } + return false +} + +// parse sink mappings and store them in the global configuration +func parseSinkMappings() error { + // Parse sink configuration + key := "" + if viper.IsSet(keySinkMappings) { + key = keySinkMappings + } + if key == "" && viper.IsSet(legacyKeySinkMappings) { + key = legacyKeySinkMappings + } + + if key != "" { + err := viper.UnmarshalKey(key, &globalConfig.sinkMappings) + if err != nil { + return fmt.Errorf("error while parsing sink mappings in configuration file %s: %w", + viper.ConfigFileUsed(), err) + } + } + return nil +} + +// parse channel type mappings and store them in the global configuration +func parseChannelTypeMappings() error { + if viper.IsSet(keyChannelTypeMappings) { + err := viper.UnmarshalKey(keyChannelTypeMappings, &globalConfig.channelTypeMappings) + if err != nil { + return fmt.Errorf("error while parsing channel type mappings in configuration file %s: %w", + viper.ConfigFileUsed(), err) + } + } + return nil +} + +// Prepare the default config file for the usage message +func defaultConfigFileForUsageMessage() string { + if runtime.GOOS == "windows" { + return "%APPDATA%\\kn\\config.yaml" + } + return "~/.config/kn/config.yaml" +} diff --git a/pkg/config/defaults.go b/vendor/knative.dev/client-pkg/pkg/config/defaults.go similarity index 100% rename from pkg/config/defaults.go rename to vendor/knative.dev/client-pkg/pkg/config/defaults.go diff --git a/vendor/knative.dev/client-pkg/pkg/config/types.go b/vendor/knative.dev/client-pkg/pkg/config/types.go new file mode 100644 index 0000000000..2ef7dc8de7 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/config/types.go @@ -0,0 +1,88 @@ +// Copyright © 2020 The Knative 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 + +// Package for holding configuration types used in bootstrapping +// and for types in configuration files + +type Config interface { + + // ConfigFile returns the location of the configuration file + ConfigFile() string + + // PluginsDir returns the path to the directory containing plugins + PluginsDir() string + + // LookupPluginsInPath returns true if plugins should be also looked up + // in the execution path + LookupPluginsInPath() bool + + // SinkMappings returns additional mappings for sink prefixes to resources + SinkMappings() []SinkMapping + + // ChannelTypeMappings returns additional mappings for channel type aliases + ChannelTypeMappings() []ChannelTypeMapping +} + +// SinkMappings is the struct of sink prefix config in kn config +type SinkMapping struct { + + // Prefix is the mapping prefix (like "svc") + Prefix string + + // Resource is the name for the mapped resource (like "services", mind the plural) + Resource string + + // Group is the api group for the mapped resource (like "core") + Group string + + // Version is the api version for the mapped resource (like "v1") + Version string +} + +// ChannelTypeMapping is the struct of ChannelType alias config in kn config +type ChannelTypeMapping struct { + + // Alias is the mapping alias (like "kafka") + Alias string + + // Kind is the name for the mapped resource kind (like "KafkaChannel") + Kind string + + // Group is the API group for the mapped resource kind (like "messaging.knative.dev") + Group string + + // Version is the API version for the mapped resource kind (like "v1alpha1") + Version string +} + +// config Keys for looking up in viper +const ( + keyPluginsDirectory = "plugins.directory" + keySinkMappings = "eventing.sink-mappings" + keyChannelTypeMappings = "eventing.channel-type-mappings" +) + +// legacy config keys, deprecated +const ( + legacyKeyPluginsDirectory = "plugins-dir" + legacyKeySinkMappings = "sink" +) + +// Global (hidden) flags +// TODO: Remove me if decided that they are not needed +const ( + flagPluginsDir = "plugins-dir" +) diff --git a/pkg/dynamic/client.go b/vendor/knative.dev/client-pkg/pkg/dynamic/client.go similarity index 99% rename from pkg/dynamic/client.go rename to vendor/knative.dev/client-pkg/pkg/dynamic/client.go index e885dca840..950abf2ef7 100644 --- a/pkg/dynamic/client.go +++ b/vendor/knative.dev/client-pkg/pkg/dynamic/client.go @@ -25,7 +25,7 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "knative.dev/eventing/pkg/apis/messaging" ) diff --git a/pkg/dynamic/client_mock.go b/vendor/knative.dev/client-pkg/pkg/dynamic/client_mock.go similarity index 99% rename from pkg/dynamic/client_mock.go rename to vendor/knative.dev/client-pkg/pkg/dynamic/client_mock.go index ebeb19eab7..c856f1086c 100644 --- a/pkg/dynamic/client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/dynamic/client_mock.go @@ -22,7 +22,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" ) // MockKnDynamicClient is a combine of test object and recorder diff --git a/pkg/dynamic/fake/fake.go b/vendor/knative.dev/client-pkg/pkg/dynamic/fake/fake.go similarity index 97% rename from pkg/dynamic/fake/fake.go rename to vendor/knative.dev/client-pkg/pkg/dynamic/fake/fake.go index 954cc43ff0..205523257b 100644 --- a/pkg/dynamic/fake/fake.go +++ b/vendor/knative.dev/client-pkg/pkg/dynamic/fake/fake.go @@ -20,7 +20,7 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/dynamic" + "knative.dev/client-pkg/pkg/dynamic" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" diff --git a/pkg/dynamic/lib.go b/vendor/knative.dev/client-pkg/pkg/dynamic/lib.go similarity index 100% rename from pkg/dynamic/lib.go rename to vendor/knative.dev/client-pkg/pkg/dynamic/lib.go diff --git a/pkg/errors/errors.go b/vendor/knative.dev/client-pkg/pkg/errors/errors.go similarity index 100% rename from pkg/errors/errors.go rename to vendor/knative.dev/client-pkg/pkg/errors/errors.go diff --git a/pkg/errors/factory.go b/vendor/knative.dev/client-pkg/pkg/errors/factory.go similarity index 100% rename from pkg/errors/factory.go rename to vendor/knative.dev/client-pkg/pkg/errors/factory.go diff --git a/pkg/errors/knerror.go b/vendor/knative.dev/client-pkg/pkg/errors/knerror.go similarity index 100% rename from pkg/errors/knerror.go rename to vendor/knative.dev/client-pkg/pkg/errors/knerror.go diff --git a/pkg/errors/types.go b/vendor/knative.dev/client-pkg/pkg/errors/types.go similarity index 100% rename from pkg/errors/types.go rename to vendor/knative.dev/client-pkg/pkg/errors/types.go diff --git a/pkg/eventing/v1/client.go b/vendor/knative.dev/client-pkg/pkg/eventing/v1/client.go similarity index 99% rename from pkg/eventing/v1/client.go rename to vendor/knative.dev/client-pkg/pkg/eventing/v1/client.go index decc443e15..8e502996dc 100644 --- a/pkg/eventing/v1/client.go +++ b/vendor/knative.dev/client-pkg/pkg/eventing/v1/client.go @@ -24,16 +24,16 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/util/retry" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" v1 "knative.dev/eventing/pkg/apis/duck/v1" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" clientv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1" duckv1 "knative.dev/pkg/apis/duck/v1" - kn_errors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" + kn_errors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/wait" ) type TriggerUpdateFunc func(origTrigger *eventingv1.Trigger) (*eventingv1.Trigger, error) diff --git a/pkg/eventing/v1/client_mock.go b/vendor/knative.dev/client-pkg/pkg/eventing/v1/client_mock.go similarity index 99% rename from pkg/eventing/v1/client_mock.go rename to vendor/knative.dev/client-pkg/pkg/eventing/v1/client_mock.go index e8cea8559f..b95d2561bd 100644 --- a/pkg/eventing/v1/client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/eventing/v1/client_mock.go @@ -21,7 +21,7 @@ import ( eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" ) // MockKnEventingClient is a combine of test object and recorder diff --git a/pkg/eventing/v1beta2/client.go b/vendor/knative.dev/client-pkg/pkg/eventing/v1beta2/client.go similarity index 98% rename from pkg/eventing/v1beta2/client.go rename to vendor/knative.dev/client-pkg/pkg/eventing/v1beta2/client.go index c1f5eacf5e..b1b713c24c 100644 --- a/pkg/eventing/v1beta2/client.go +++ b/vendor/knative.dev/client-pkg/pkg/eventing/v1beta2/client.go @@ -19,8 +19,8 @@ import ( apis_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - kn_errors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/util" + kn_errors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/util" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" diff --git a/pkg/eventing/v1beta2/client_mock.go b/vendor/knative.dev/client-pkg/pkg/eventing/v1beta2/client_mock.go similarity index 99% rename from pkg/eventing/v1beta2/client_mock.go rename to vendor/knative.dev/client-pkg/pkg/eventing/v1beta2/client_mock.go index 6d53b91c88..b026f1efec 100644 --- a/pkg/eventing/v1beta2/client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/eventing/v1beta2/client_mock.go @@ -20,7 +20,7 @@ import ( eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" ) // MockKnEventingV1beta2Client is a combine of test object and recorder diff --git a/vendor/knative.dev/client-pkg/pkg/flags/bool.go b/vendor/knative.dev/client-pkg/pkg/flags/bool.go new file mode 100644 index 0000000000..feca0b2af6 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/flags/bool.go @@ -0,0 +1,126 @@ +// Copyright © 2019 The Knative 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 flags + +import ( + "fmt" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/spf13/pflag" +) + +var ( + negPrefix = "no-" +) + +// AddBothBoolFlagsUnhidden is just like AddBothBoolFlags but shows both flags. +func AddBothBoolFlagsUnhidden(f *pflag.FlagSet, p *bool, name, short string, value bool, usage string) { + + negativeName := negPrefix + name + + f.BoolVarP(p, name, short, value, usage) + f.Bool(negativeName, !value, InvertUsage(usage)) +} + +// AddBothBoolFlags adds the given flag in both `--foo` and `--no-foo` variants. +// If you do this, make sure you call ReconcileBoolFlags later to catch errors +// and set the relationship between the flag values. Only the flag that does the +// non-default behavior is visible; the other is hidden. +func AddBothBoolFlags(f *pflag.FlagSet, p *bool, name, short string, value bool, usage string) { + AddBothBoolFlagsUnhidden(f, p, name, short, value, usage) + negativeName := negPrefix + name + if value { + err := f.MarkHidden(name) + if err != nil { + panic(err) + } + } else { + err := f.MarkHidden(negativeName) + if err != nil { + panic(err) + } + } +} + +// ReconcileBoolFlags sets the value of the all the "--foo" flags based on +// "--no-foo" if provided, and returns an error if both were provided or an +// explicit value of false was provided to either (as that's confusing). +func ReconcileBoolFlags(f *pflag.FlagSet) error { + var err error + f.VisitAll(func(flag *pflag.Flag) { + // Return early from our comprehension + if err != nil { + return + } + + // Walk the "no-" versions of the flags. Make sure we didn't set + // both, and set the positive value to the opposite of the "no-" + // value if it exists. + if strings.HasPrefix(flag.Name, negPrefix) { + positiveName := flag.Name[len(negPrefix):] + positive := f.Lookup(positiveName) + // Non-paired flag, or wrong types + if positive == nil || positive.Value.Type() != "bool" || flag.Value.Type() != "bool" { + return + } + if flag.Changed { + if positive.Changed { + err = fmt.Errorf("only one of --%s and --%s may be specified", + flag.Name, positiveName) + return + } + err = checkExplicitFalse(flag, positiveName) + if err != nil { + return + } + err = positive.Value.Set("false") + } else { + err = checkExplicitFalse(positive, flag.Name) + } + } + + }) + return err +} + +// checkExplicitFalse returns an error if the flag was explicitly set to false. +func checkExplicitFalse(f *pflag.Flag, betterFlag string) error { + if !f.Changed { + return nil + } + val, err := strconv.ParseBool(f.Value.String()) + if err != nil { + return err + } + if !val { + return fmt.Errorf("use --%s instead of providing \"%s\" to --%s", + betterFlag, f.Value.String(), f.Name) + } + return nil +} + +// FirstCharToLower converts first char in given string to lowercase +func FirstCharToLower(s string) string { + r, n := utf8.DecodeRuneInString(s) + return string(unicode.ToLower(r)) + s[n:] +} + +// InvertUsage inverts the usage string with prefix "Do not" +func InvertUsage(usage string) string { + return "Do not " + FirstCharToLower(usage) +} diff --git a/vendor/knative.dev/client-pkg/pkg/flags/podspec_helper.go b/vendor/knative.dev/client-pkg/pkg/flags/podspec_helper.go new file mode 100644 index 0000000000..d1d9f1b4b8 --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/flags/podspec_helper.go @@ -0,0 +1,1127 @@ +// Copyright © 2020 The Knative 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 flags + +import ( + "fmt" + "os" + "strconv" + "strings" + + "k8s.io/utils/pointer" + + "k8s.io/apimachinery/pkg/util/intstr" + + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/util/yaml" + + corev1 "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/util/sets" + "knative.dev/client-pkg/pkg/util" +) + +// VolumeSourceType is a type standing for enumeration of ConfigMap and Secret +type VolumeSourceType int + +// Enumeration of volume source types: ConfigMap or Secret +const ( + ConfigMapVolumeSourceType VolumeSourceType = iota + SecretVolumeSourceType + EmptyDirVolumeSourceType + PVCVolumeSourceType + PortFormatErr = "the port specification '%s' is not valid. Please provide in the format 'NAME:PORT', where 'NAME' is optional. Examples: '--port h2c:8080' , '--port 8080'." +) + +type MountInfo struct { + VolumeName string + SubPath string + MountOptions string +} + +func (vt VolumeSourceType) String() string { + names := [...]string{"config-map", "secret"} + if vt < ConfigMapVolumeSourceType || vt > SecretVolumeSourceType { + return "unknown" + } + return names[vt] +} + +func containerOfPodSpec(spec *corev1.PodSpec) *corev1.Container { + if len(spec.Containers) == 0 { + newContainer := corev1.Container{} + spec.Containers = append(spec.Containers, newContainer) + } + return &spec.Containers[0] +} + +// UpdateEnvVars gives the configuration all the env var values listed in the given map of +// vars. Does not touch any environment variables not mentioned, but it can add +// new env vars and change the values of existing ones. +func UpdateEnvVars(spec *corev1.PodSpec, allArgs []string, + envToUpdate *util.OrderedMap, envToRemove []string, + envValueFromToUpdate *util.OrderedMap, envValueFromToRemove []string, + envFileName string, envValueFileToUpdate *util.OrderedMap, envValueFileToRemove []string, +) error { + container := containerOfPodSpec(spec) + + allEnvsToUpdate := util.NewOrderedMap() + + envIterator := envToUpdate.Iterator() + envValueFromIterator := envValueFromToUpdate.Iterator() + envValueFileIterator := envValueFileToUpdate.Iterator() + + envKey, envValue, envExists := envIterator.NextString() + envValueFromKey, envValueFromValue, envValueFromExists := envValueFromIterator.NextString() + envValueFileKey, envValueFileValue, envValueFileExists := envValueFileIterator.NextString() + for _, arg := range allArgs { + // envs are stored as NAME=value + if envExists && isValidEnvArg(arg, envKey, envValue) { + allEnvsToUpdate.Set(envKey, corev1.EnvVar{ + Name: envKey, + Value: envValue, + }) + envKey, envValue, envExists = envIterator.NextString() + } else if envValueFromExists && isValidEnvValueFromArg(arg, envValueFromKey, envValueFromValue) { + // envs are stored as NAME=secret:sercretName:key or NAME=config-map:cmName:key + envVarSource, err := createEnvVarSource(envValueFromValue) + if err != nil { + return err + } + allEnvsToUpdate.Set(envValueFromKey, corev1.EnvVar{ + Name: envValueFromKey, + ValueFrom: envVarSource, + }) + envValueFromKey, envValueFromValue, envValueFromExists = envValueFromIterator.NextString() + } else if envValueFileExists && isValidEnvValueFileArg(arg, envFileName) { + for envValueFileExists { + allEnvsToUpdate.Set(envValueFileKey, corev1.EnvVar{ + Name: envValueFileKey, + Value: envValueFileValue, + }) + envValueFileKey, envValueFileValue, envValueFileExists = envValueFileIterator.NextString() + } + } + } + + updated := updateEnvVarsFromMap(container.Env, allEnvsToUpdate) + updated = removeEnvVars(updated, append(envToRemove, envValueFromToRemove...)) + + container.Env = updated + + return nil +} + +// isValidEnvArg checks that the input arg is a valid argument for specifying env value, +// ie. stored as NAME=value +func isValidEnvArg(arg, envKey, envValue string) bool { + return strings.HasPrefix(arg, envKey+"="+envValue) || strings.HasPrefix(arg, "-e="+envKey+"="+envValue) || strings.HasPrefix(arg, "--env="+envKey+"="+envValue) +} + +// isValidEnvValueFromArg checks that the input arg is a valid argument for specifying env from value, +// ie. stored as NAME=secret:sercretName:key or NAME=config-map:cmName:key +func isValidEnvValueFromArg(arg, envValueFromKey, envValueFromValue string) bool { + return strings.HasPrefix(arg, envValueFromKey+"="+envValueFromValue) || strings.HasPrefix(arg, "--env-value-from="+envValueFromKey+"="+envValueFromValue) +} + +// isValidEnvValueFileArg checks that the input arg is a valid argument for specifying env from value, +// ie. stored as NAME=secret:sercretName:key or NAME=config-map:cmName:key +func isValidEnvValueFileArg(arg, envFileName string) bool { + return strings.HasPrefix(arg, envFileName) || strings.HasPrefix(arg, "--env-file="+envFileName) +} + +// UpdateEnvFrom updates envFrom +func UpdateEnvFrom(spec *corev1.PodSpec, toUpdate []string, toRemove []string) error { + container := containerOfPodSpec(spec) + envFrom, err := updateEnvFrom(container.EnvFrom, toUpdate) + if err != nil { + return err + } + container.EnvFrom, err = removeEnvFrom(envFrom, toRemove) + return err +} + +// UpdateVolumeMountsAndVolumes updates the configuration for volume mounts and volumes. +func UpdateVolumeMountsAndVolumes(spec *corev1.PodSpec, + mountsToUpdate *util.OrderedMap, mountsToRemove []string, volumesToUpdate *util.OrderedMap, volumesToRemove []string) error { + container := containerOfPodSpec(spec) + + volumeSourceInfoByName, mountsToUpdate, err := reviseVolumeInfoAndMountsToUpdate(mountsToUpdate, volumesToUpdate) + if err != nil { + return err + } + + volumes, err := updateVolumesFromMap(spec.Volumes, volumeSourceInfoByName) + if err != nil { + return err + } + + volumeMounts, err := updateVolumeMountsFromMap(container.VolumeMounts, mountsToUpdate, volumes) + if err != nil { + return err + } + + volumesToRemove = reviseVolumesToRemove(container.VolumeMounts, volumesToRemove, mountsToRemove) + + container.VolumeMounts = removeVolumeMounts(volumeMounts, mountsToRemove) + spec.Volumes, err = removeVolumes(volumes, volumesToRemove, container.VolumeMounts) + + return err +} + +// UpdateImage a given image +func UpdateImage(spec *corev1.PodSpec, image string) error { + // When not setting the image to a digest, add the user image annotation. + container := containerOfPodSpec(spec) + container.Image = image + return nil +} + +// UpdateContainerCommand updates container with a given argument +func UpdateContainerCommand(spec *corev1.PodSpec, command []string) error { + container := containerOfPodSpec(spec) + container.Command = command + return nil +} + +// UpdateContainerArg updates container with a given argument +func UpdateContainerArg(spec *corev1.PodSpec, arg []string) error { + container := containerOfPodSpec(spec) + container.Args = arg + return nil +} + +// UpdateContainerPort updates container with a given name:port +func UpdateContainerPort(spec *corev1.PodSpec, port string) error { + container := containerOfPodSpec(spec) + + var containerPort int64 + var name string + var err error + + elements := strings.SplitN(port, ":", 2) + if len(elements) == 2 { + name = elements[0] + containerPort, err = strconv.ParseInt(elements[1], 10, 32) + if err != nil { + return fmt.Errorf(PortFormatErr, port) + } + } else { + name = "" + containerPort, err = strconv.ParseInt(elements[0], 10, 32) + if err != nil { + return fmt.Errorf(PortFormatErr, port) + } + } + + container.Ports = []corev1.ContainerPort{{ + ContainerPort: int32(containerPort), + Name: name, + }} + return nil +} + +// UpdateUser updates container with a given user id +func UpdateUser(spec *corev1.PodSpec, user int64) error { + container := containerOfPodSpec(spec) + container.SecurityContext = &corev1.SecurityContext{ + RunAsUser: &user, + } + return nil +} + +// UpdateResources updates container resources for given revision spec +func UpdateResources(spec *corev1.PodSpec, resources corev1.ResourceRequirements, requestsToRemove, limitsToRemove []string) error { + container := containerOfPodSpec(spec) + + if container.Resources.Requests == nil { + container.Resources.Requests = corev1.ResourceList{} + } + + for k, v := range resources.Requests { + container.Resources.Requests[k] = v + } + + for _, reqToRemove := range requestsToRemove { + delete(container.Resources.Requests, corev1.ResourceName(reqToRemove)) + } + + if container.Resources.Limits == nil { + container.Resources.Limits = corev1.ResourceList{} + } + + for k, v := range resources.Limits { + container.Resources.Limits[k] = v + } + + for _, limToRemove := range limitsToRemove { + delete(container.Resources.Limits, corev1.ResourceName(limToRemove)) + } + + return nil +} + +// UpdateServiceAccountName updates the service account name used for the corresponding knative service +func UpdateServiceAccountName(spec *corev1.PodSpec, serviceAccountName string) { + serviceAccountName = strings.TrimSpace(serviceAccountName) + spec.ServiceAccountName = serviceAccountName +} + +// UpdateImagePullSecrets updates the image pull secrets used for the corresponding knative service +func UpdateImagePullSecrets(spec *corev1.PodSpec, pullsecrets string) { + pullsecrets = strings.TrimSpace(pullsecrets) + if pullsecrets == "" { + spec.ImagePullSecrets = nil + } else { + spec.ImagePullSecrets = []corev1.LocalObjectReference{{ + Name: pullsecrets, + }} + } +} + +// UpdateContainers updates the containers array with additional ones provided from file or os.Stdin +func UpdateContainers(spec *corev1.PodSpec, containers []corev1.Container) { + var matched []string + if len(spec.Containers) == 1 { + spec.Containers = append(spec.Containers, containers...) + } else { + for i, container := range spec.Containers { + for j, toUpdate := range containers { + if container.Name == toUpdate.Name { + + spec.Containers[i] = containers[j] + + matched = append(matched, toUpdate.Name) + } + } + } + for _, container := range containers { + if !util.SliceContainsIgnoreCase(matched, container.Name) { + spec.Containers = append(spec.Containers, container) + } + } + } +} + +// UpdateLivenessProbe updates container liveness probe based on provided string +func UpdateLivenessProbe(spec *corev1.PodSpec, probeString string) error { + c := containerOfPodSpec(spec) + handler, err := resolveProbeHandler(probeString) + if err != nil { + return err + } + if c.LivenessProbe == nil { + c.LivenessProbe = &corev1.Probe{} + } + c.LivenessProbe.ProbeHandler = *handler + return nil +} + +// UpdateLivenessProbeOpts updates container liveness probe commons options based on provided string +func UpdateLivenessProbeOpts(spec *corev1.PodSpec, probeString string) error { + c := containerOfPodSpec(spec) + if c.LivenessProbe == nil { + c.LivenessProbe = &corev1.Probe{} + } + err := resolveProbeOptions(c.LivenessProbe, probeString) + if err != nil { + return err + } + return nil +} + +// UpdateReadinessProbe updates container readiness probe based on provided string +func UpdateReadinessProbe(spec *corev1.PodSpec, probeString string) error { + c := containerOfPodSpec(spec) + handler, err := resolveProbeHandler(probeString) + if err != nil { + return err + } + if c.ReadinessProbe == nil { + c.ReadinessProbe = &corev1.Probe{} + } + c.ReadinessProbe.ProbeHandler = *handler + return nil +} + +// UpdateReadinessProbeOpts updates container readiness probe commons options based on provided string +func UpdateReadinessProbeOpts(spec *corev1.PodSpec, probeString string) error { + c := containerOfPodSpec(spec) + if c.ReadinessProbe == nil { + c.ReadinessProbe = &corev1.Probe{} + } + err := resolveProbeOptions(c.ReadinessProbe, probeString) + if err != nil { + return err + } + return nil +} + +// UpdateImagePullPolicy updates the pull policy for the given revision template +func UpdateImagePullPolicy(spec *corev1.PodSpec, imagePullPolicy string) error { + container := containerOfPodSpec(spec) + + if !isValidPullPolicy(imagePullPolicy) { + return fmt.Errorf("invalid --pull-policy %s. Valid arguments (case insensitive): Always | Never | IfNotPresent", imagePullPolicy) + } + container.ImagePullPolicy = getPolicy(imagePullPolicy) + return nil +} + +// UpdateSecurityContext update the Security Context +func UpdateSecurityContext(spec *corev1.PodSpec, securityContext string) error { + container := containerOfPodSpec(spec) + switch strings.ToLower(securityContext) { + case "none": + // Blank any Security Context defined + container.SecurityContext = nil + case "strict": + // Add or update Security Context to default strict + container.SecurityContext = DefaultStrictSecCon() + //TODO(dsimansk): add parsing of SC options from the flag value + default: + return fmt.Errorf("invalid --security-context %s. Valid arguments: strict | none", securityContext) + } + return nil +} + +// DefaultStrictSecCon helper function to get default strict Security Context +func DefaultStrictSecCon() *corev1.SecurityContext { + return &corev1.SecurityContext{ + AllowPrivilegeEscalation: pointer.Bool(false), + RunAsNonRoot: pointer.Bool(true), + Capabilities: &corev1.Capabilities{ + Drop: []corev1.Capability{"ALL"}, + }, + SeccompProfile: &corev1.SeccompProfile{ + Type: corev1.SeccompProfileTypeRuntimeDefault, + }, + } +} + +func getPolicy(policy string) v1.PullPolicy { + var ret v1.PullPolicy + switch strings.ToLower(policy) { + case "always": + ret = v1.PullAlways + case "ifnotpresent": + ret = v1.PullIfNotPresent + case "never": + ret = v1.PullNever + } + return ret +} + +func isValidPullPolicy(policy string) bool { + validPolicies := []string{string(v1.PullAlways), string(v1.PullNever), string(v1.PullIfNotPresent)} + return util.SliceContainsIgnoreCase(validPolicies, policy) +} + +// ======================================================================================= +func updateEnvVarsFromMap(env []corev1.EnvVar, toUpdate *util.OrderedMap) []corev1.EnvVar { + updated := sets.NewString() + + for i := range env { + object, present := toUpdate.Get(env[i].Name) + if present { + env[i] = object.(corev1.EnvVar) + updated.Insert(env[i].Name) + } + } + it := toUpdate.Iterator() + for name, envVar, ok := it.Next(); ok; name, envVar, ok = it.Next() { + if !updated.Has(name) { + env = append(env, envVar.(corev1.EnvVar)) + } + } + return env +} + +func removeEnvVars(env []corev1.EnvVar, toRemove []string) []corev1.EnvVar { + for _, name := range toRemove { + for i, envVar := range env { + if envVar.Name == name { + env = append(env[:i], env[i+1:]...) + break + } + } + } + return env +} + +func createEnvVarSource(spec string) (*corev1.EnvVarSource, error) { + slices := strings.SplitN(spec, ":", 3) + if len(slices) != 3 { + return nil, fmt.Errorf("argument requires a value in form \"resourceType:name:key\" where \"resourceType\" can be one of \"config-map\" (\"cm\") or \"secret\" (\"sc\"); got %q", spec) + } + + typeString := strings.TrimSpace(slices[0]) + sourceName := strings.TrimSpace(slices[1]) + sourceKey := strings.TrimSpace(slices[2]) + + var sourceType string + envVarSource := corev1.EnvVarSource{} + + switch typeString { + case "config-map", "cm": + sourceType = "ConfigMap" + envVarSource.ConfigMapKeyRef = &corev1.ConfigMapKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: sourceName, + }, + Key: sourceKey} + case "secret", "sc": + sourceType = "Secret" + envVarSource.SecretKeyRef = &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: sourceName, + }, + Key: sourceKey} + default: + return nil, fmt.Errorf("unsupported env source type \"%q\"; supported source types are \"config-map\" (\"cm\") and \"secret\" (\"sc\")", slices[0]) + } + + if len(sourceName) == 0 { + return nil, fmt.Errorf("the name of %s cannot be an empty string", sourceType) + } + + if len(sourceKey) == 0 { + return nil, fmt.Errorf("the key referenced by resource %s \"%s\" cannot be an empty string", sourceType, sourceName) + } + + return &envVarSource, nil +} + +// ======================================================================================= +func updateEnvFrom(envFromSources []corev1.EnvFromSource, toUpdate []string) ([]corev1.EnvFromSource, error) { + existingNameSet := make(map[string]bool) + + for i := range envFromSources { + envSrc := &envFromSources[i] + if canonicalName, err := getCanonicalNameFromEnvFromSource(envSrc); err == nil { + existingNameSet[canonicalName] = true + } + } + + for _, s := range toUpdate { + info, err := newVolumeSourceInfoWithSpecString(s) + if err != nil { + return nil, err + } + + if _, ok := existingNameSet[info.getCanonicalName()]; !ok { + envFromSources = append(envFromSources, *info.createEnvFromSource()) + } + } + + return envFromSources, nil +} + +func removeEnvFrom(envFromSources []corev1.EnvFromSource, toRemove []string) ([]corev1.EnvFromSource, error) { + for _, name := range toRemove { + info, err := newVolumeSourceInfoWithSpecString(name) + if err != nil { + return nil, err + } + for i, envSrc := range envFromSources { + if (info.volumeSourceType == ConfigMapVolumeSourceType && envSrc.ConfigMapRef != nil && info.volumeSourceName == envSrc.ConfigMapRef.Name) || + (info.volumeSourceType == SecretVolumeSourceType && envSrc.SecretRef != nil && info.volumeSourceName == envSrc.SecretRef.Name) { + envFromSources = append(envFromSources[:i], envFromSources[i+1:]...) + break + } + } + } + + if len(envFromSources) == 0 { + envFromSources = nil + } + + return envFromSources, nil +} + +func updateVolume(volume *corev1.Volume, info *volumeSourceInfo) error { + switch info.volumeSourceType { + case ConfigMapVolumeSourceType: + volume.Secret = nil + volume.ConfigMap = &corev1.ConfigMapVolumeSource{LocalObjectReference: corev1.LocalObjectReference{Name: info.volumeSourceName}} + case SecretVolumeSourceType: + volume.ConfigMap = nil + volume.Secret = &corev1.SecretVolumeSource{SecretName: info.volumeSourceName} + case EmptyDirVolumeSourceType: + volume.EmptyDir = &corev1.EmptyDirVolumeSource{Medium: corev1.StorageMedium(info.emptyDirMemoryType), SizeLimit: info.emptyDirSize} + case PVCVolumeSourceType: + volume.PersistentVolumeClaim = &corev1.PersistentVolumeClaimVolumeSource{ClaimName: info.volumeSourceName} + default: + return fmt.Errorf("Invalid VolumeSourceType") + } + return nil +} + +// updateVolumeMountsFromMap updates or adds volume mounts. If a given name of a volume is not existing, it returns an error +func updateVolumeMountsFromMap(volumeMounts []corev1.VolumeMount, toUpdate *util.OrderedMap, volumes []corev1.Volume) ([]corev1.VolumeMount, error) { + set := make(map[string]bool) + + var err error + for i := range volumeMounts { + volumeMount := &volumeMounts[i] + mountInfo, present := toUpdate.Get(volumeMount.MountPath) + + if present { + volumeMountInfo := mountInfo.(*MountInfo) + name := volumeMountInfo.VolumeName + if !existsVolumeNameInVolumes(name, volumes) { + return nil, fmt.Errorf("There is no volume matched with %q", name) + } + volumeMount.ReadOnly, err = isReadOnlyVolume(name, volumeMountInfo.MountOptions, volumes) + if err != nil { + return nil, err + } + volumeMount.Name = name + volumeMount.SubPath = volumeMountInfo.SubPath + set[volumeMount.MountPath] = true + } + } + + it := toUpdate.Iterator() + for mountPath, mountInfo, ok := it.Next(); ok; mountPath, mountInfo, ok = it.Next() { + volumeMountInfo := mountInfo.(*MountInfo) + name := volumeMountInfo.VolumeName + readOnly, err := isReadOnlyVolume(name, volumeMountInfo.MountOptions, volumes) + if err != nil { + return nil, err + } + if !set[mountPath] { + volumeMounts = append(volumeMounts, corev1.VolumeMount{ + Name: name, + ReadOnly: readOnly, + MountPath: mountPath, + SubPath: volumeMountInfo.SubPath, + }) + } + } + + return volumeMounts, nil +} + +func removeVolumeMounts(volumeMounts []corev1.VolumeMount, toRemove []string) []corev1.VolumeMount { + for _, mountPath := range toRemove { + for i, volumeMount := range volumeMounts { + if volumeMount.MountPath == mountPath { + volumeMounts = append(volumeMounts[:i], volumeMounts[i+1:]...) + break + } + } + } + + if len(volumeMounts) == 0 { + return nil + } + + return volumeMounts +} + +// updateVolumesFromMap updates or adds volumes regardless whether the volume is used or not +func updateVolumesFromMap(volumes []corev1.Volume, toUpdate *util.OrderedMap) ([]corev1.Volume, error) { + set := make(map[string]bool) + + for i := range volumes { + volume := &volumes[i] + info, present := toUpdate.Get(volume.Name) + if present { + err := updateVolume(volume, info.(*volumeSourceInfo)) + if err != nil { + return nil, err + } + set[volume.Name] = true + } + } + + it := toUpdate.Iterator() + for name, info, ok := it.Next(); ok; name, info, ok = it.Next() { + if !set[name] { + volumes = append(volumes, corev1.Volume{Name: name}) + updateVolume(&volumes[len(volumes)-1], info.(*volumeSourceInfo)) + } + } + + return volumes, nil +} + +// removeVolumes removes volumes. If there is a volume mount referencing the volume, it causes an error +func removeVolumes(volumes []corev1.Volume, toRemove []string, volumeMounts []corev1.VolumeMount) ([]corev1.Volume, error) { + for _, name := range toRemove { + for i, volume := range volumes { + if volume.Name == name { + if existsVolumeNameInVolumeMounts(name, volumeMounts) { + return nil, fmt.Errorf("The volume %q cannot be removed because it is mounted", name) + } + volumes = append(volumes[:i], volumes[i+1:]...) + break + } + } + } + + if len(volumes) == 0 { + return nil, nil + } + + return volumes, nil +} + +// ======================================================================================= + +type volumeSourceInfo struct { + volumeSourceType VolumeSourceType + volumeSourceName string + emptyDirMemoryType string + emptyDirSize *resource.Quantity +} + +func newVolumeSourceInfoWithSpecString(spec string) (*volumeSourceInfo, error) { + slices := strings.SplitN(spec, ":", 3) + if len(slices) < 2 { + return nil, fmt.Errorf("argument requires a value that contains the : character; got %q, %q", spec, slices) + } + + if len(slices) == 2 { + var volumeSourceType VolumeSourceType + + typeString := strings.TrimSpace(slices[0]) + volumeSourceName := strings.TrimSpace(slices[1]) + + switch typeString { + case "config-map", "cm": + volumeSourceType = ConfigMapVolumeSourceType + case "secret", "sc": + volumeSourceType = SecretVolumeSourceType + case "emptyDir", "ed": + volumeSourceType = EmptyDirVolumeSourceType + case "persistentVolumeClaim", "pvc": + volumeSourceType = PVCVolumeSourceType + default: + return nil, fmt.Errorf("unsupported volume source type \"%q\"; supported volume source types are \"config-map\" and \"secret\"", slices[0]) + } + + if len(volumeSourceName) == 0 { + return nil, fmt.Errorf("the name of %s cannot be an empty string", volumeSourceType) + } + + return &volumeSourceInfo{ + volumeSourceType: volumeSourceType, + volumeSourceName: volumeSourceName, + }, nil + } else { + typeString := strings.TrimSpace(slices[0]) + switch typeString { + case "config-map", "cm", "secret", "sc", "persistentVolumeClaim", "pvc": + return nil, fmt.Errorf("incorrect mount details for type %q", typeString) + case "emptyDir", "ed": + volName := slices[1] + edType, edSize, err := getEmptyDirTypeAndSize(slices[2]) + if err != nil { + return nil, err + } + return &volumeSourceInfo{ + volumeSourceType: EmptyDirVolumeSourceType, + volumeSourceName: volName, + emptyDirMemoryType: edType, + emptyDirSize: edSize, + }, nil + default: + return nil, fmt.Errorf("unsupported volume type \"%q\"; supported volume types are \"config-map or cm\", \"secret or sc\", \"volume or vo\", and \"emptyDir or ed\"", slices[0]) + } + + } +} + +func (vol *volumeSourceInfo) getCanonicalName() string { + return fmt.Sprintf("%s:%s", vol.volumeSourceType, vol.volumeSourceName) +} + +func getCanonicalNameFromEnvFromSource(envSrc *corev1.EnvFromSource) (string, error) { + if envSrc.ConfigMapRef != nil { + return fmt.Sprintf("%s:%s", ConfigMapVolumeSourceType, envSrc.ConfigMapRef.Name), nil + } + if envSrc.SecretRef != nil { + return fmt.Sprintf("%s:%s", SecretVolumeSourceType, envSrc.SecretRef.Name), nil + } + + return "", fmt.Errorf("there is no ConfigMapRef or SecretRef in a EnvFromSource") +} + +func (vol *volumeSourceInfo) createEnvFromSource() *corev1.EnvFromSource { + switch vol.volumeSourceType { + case ConfigMapVolumeSourceType: + return &corev1.EnvFromSource{ + ConfigMapRef: &corev1.ConfigMapEnvSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: vol.volumeSourceName, + }}} + case SecretVolumeSourceType: + return &corev1.EnvFromSource{ + SecretRef: &corev1.SecretEnvSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: vol.volumeSourceName, + }}} + } + + return nil +} + +// ======================================================================================= + +func isReadOnlyVolume(volumeName string, mountOptions string, volumes []corev1.Volume) (bool, error) { + if mountOptions != "" { + options, err := parseMountOptions(mountOptions) + if err != nil { + return false, err + } + if val, ok := options.Get("readonly"); ok && val != "" { + return strconv.ParseBool(val.(string)) + } + } + for _, volume := range volumes { + if volume.Name == volumeName { + return defaultReadOnly(volume), nil + } + } + return true, nil +} + +func parseMountOptions(options string) (*util.OrderedMap, error) { + mountOptions := util.NewOrderedMap() + slices := strings.Split(options, ",") + for _, slice := range slices { + pair := strings.SplitN(slice, "=", 2) + switch strings.ToLower(pair[0]) { + case "readonly": + mountOptions.Set("readonly", pair[1]) + default: + return nil, fmt.Errorf("unknown mount option %q", pair[0]) + } + } + return mountOptions, nil +} + +func defaultReadOnly(volume v1.Volume) bool { + if volume.EmptyDir != nil || volume.PersistentVolumeClaim != nil { + return false + } + return true +} + +func existsVolumeNameInVolumes(volumeName string, volumes []corev1.Volume) bool { + for _, volume := range volumes { + if volume.Name == volumeName { + return true + } + } + return false +} + +func existsVolumeNameInVolumeMounts(volumeName string, volumeMounts []corev1.VolumeMount) bool { + for _, volumeMount := range volumeMounts { + if volumeMount.Name == volumeName { + return true + } + } + return false +} + +// ======================================================================================= + +func getMountInfo(volume string) *MountInfo { + configSlices := strings.SplitN(volume, ":", 2) + var mountInfo MountInfo + if len(configSlices) == 2 { + readOnlySlices := strings.SplitN(configSlices[1], "=", 2) + switch strings.ToLower(readOnlySlices[0]) { + case "readonly": + + } + mountInfo.MountOptions = configSlices[1] + } + slices := strings.SplitN(configSlices[0], "/", 2) + if len(slices) == 1 || slices[1] == "" { + mountInfo.VolumeName = slices[0] + } else { + mountInfo.VolumeName = slices[0] + mountInfo.SubPath = slices[1] + } + return &mountInfo +} + +func reviseVolumeInfoAndMountsToUpdate(mountsToUpdate *util.OrderedMap, volumesToUpdate *util.OrderedMap) (*util.OrderedMap, *util.OrderedMap, error) { + volumeSourceInfoByName := util.NewOrderedMap() //make(map[string]*volumeSourceInfo) + mountsToUpdateRevised := util.NewOrderedMap() //make(map[string]string) + + it := mountsToUpdate.Iterator() + for path, value, ok := it.NextString(); ok; path, value, ok = it.NextString() { + // slices[0] -> config-map, cm, secret, sc, volume, or vo + // slices[1] -> secret, config-map, or volume name + slices := strings.SplitN(value, ":", 2) + if len(slices) == 1 { + mountInfo := getMountInfo(slices[0]) + mountsToUpdateRevised.Set(path, mountInfo) + } else { + switch volumeType := slices[0]; volumeType { + case "config-map", "cm": + generatedName := util.GenerateVolumeName(path) + mountInfo := getMountInfo(slices[1]) + volumeSourceInfoByName.Set(generatedName, &volumeSourceInfo{ + volumeSourceType: ConfigMapVolumeSourceType, + volumeSourceName: mountInfo.VolumeName, + }) + mountInfo.VolumeName = generatedName + mountsToUpdateRevised.Set(path, mountInfo) + case "secret", "sc": + generatedName := util.GenerateVolumeName(path) + mountInfo := getMountInfo(slices[1]) + volumeSourceInfoByName.Set(generatedName, &volumeSourceInfo{ + volumeSourceType: SecretVolumeSourceType, + volumeSourceName: mountInfo.VolumeName, + }) + mountInfo.VolumeName = generatedName + mountsToUpdateRevised.Set(path, mountInfo) + case "emptyDir", "ed": + generatedName := util.GenerateVolumeName(path) + mountInfo := getMountInfo(slices[1]) + volumeSourceInfoByName.Set(generatedName, &volumeSourceInfo{ + volumeSourceType: EmptyDirVolumeSourceType, + volumeSourceName: slices[1], + emptyDirMemoryType: "", + }) + mountInfo.VolumeName = generatedName + mountsToUpdateRevised.Set(path, mountInfo) + case "persistentVolumeClaim", "pvc": + generatedName := util.GenerateVolumeName(path) + mountInfo := getMountInfo(slices[1]) + volumeSourceInfoByName.Set(generatedName, &volumeSourceInfo{ + volumeSourceType: PVCVolumeSourceType, + volumeSourceName: mountInfo.VolumeName, + }) + mountInfo.VolumeName = generatedName + mountsToUpdateRevised.Set(path, mountInfo) + default: + return nil, nil, fmt.Errorf("unsupported volume type \"%q\"; supported volume types are \"config-map or cm\", \"secret or sc\", \"volume or vo\", and \"emptyDir or ed\"", slices[0]) + } + } + } + + it = volumesToUpdate.Iterator() + for name, value, ok := it.NextString(); ok; name, value, ok = it.NextString() { + info, err := newVolumeSourceInfoWithSpecString(value) + if err != nil { + return nil, nil, err + } + volumeSourceInfoByName.Set(name, info) + } + + return volumeSourceInfoByName, mountsToUpdateRevised, nil +} + +func getEmptyDirTypeAndSize(value string) (string, *resource.Quantity, error) { + slices := strings.SplitN(value, ",", 2) + formatErr := fmt.Errorf("incorrect format to specify emptyDir type") + repeatErrStr := "cannot repeat the key %q" + var dirType string + var size *resource.Quantity + switch len(slices) { + case 0: + return "", nil, nil + case 1: + typeSizeSlices := strings.SplitN(slices[0], "=", 2) + if len(typeSizeSlices) < 2 { + return "", nil, formatErr + } + switch strings.ToLower(typeSizeSlices[0]) { + case "type": + dirType = typeSizeSlices[1] + case "size": + quantity, err := resource.ParseQuantity(typeSizeSlices[1]) + if err != nil { + return "", nil, formatErr + } + size = &quantity + default: + return "", nil, formatErr + } + case 2: + for _, slice := range slices { + typeSizeSlices := strings.SplitN(slice, "=", 2) + if len(typeSizeSlices) < 2 { + return "", nil, formatErr + } + switch strings.ToLower(typeSizeSlices[0]) { + case "type": + if dirType != "" { + return "", nil, fmt.Errorf(repeatErrStr, "type") + } + dirType = typeSizeSlices[1] + case "size": + if size != nil { + return "", nil, fmt.Errorf(repeatErrStr, "size") + } + quantity, err := resource.ParseQuantity(typeSizeSlices[1]) + if err != nil { + return "", nil, formatErr + } + size = &quantity + default: + return "", nil, formatErr + } + } + } + return dirType, size, nil +} + +func reviseVolumesToRemove(volumeMounts []corev1.VolumeMount, volumesToRemove []string, mountsToRemove []string) []string { + for _, pathToRemove := range mountsToRemove { + for _, volumeMount := range volumeMounts { + if volumeMount.MountPath == pathToRemove && volumeMount.Name == util.GenerateVolumeName(pathToRemove) { + volumesToRemove = append(volumesToRemove, volumeMount.Name) + } + } + } + return volumesToRemove +} + +func decodeContainersFromFile(filename string) (*corev1.PodSpec, error) { + var f *os.File + var err error + if filename == "-" { + f = os.Stdin + } else { + f, err = os.Open(filename) + if err != nil { + return nil, err + } + } + podSpec := &corev1.PodSpec{} + decoder := yaml.NewYAMLOrJSONDecoder(f, 512) + if err = decoder.Decode(podSpec); err != nil { + return nil, err + } + return podSpec, nil +} + +// ======================================================================================= +// Probes + +// resolveProbe parses probes as a string +// It's split into two functions: +// - resolveProbeOptions() -> common probe opts +// - resolveProbeHandler() -> probe handler [HTTPGet, Exec, TCPSocket] +// Format: +// - [http,https]:host:port:path +// - exec:cmd,cmd,... +// - tcp:host:port +// Common opts (comma separated, case insensitive): +// - InitialDelaySeconds=,FailureThreshold=, +// SuccessThreshold=,PeriodSeconds==,TimeoutSeconds= + +// resolveProbeOptions parses probe commons options +func resolveProbeOptions(probe *corev1.Probe, probeString string) error { + options := strings.Split(probeString, ",") + mappedOptions, err := util.MapFromArray(options, "=") + if err != nil { + return err + } + for k, v := range mappedOptions { + // Trim & verify value is convertible to int + intValue, err := strconv.ParseInt(strings.TrimSpace(v), 0, 32) + if err != nil { + return fmt.Errorf("not a nummeric value for parameter '%s'", k) + } + // Lower case param name mapping + switch strings.TrimSpace(strings.ToLower(k)) { + case "initialdelayseconds": + probe.InitialDelaySeconds = int32(intValue) + case "timeoutseconds": + probe.TimeoutSeconds = int32(intValue) + case "periodseconds": + probe.PeriodSeconds = int32(intValue) + case "successthreshold": + probe.SuccessThreshold = int32(intValue) + case "failurethreshold": + probe.FailureThreshold = int32(intValue) + default: + return fmt.Errorf("not a valid probe parameter name '%s'", k) + } + } + return nil +} + +// resolveProbeHandler parses probe handler options +func resolveProbeHandler(probeString string) (*corev1.ProbeHandler, error) { + if len(probeString) == 0 { + return nil, fmt.Errorf("no probe parameters detected") + } + probeParts := strings.Split(probeString, ":") + if len(probeParts) > 4 { + return nil, fmt.Errorf("too many probe parameters provided, please check the format") + } + var probeHandler *corev1.ProbeHandler + switch probeParts[0] { + case "http", "https": + if len(probeParts) != 4 { + return nil, fmt.Errorf("unexpected probe format, please use 'http:host:port:path'") + } + handler := corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{}, + } + if probeParts[0] == "https" { + handler.HTTPGet.Scheme = v1.URISchemeHTTPS + } + handler.HTTPGet.Host = probeParts[1] + if probeParts[2] != "" { + // Cosmetic fix to have default 'port: 0' instead of empty string 'port: ""' + handler.HTTPGet.Port = intstr.Parse(probeParts[2]) + } + handler.HTTPGet.Path = probeParts[3] + + probeHandler = &handler + case "exec": + if len(probeParts) != 2 { + return nil, fmt.Errorf("unexpected probe format, please use 'exec:[,,...]'") + } + if len(probeParts[1]) == 0 { + return nil, fmt.Errorf("at least one command parameter is required for Exec probe") + } + handler := corev1.ProbeHandler{ + Exec: &corev1.ExecAction{}, + } + cmd := strings.Split(probeParts[1], ",") + handler.Exec.Command = cmd + + probeHandler = &handler + case "tcp": + if len(probeParts) != 3 { + return nil, fmt.Errorf("unexpected probe format, please use 'tcp:host:port") + } + handler := corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{}, + } + handler.TCPSocket.Host = probeParts[1] + handler.TCPSocket.Port = intstr.Parse(probeParts[2]) + + probeHandler = &handler + default: + return nil, fmt.Errorf("unsupported probe type '%s'; supported types: http, https, exec, tcp", probeParts[0]) + } + return probeHandler, nil +} + +// ======================================================================================= diff --git a/pkg/messaging/v1/channels_client.go b/vendor/knative.dev/client-pkg/pkg/messaging/v1/channels_client.go similarity index 98% rename from pkg/messaging/v1/channels_client.go rename to vendor/knative.dev/client-pkg/pkg/messaging/v1/channels_client.go index 2f996155dc..5a4beb5a28 100644 --- a/pkg/messaging/v1/channels_client.go +++ b/vendor/knative.dev/client-pkg/pkg/messaging/v1/channels_client.go @@ -17,7 +17,7 @@ package v1 import ( "context" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" @@ -26,7 +26,7 @@ import ( messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" clientmessagingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" - knerrors "knative.dev/client/pkg/errors" + knerrors "knative.dev/client-pkg/pkg/errors" ) // KnChannelsClient for interacting with Channels diff --git a/pkg/messaging/v1/channels_client_mock.go b/vendor/knative.dev/client-pkg/pkg/messaging/v1/channels_client_mock.go similarity index 99% rename from pkg/messaging/v1/channels_client_mock.go rename to vendor/knative.dev/client-pkg/pkg/messaging/v1/channels_client_mock.go index bc4cab109c..bb7120e2a4 100644 --- a/pkg/messaging/v1/channels_client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/messaging/v1/channels_client_mock.go @@ -20,7 +20,7 @@ import ( messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" ) type MockKnChannelsClient struct { diff --git a/pkg/messaging/v1/client.go b/vendor/knative.dev/client-pkg/pkg/messaging/v1/client.go similarity index 98% rename from pkg/messaging/v1/client.go rename to vendor/knative.dev/client-pkg/pkg/messaging/v1/client.go index a3bf1064e2..eeadc12e52 100644 --- a/pkg/messaging/v1/client.go +++ b/vendor/knative.dev/client-pkg/pkg/messaging/v1/client.go @@ -21,7 +21,7 @@ import ( "knative.dev/eventing/pkg/client/clientset/versioned/scheme" clientv1beta1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // KnMessagingClient to Eventing Messaging. All methods are relative to diff --git a/pkg/messaging/v1/subscriptions_client.go b/vendor/knative.dev/client-pkg/pkg/messaging/v1/subscriptions_client.go similarity index 98% rename from pkg/messaging/v1/subscriptions_client.go rename to vendor/knative.dev/client-pkg/pkg/messaging/v1/subscriptions_client.go index c52d902bdb..61c4dc5bfc 100644 --- a/pkg/messaging/v1/subscriptions_client.go +++ b/vendor/knative.dev/client-pkg/pkg/messaging/v1/subscriptions_client.go @@ -20,7 +20,7 @@ import ( "context" "fmt" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" "k8s.io/client-go/util/retry" @@ -30,7 +30,7 @@ import ( clientmessagingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" duckv1 "knative.dev/pkg/apis/duck/v1" - knerrors "knative.dev/client/pkg/errors" + knerrors "knative.dev/client-pkg/pkg/errors" ) type SubscriptionUpdateFunc func(origSub *messagingv1.Subscription) (*messagingv1.Subscription, error) diff --git a/pkg/messaging/v1/subscriptions_client_mock.go b/vendor/knative.dev/client-pkg/pkg/messaging/v1/subscriptions_client_mock.go similarity index 99% rename from pkg/messaging/v1/subscriptions_client_mock.go rename to vendor/knative.dev/client-pkg/pkg/messaging/v1/subscriptions_client_mock.go index 11091a03c2..1f84ad8c9f 100644 --- a/pkg/messaging/v1/subscriptions_client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/messaging/v1/subscriptions_client_mock.go @@ -22,7 +22,7 @@ import ( messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" ) type MockKnSubscriptionsClient struct { diff --git a/pkg/printers/interface.go b/vendor/knative.dev/client-pkg/pkg/printers/interface.go similarity index 100% rename from pkg/printers/interface.go rename to vendor/knative.dev/client-pkg/pkg/printers/interface.go diff --git a/pkg/printers/prefixwriter.go b/vendor/knative.dev/client-pkg/pkg/printers/prefixwriter.go similarity index 100% rename from pkg/printers/prefixwriter.go rename to vendor/knative.dev/client-pkg/pkg/printers/prefixwriter.go diff --git a/pkg/printers/tablegenerator.go b/vendor/knative.dev/client-pkg/pkg/printers/tablegenerator.go similarity index 100% rename from pkg/printers/tablegenerator.go rename to vendor/knative.dev/client-pkg/pkg/printers/tablegenerator.go diff --git a/pkg/printers/tableprinter.go b/vendor/knative.dev/client-pkg/pkg/printers/tableprinter.go similarity index 100% rename from pkg/printers/tableprinter.go rename to vendor/knative.dev/client-pkg/pkg/printers/tableprinter.go diff --git a/pkg/printers/tabwriter.go b/vendor/knative.dev/client-pkg/pkg/printers/tabwriter.go similarity index 100% rename from pkg/printers/tabwriter.go rename to vendor/knative.dev/client-pkg/pkg/printers/tabwriter.go diff --git a/pkg/serving/config_changes.go b/vendor/knative.dev/client-pkg/pkg/serving/config_changes.go similarity index 99% rename from pkg/serving/config_changes.go rename to vendor/knative.dev/client-pkg/pkg/serving/config_changes.go index 41287f072c..f16d478f8d 100644 --- a/pkg/serving/config_changes.go +++ b/vendor/knative.dev/client-pkg/pkg/serving/config_changes.go @@ -22,7 +22,7 @@ import ( "strings" "time" - "knative.dev/client/pkg/kn/flags" + "knative.dev/client-pkg/pkg/flags" "knative.dev/pkg/ptr" "knative.dev/serving/pkg/apis/autoscaling" servingconfig "knative.dev/serving/pkg/apis/config" diff --git a/pkg/serving/revision_template.go b/vendor/knative.dev/client-pkg/pkg/serving/revision_template.go similarity index 100% rename from pkg/serving/revision_template.go rename to vendor/knative.dev/client-pkg/pkg/serving/revision_template.go diff --git a/pkg/serving/service.go b/vendor/knative.dev/client-pkg/pkg/serving/service.go similarity index 100% rename from pkg/serving/service.go rename to vendor/knative.dev/client-pkg/pkg/serving/service.go diff --git a/pkg/serving/v1/apply.go b/vendor/knative.dev/client-pkg/pkg/serving/v1/apply.go similarity index 99% rename from pkg/serving/v1/apply.go rename to vendor/knative.dev/client-pkg/pkg/serving/v1/apply.go index 11808b426a..40588d69f4 100644 --- a/pkg/serving/v1/apply.go +++ b/vendor/knative.dev/client-pkg/pkg/serving/v1/apply.go @@ -15,7 +15,7 @@ import ( "k8s.io/apimachinery/pkg/util/jsonmergepatch" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // Copyright © 2020 The Knative Authors diff --git a/pkg/serving/v1/client.go b/vendor/knative.dev/client-pkg/pkg/serving/v1/client.go similarity index 99% rename from pkg/serving/v1/client.go rename to vendor/knative.dev/client-pkg/pkg/serving/v1/client.go index f5c6e964a9..9c83ab5959 100644 --- a/pkg/serving/v1/client.go +++ b/vendor/knative.dev/client-pkg/pkg/serving/v1/client.go @@ -20,7 +20,7 @@ import ( "fmt" "time" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" "k8s.io/client-go/util/retry" @@ -29,9 +29,9 @@ import ( "knative.dev/pkg/apis" "knative.dev/serving/pkg/client/clientset/versioned/scheme" - "knative.dev/client/pkg/serving" - "knative.dev/client/pkg/util" - "knative.dev/client/pkg/wait" + "knative.dev/client-pkg/pkg/serving" + "knative.dev/client-pkg/pkg/util" + "knative.dev/client-pkg/pkg/wait" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" @@ -41,7 +41,7 @@ import ( servingv1 "knative.dev/serving/pkg/apis/serving/v1" clientv1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1" - clienterrors "knative.dev/client/pkg/errors" + clienterrors "knative.dev/client-pkg/pkg/errors" ) // Func signature for an updating function which returns the updated service object diff --git a/pkg/serving/v1/client_mock.go b/vendor/knative.dev/client-pkg/pkg/serving/v1/client_mock.go similarity index 99% rename from pkg/serving/v1/client_mock.go rename to vendor/knative.dev/client-pkg/pkg/serving/v1/client_mock.go index ad2a1fb1b4..f446b8d713 100644 --- a/pkg/serving/v1/client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/serving/v1/client_mock.go @@ -24,8 +24,8 @@ import ( "k8s.io/apimachinery/pkg/labels" servingv1 "knative.dev/serving/pkg/apis/serving/v1" - "knative.dev/client/pkg/util/mock" - "knative.dev/client/pkg/wait" + "knative.dev/client-pkg/pkg/util/mock" + "knative.dev/client-pkg/pkg/wait" ) type MockKnServingClient struct { diff --git a/pkg/serving/v1/gitops.go b/vendor/knative.dev/client-pkg/pkg/serving/v1/gitops.go similarity index 99% rename from pkg/serving/v1/gitops.go rename to vendor/knative.dev/client-pkg/pkg/serving/v1/gitops.go index d3b3d05798..7dcc9ad1ea 100644 --- a/pkg/serving/v1/gitops.go +++ b/vendor/knative.dev/client-pkg/pkg/serving/v1/gitops.go @@ -28,7 +28,7 @@ import ( "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/cli-runtime/pkg/genericclioptions" - "knative.dev/client/pkg/wait" + "knative.dev/client-pkg/pkg/wait" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) diff --git a/pkg/serving/v1beta1/client.go b/vendor/knative.dev/client-pkg/pkg/serving/v1beta1/client.go similarity index 98% rename from pkg/serving/v1beta1/client.go rename to vendor/knative.dev/client-pkg/pkg/serving/v1beta1/client.go index aa4301c50b..81fe12ff11 100644 --- a/pkg/serving/v1beta1/client.go +++ b/vendor/knative.dev/client-pkg/pkg/serving/v1beta1/client.go @@ -18,7 +18,7 @@ import ( "context" "fmt" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" "k8s.io/client-go/util/retry" @@ -26,8 +26,8 @@ import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/util" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/util" servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" "knative.dev/serving/pkg/client/clientset/versioned/scheme" clientv1beta1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1" diff --git a/pkg/serving/v1beta1/client_mock.go b/vendor/knative.dev/client-pkg/pkg/serving/v1beta1/client_mock.go similarity index 99% rename from pkg/serving/v1beta1/client_mock.go rename to vendor/knative.dev/client-pkg/pkg/serving/v1beta1/client_mock.go index ea18cee093..470b956c1a 100644 --- a/pkg/serving/v1beta1/client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/serving/v1beta1/client_mock.go @@ -18,7 +18,7 @@ import ( "context" "testing" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1" ) diff --git a/pkg/sources/common.go b/vendor/knative.dev/client-pkg/pkg/sources/common.go similarity index 100% rename from pkg/sources/common.go rename to vendor/knative.dev/client-pkg/pkg/sources/common.go diff --git a/pkg/sources/v1/apiserver_client.go b/vendor/knative.dev/client-pkg/pkg/sources/v1/apiserver_client.go similarity index 98% rename from pkg/sources/v1/apiserver_client.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1/apiserver_client.go index 09a59d0855..f84d3bcff4 100644 --- a/pkg/sources/v1/apiserver_client.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1/apiserver_client.go @@ -20,8 +20,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/util" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/util" v1 "knative.dev/eventing/pkg/apis/sources/v1" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" diff --git a/pkg/sources/v1/apiserver_client_mock.go b/vendor/knative.dev/client-pkg/pkg/sources/v1/apiserver_client_mock.go similarity index 99% rename from pkg/sources/v1/apiserver_client_mock.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1/apiserver_client_mock.go index be1cee50b5..9fffb66bad 100644 --- a/pkg/sources/v1/apiserver_client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1/apiserver_client_mock.go @@ -20,7 +20,7 @@ import ( v1 "knative.dev/eventing/pkg/apis/sources/v1" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" ) // MockKnAPIServerSourceClient for mocking the client diff --git a/pkg/sources/v1/binding_client.go b/vendor/knative.dev/client-pkg/pkg/sources/v1/binding_client.go similarity index 99% rename from pkg/sources/v1/binding_client.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1/binding_client.go index 0a23cd1b3f..fd197dfe96 100644 --- a/pkg/sources/v1/binding_client.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1/binding_client.go @@ -28,8 +28,8 @@ import ( duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/tracker" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/util" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/util" ) // KnSinkBindingClient to Eventing Sources. All methods are relative to the diff --git a/pkg/sources/v1/binding_client_mock.go b/vendor/knative.dev/client-pkg/pkg/sources/v1/binding_client_mock.go similarity index 99% rename from pkg/sources/v1/binding_client_mock.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1/binding_client_mock.go index c3f0d33a5d..ab79482364 100644 --- a/pkg/sources/v1/binding_client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1/binding_client_mock.go @@ -20,7 +20,7 @@ import ( v1 "knative.dev/eventing/pkg/apis/sources/v1" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" ) // MockKnSinkBindingClient is a combine of test object and recorder diff --git a/pkg/sources/v1/client.go b/vendor/knative.dev/client-pkg/pkg/sources/v1/client.go similarity index 100% rename from pkg/sources/v1/client.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1/client.go diff --git a/pkg/sources/v1/container_client.go b/vendor/knative.dev/client-pkg/pkg/sources/v1/container_client.go similarity index 98% rename from pkg/sources/v1/container_client.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1/container_client.go index 7e9e408154..7aaef5118f 100644 --- a/pkg/sources/v1/container_client.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1/container_client.go @@ -20,15 +20,15 @@ import ( "context" "fmt" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" "k8s.io/client-go/util/retry" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - knerrors "knative.dev/client/pkg/errors" - "knative.dev/client/pkg/util" + knerrors "knative.dev/client-pkg/pkg/errors" + "knative.dev/client-pkg/pkg/util" v1 "knative.dev/eventing/pkg/apis/sources/v1" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" clientv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1" diff --git a/pkg/sources/v1/container_client_mock.go b/vendor/knative.dev/client-pkg/pkg/sources/v1/container_client_mock.go similarity index 99% rename from pkg/sources/v1/container_client_mock.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1/container_client_mock.go index 19a34ae104..59416e61d2 100644 --- a/pkg/sources/v1/container_client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1/container_client_mock.go @@ -20,7 +20,7 @@ import ( "context" "testing" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" v1 "knative.dev/eventing/pkg/apis/sources/v1" ) diff --git a/pkg/sources/v1beta2/client.go b/vendor/knative.dev/client-pkg/pkg/sources/v1beta2/client.go similarity index 100% rename from pkg/sources/v1beta2/client.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1beta2/client.go diff --git a/pkg/sources/v1beta2/ping_client.go b/vendor/knative.dev/client-pkg/pkg/sources/v1beta2/ping_client.go similarity index 98% rename from pkg/sources/v1beta2/ping_client.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1beta2/ping_client.go index 8ae3843906..2d0e1e94ba 100644 --- a/pkg/sources/v1beta2/ping_client.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1beta2/ping_client.go @@ -18,15 +18,15 @@ import ( "context" "fmt" - "knative.dev/client/pkg/config" + "knative.dev/client-pkg/pkg/config" "k8s.io/client-go/util/retry" "k8s.io/apimachinery/pkg/runtime" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "knative.dev/eventing/pkg/client/clientset/versioned/scheme" - knerrors "knative.dev/client/pkg/errors" + knerrors "knative.dev/client-pkg/pkg/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" diff --git a/pkg/sources/v1beta2/ping_client_mock.go b/vendor/knative.dev/client-pkg/pkg/sources/v1beta2/ping_client_mock.go similarity index 99% rename from pkg/sources/v1beta2/ping_client_mock.go rename to vendor/knative.dev/client-pkg/pkg/sources/v1beta2/ping_client_mock.go index 44b2c97870..42623f0369 100644 --- a/pkg/sources/v1beta2/ping_client_mock.go +++ b/vendor/knative.dev/client-pkg/pkg/sources/v1beta2/ping_client_mock.go @@ -18,7 +18,7 @@ import ( "context" "testing" - "knative.dev/client/pkg/util/mock" + "knative.dev/client-pkg/pkg/util/mock" sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" ) diff --git a/pkg/util/compare.go b/vendor/knative.dev/client-pkg/pkg/util/compare.go similarity index 100% rename from pkg/util/compare.go rename to vendor/knative.dev/client-pkg/pkg/util/compare.go diff --git a/pkg/util/corev1_helper.go b/vendor/knative.dev/client-pkg/pkg/util/corev1_helper.go similarity index 100% rename from pkg/util/corev1_helper.go rename to vendor/knative.dev/client-pkg/pkg/util/corev1_helper.go diff --git a/pkg/util/logging_http_transport.go b/vendor/knative.dev/client-pkg/pkg/util/logging_http_transport.go similarity index 100% rename from pkg/util/logging_http_transport.go rename to vendor/knative.dev/client-pkg/pkg/util/logging_http_transport.go diff --git a/pkg/util/mock/mock_helper.go b/vendor/knative.dev/client-pkg/pkg/util/mock/mock_helper.go similarity index 100% rename from pkg/util/mock/mock_helper.go rename to vendor/knative.dev/client-pkg/pkg/util/mock/mock_helper.go diff --git a/pkg/util/orderedmap.go b/vendor/knative.dev/client-pkg/pkg/util/orderedmap.go similarity index 100% rename from pkg/util/orderedmap.go rename to vendor/knative.dev/client-pkg/pkg/util/orderedmap.go diff --git a/pkg/util/parsing_helper.go b/vendor/knative.dev/client-pkg/pkg/util/parsing_helper.go similarity index 100% rename from pkg/util/parsing_helper.go rename to vendor/knative.dev/client-pkg/pkg/util/parsing_helper.go diff --git a/pkg/util/schema_handling.go b/vendor/knative.dev/client-pkg/pkg/util/schema_handling.go similarity index 100% rename from pkg/util/schema_handling.go rename to vendor/knative.dev/client-pkg/pkg/util/schema_handling.go diff --git a/lib/test/broker.go b/vendor/knative.dev/client-pkg/pkg/util/test/broker.go similarity index 98% rename from lib/test/broker.go rename to vendor/knative.dev/client-pkg/pkg/util/test/broker.go index 83ddf9dffd..dc057f8e56 100644 --- a/lib/test/broker.go +++ b/vendor/knative.dev/client-pkg/pkg/util/test/broker.go @@ -19,7 +19,7 @@ import ( "time" "gotest.tools/v3/assert" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" "k8s.io/apimachinery/pkg/util/wait" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" diff --git a/lib/test/capture_output.go b/vendor/knative.dev/client-pkg/pkg/util/test/capture_output.go similarity index 100% rename from lib/test/capture_output.go rename to vendor/knative.dev/client-pkg/pkg/util/test/capture_output.go diff --git a/lib/test/channel.go b/vendor/knative.dev/client-pkg/pkg/util/test/channel.go similarity index 98% rename from lib/test/channel.go rename to vendor/knative.dev/client-pkg/pkg/util/test/channel.go index dae8f3545f..6f6ca5385b 100644 --- a/lib/test/channel.go +++ b/vendor/knative.dev/client-pkg/pkg/util/test/channel.go @@ -19,7 +19,7 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func ChannelCreate(r *KnRunResultCollector, cname string, args ...string) { diff --git a/lib/test/cli.go b/vendor/knative.dev/client-pkg/pkg/util/test/cli.go similarity index 100% rename from lib/test/cli.go rename to vendor/knative.dev/client-pkg/pkg/util/test/cli.go diff --git a/lib/test/eventtype.go b/vendor/knative.dev/client-pkg/pkg/util/test/eventtype.go similarity index 98% rename from lib/test/eventtype.go rename to vendor/knative.dev/client-pkg/pkg/util/test/eventtype.go index 2608286a32..ac3cc09096 100644 --- a/lib/test/eventtype.go +++ b/vendor/knative.dev/client-pkg/pkg/util/test/eventtype.go @@ -16,7 +16,7 @@ package test import ( "gotest.tools/v3/assert" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // EventtypeCreate creates an eventtype with the given name. diff --git a/lib/test/flags.go b/vendor/knative.dev/client-pkg/pkg/util/test/flags.go similarity index 100% rename from lib/test/flags.go rename to vendor/knative.dev/client-pkg/pkg/util/test/flags.go diff --git a/vendor/knative.dev/client-pkg/pkg/util/test/init.go b/vendor/knative.dev/client-pkg/pkg/util/test/init.go new file mode 100644 index 0000000000..5e4066592a --- /dev/null +++ b/vendor/knative.dev/client-pkg/pkg/util/test/init.go @@ -0,0 +1,25 @@ +/* + Copyright 2024 The Knative 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 test + +import "testing" + +func init() { + if !testing.Testing() { + panic("knative.dev/client-pkg/pkg/util/test: can only be called from test files") + } +} diff --git a/lib/test/integration.go b/vendor/knative.dev/client-pkg/pkg/util/test/integration.go similarity index 100% rename from lib/test/integration.go rename to vendor/knative.dev/client-pkg/pkg/util/test/integration.go diff --git a/lib/test/result_collector.go b/vendor/knative.dev/client-pkg/pkg/util/test/result_collector.go similarity index 100% rename from lib/test/result_collector.go rename to vendor/knative.dev/client-pkg/pkg/util/test/result_collector.go diff --git a/lib/test/revision.go b/vendor/knative.dev/client-pkg/pkg/util/test/revision.go similarity index 99% rename from lib/test/revision.go rename to vendor/knative.dev/client-pkg/pkg/util/test/revision.go index 7d389655ab..46521e7d83 100644 --- a/lib/test/revision.go +++ b/vendor/knative.dev/client-pkg/pkg/util/test/revision.go @@ -20,7 +20,7 @@ import ( "strings" "gotest.tools/v3/assert" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // RevisionListForService list revisions of given service and verifies if their status is True diff --git a/lib/test/service.go b/vendor/knative.dev/client-pkg/pkg/util/test/service.go similarity index 92% rename from lib/test/service.go rename to vendor/knative.dev/client-pkg/pkg/util/test/service.go index deec4b81db..2bbddca03f 100644 --- a/lib/test/service.go +++ b/vendor/knative.dev/client-pkg/pkg/util/test/service.go @@ -25,14 +25,14 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clientv1alpha1 "knative.dev/client/pkg/apis/client/v1alpha1" + clientv1alpha1 "knative.dev/client-pkg/pkg/apis/client/v1alpha1" "knative.dev/pkg/ptr" pkgtest "knative.dev/pkg/test" "knative.dev/serving/pkg/apis/config" servingv1 "knative.dev/serving/pkg/apis/serving/v1" servingtest "knative.dev/serving/pkg/testing/v1" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) // ExpectedServiceListOption enables further configuration of a ServiceList. @@ -51,20 +51,6 @@ func ServiceCreate(r *KnRunResultCollector, serviceName string) { assert.Check(r.T(), util.ContainsAllIgnoreCase(out.Stdout, "service", serviceName, "creating", "namespace", r.KnTest().Kn().Namespace(), "ready")) } -// ServiceCreate verifies given service creation async mode and also verifies output -func ServiceCreateNoWait(r *KnRunResultCollector, serviceName string) { - out := r.KnTest().Kn().Run("service", "create", serviceName, "--no-wait", "--image", pkgtest.ImagePath("helloworld")) - r.AssertNoError(out) - assert.Check(r.T(), util.ContainsAllIgnoreCase(out.Stdout, "service", serviceName, "created", "namespace", r.KnTest().Kn().Namespace())) -} - -// ServiceWait waits for service to be ready and also verifies output -func ServiceWait(r *KnRunResultCollector, serviceName string) { - out := r.KnTest().Kn().Run("service", "wait", serviceName) - r.AssertNoError(out) - assert.Check(r.T(), util.ContainsAllIgnoreCase(out.Stdout, "service", serviceName, "ready", "namespace", r.KnTest().Kn().Namespace())) -} - // ServiceListEmpty verifies that there are no services present func ServiceListEmpty(r *KnRunResultCollector) { out := r.KnTest().Kn().Run("service", "list") diff --git a/lib/test/subscription.go b/vendor/knative.dev/client-pkg/pkg/util/test/subscription.go similarity index 98% rename from lib/test/subscription.go rename to vendor/knative.dev/client-pkg/pkg/util/test/subscription.go index 537e2f4188..f61f5ef1f1 100644 --- a/lib/test/subscription.go +++ b/vendor/knative.dev/client-pkg/pkg/util/test/subscription.go @@ -21,7 +21,7 @@ import ( "gotest.tools/v3/assert" - "knative.dev/client/pkg/util" + "knative.dev/client-pkg/pkg/util" ) func SubscriptionCreate(r *KnRunResultCollector, sname string, args ...string) { diff --git a/lib/test/utils.go b/vendor/knative.dev/client-pkg/pkg/util/test/utils.go similarity index 100% rename from lib/test/utils.go rename to vendor/knative.dev/client-pkg/pkg/util/test/utils.go diff --git a/pkg/util/unstructured.go b/vendor/knative.dev/client-pkg/pkg/util/unstructured.go similarity index 100% rename from pkg/util/unstructured.go rename to vendor/knative.dev/client-pkg/pkg/util/unstructured.go diff --git a/pkg/wait/poll_watcher.go b/vendor/knative.dev/client-pkg/pkg/wait/poll_watcher.go similarity index 100% rename from pkg/wait/poll_watcher.go rename to vendor/knative.dev/client-pkg/pkg/wait/poll_watcher.go diff --git a/pkg/wait/test_wait_helper.go b/vendor/knative.dev/client-pkg/pkg/wait/test_wait_helper.go similarity index 100% rename from pkg/wait/test_wait_helper.go rename to vendor/knative.dev/client-pkg/pkg/wait/test_wait_helper.go diff --git a/pkg/wait/wait_for_ready.go b/vendor/knative.dev/client-pkg/pkg/wait/wait_for_ready.go similarity index 100% rename from pkg/wait/wait_for_ready.go rename to vendor/knative.dev/client-pkg/pkg/wait/wait_for_ready.go diff --git a/vendor/knative.dev/hack/cmd/script/README.md b/vendor/knative.dev/hack/cmd/script/README.md new file mode 100644 index 0000000000..66579b2493 --- /dev/null +++ b/vendor/knative.dev/hack/cmd/script/README.md @@ -0,0 +1,49 @@ +# Vendorless Knative + +The Knative projects can be built without a vendor directory. This is a +convenience for developers, and brings a number of benefits: + +* It is easier to see the changes to the code and review them. +* It is easier to maintain the build and CI scripts, as they don't need to + filter out the vendor directory. +* The project doesn't look dated (the proper dependency management tools + are available for Go since 1.13+). +* No vendor directory means less possibility of accidentally traversing + into it by symlinks or scripts. + +For more details and reasons for avoiding the vendor directory, see +[knative/infra#134](https://github.com/knative/infra/issues/134). + +## Status + +The [knative/infra#134](https://github.com/knative/infra/issues/134) is +ongoing effort. Currently, it is possible to use make projects vendorless, +only if they don't use Knative nor Kubernetes code-generation tools. See the +epic issue for current status. + +## Migration to a vendorless project + +The following steps are required to migrate a project to be vendorless: + +1. Update the `knative.dev/hack` dependency to the latest version. +1. Update the project scripts to use the scripts inflation: + ```patch + -source $(dirname $0)/../vendor/knative.dev/hack/release.sh + +source "$(go run knative.dev/hack/cmd/script release.sh)" + ``` +1. Update the `hack/tools.go` file to refer to the `knative.dev/hack/cmd/script` + tool: + ```go + package hack + + import ( + _ "knative.dev/hack/cmd/script" + ) + ``` +1. Remove the `vendor` directory. +1. Run `hack/update-deps.sh` to update the `go.mod` file(s). + +### Examples of migrated projects + +* [knative/func#1966](https://github.com/knative/func/pull/1966) +* [knative-extensions/kn-plugin-event#307](https://github.com/knative-extensions/kn-plugin-event/pull/307) diff --git a/vendor/knative.dev/hack/cmd/script/main.go b/vendor/knative.dev/hack/cmd/script/main.go new file mode 100644 index 0000000000..288e10710f --- /dev/null +++ b/vendor/knative.dev/hack/cmd/script/main.go @@ -0,0 +1,28 @@ +/* +Copyright 2022 The Knative 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 + + 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 main + +import "knative.dev/hack/pkg/inflator/cli" + +func main() { + cli.ExecuteOrDie(cli.Options...) +} + +// RunMain is used by tests to run the main function. +func RunMain() { // nolint:deadcode + main() +} diff --git a/vendor/knative.dev/hack/pkg/inflator/cli/app.go b/vendor/knative.dev/hack/pkg/inflator/cli/app.go new file mode 100644 index 0000000000..445adca2df --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/cli/app.go @@ -0,0 +1,40 @@ +package cli + +import ( + "fmt" + + "knative.dev/hack/pkg/inflator/extract" + "knative.dev/hack/pkg/retcode" +) + +// Execute will execute the application. +func Execute(opts []Option) Result { + ex := Execution{}.Default().Configure(opts) + fl, err := parseArgs(&ex) + if err != nil { + return Result{ + Execution: ex, + Err: err, + } + } + op := createOperation(fl, ex.Args) + return Result{ + Execution: ex, + Err: op.Extract(ex), + } +} + +// ExecuteOrDie will execute the application or perform os.Exit in case of error. +func ExecuteOrDie(opts ...Option) { + if r := Execute(opts); r.Err != nil { + r.PrintErrln(fmt.Sprintf("%v", r.Err)) + r.Exit(retcode.Calc(r.Err)) + } +} + +func createOperation(fl *flags, argv []string) extract.Operation { + return extract.Operation{ + ScriptName: argv[0], + Verbose: fl.verbose, + } +} diff --git a/vendor/knative.dev/hack/pkg/inflator/cli/exec.go b/vendor/knative.dev/hack/pkg/inflator/cli/exec.go new file mode 100644 index 0000000000..3f3617b2d8 --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/cli/exec.go @@ -0,0 +1,51 @@ +package cli + +import ( + "io" + "os" +) + +// Execution is used to execute a command. +type Execution struct { + Args []string + Stdout io.Writer + Stderr io.Writer + Exit func(code int) +} + +// Default will set default values for the execution. +func (e Execution) Default() Execution { + if e.Stdout == nil { + e.Stdout = os.Stdout + } + if e.Stderr == nil { + e.Stderr = os.Stderr + } + if e.Exit == nil { + e.Exit = os.Exit + } + if len(e.Args) == 0 { + e.Args = os.Args[1:] + } + return e +} + +// Configure will configure the execution. +func (e Execution) Configure(opts []Option) Execution { + for _, opt := range opts { + opt(&e) + } + return e +} + +// Option is used to configure an App. +type Option func(*Execution) + +// Options to override the commandline for testing purposes. +var Options []Option //nolint:gochecknoglobals + +// Result is a result of execution. +type Result struct { + Execution + Err error +} diff --git a/vendor/knative.dev/hack/pkg/inflator/cli/flags.go b/vendor/knative.dev/hack/pkg/inflator/cli/flags.go new file mode 100644 index 0000000000..3e9331819b --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/cli/flags.go @@ -0,0 +1,46 @@ +package cli + +import ( + "os" + "strings" +) + +const ( + // ManualVerboseEnvVar is the environment variable that can be set to disable + // automatic verbose mode on CI servers. + ManualVerboseEnvVar = "KNATIVE_HACK_SCRIPT_MANUAL_VERBOSE" +) + +type flags struct { + verbose bool +} + +func parseArgs(ex *Execution) (*flags, error) { + f := flags{ + verbose: isCiServer(), + } + if len(ex.Args) == 0 { + return nil, usageErr{} + } + for i := 0; i < len(ex.Args); i++ { + if ex.Args[i] == "-v" || ex.Args[i] == "--verbose" { + f.verbose = true + ex.Args = append(ex.Args[:i], ex.Args[i+1:]...) + i-- + } + + if ex.Args[i] == "-h" || ex.Args[i] == "--help" { + return nil, usageErr{} + } + } + return &f, nil +} + +func isCiServer() bool { + if strings.HasPrefix(strings.ToLower(os.Getenv(ManualVerboseEnvVar)), "t") { + return false + } + return os.Getenv("CI") != "" || + os.Getenv("BUILD_ID") != "" || + os.Getenv("PROW_JOB_ID") != "" +} diff --git a/vendor/knative.dev/hack/pkg/inflator/cli/print.go b/vendor/knative.dev/hack/pkg/inflator/cli/print.go new file mode 100644 index 0000000000..ca73457222 --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/cli/print.go @@ -0,0 +1,33 @@ +package cli + +import "fmt" + +// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. +func (e Execution) Print(i ...interface{}) { + fmt.Fprint(e.Stdout, i...) +} + +// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. +func (e Execution) Println(i ...interface{}) { + e.Print(fmt.Sprintln(i...)) +} + +// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. +func (e Execution) Printf(format string, i ...interface{}) { + e.Print(fmt.Sprintf(format, i...)) +} + +// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. +func (e Execution) PrintErr(i ...interface{}) { + fmt.Fprint(e.Stderr, i...) +} + +// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. +func (e Execution) PrintErrln(i ...interface{}) { + e.PrintErr(fmt.Sprintln(i...)) +} + +// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. +func (e Execution) PrintErrf(format string, i ...interface{}) { + e.PrintErr(fmt.Sprintf(format, i...)) +} diff --git a/vendor/knative.dev/hack/pkg/inflator/cli/usage.go b/vendor/knative.dev/hack/pkg/inflator/cli/usage.go new file mode 100644 index 0000000000..e338e536a9 --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/cli/usage.go @@ -0,0 +1,25 @@ +package cli + +type usageErr struct{} + +func (u usageErr) Retcode() int { + return 0 +} + +func (u usageErr) Error() string { + return `Hacks as Go self-extracting binary + +Will extract Hack scripts to a temporary directory, and provide a source +file path to requested shell script. + +# In Bash script +source "$(go run knative.dev/hack/cmd/script@latest library.sh)" + +Usage: + script [flags] library.sh + +Flags: + -h, --help help + -v, --verbose verbose output +` +} diff --git a/vendor/knative.dev/hack/pkg/inflator/extract/errors.go b/vendor/knative.dev/hack/pkg/inflator/extract/errors.go new file mode 100644 index 0000000000..f6583458bb --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/extract/errors.go @@ -0,0 +1,24 @@ +package extract + +import ( + "errors" + "fmt" +) + +var ( + // ErrBug is an error that indicates a bug in the code. + ErrBug = errors.New("probably a bug in the code") + + // ErrUnexpected is an error that indicates an unexpected situation. + ErrUnexpected = errors.New("unexpected situation") +) + +func wrapErr(err error, target error) error { + if err == nil { + return nil + } + if errors.Is(err, target) { + return err + } + return fmt.Errorf("%w: %v", target, err) +} diff --git a/vendor/knative.dev/hack/pkg/inflator/extract/extract.go b/vendor/knative.dev/hack/pkg/inflator/extract/extract.go new file mode 100644 index 0000000000..b48ac5687b --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/extract/extract.go @@ -0,0 +1,136 @@ +package extract + +import ( + "io/fs" + "math" + "os" + "path" + "strings" + + "knative.dev/hack" +) + +const ( + // HackScriptsDirEnvVar is the name of the environment variable that points + // to directory where knative-hack scripts will be extracted. + HackScriptsDirEnvVar = "KNATIVE_HACK_SCRIPTS_DIR" + // PermOwnerWrite is the permission bits for owner write. + PermOwnerWrite = 0o200 + // PermAllExecutable is the permission bits for executable. + PermAllExecutable = 0o111 +) + +// Printer is an interface for printing messages. +type Printer interface { + Print(i ...interface{}) + Println(i ...interface{}) + Printf(format string, i ...interface{}) + PrintErr(i ...interface{}) + PrintErrln(i ...interface{}) + PrintErrf(format string, i ...interface{}) +} + +// Operation is the main extract object that can extract scripts. +type Operation struct { + // ScriptName is the name of the script to extract. + ScriptName string + // Verbose will print more information. + Verbose bool +} + +// Extract will extract a script from the library to a temporary directory and +// provide the file path to it. +func (o Operation) Extract(prtr Printer) error { + l := logger{o.Verbose, prtr} + hackRootDir := os.Getenv(HackScriptsDirEnvVar) + if f, err := hack.Scripts.Open(o.ScriptName); err != nil { + return wrapErr(err, ErrUnexpected) + } else if err = f.Close(); err != nil { + return wrapErr(err, ErrUnexpected) + } + if hackRootDir == "" { + hackRootDir = path.Join(os.TempDir(), "knative", "hack", "scripts") + } + l.debugf("Extracting hack scripts to directory: %s", hackRootDir) + if err := copyDir(l, hack.Scripts, hackRootDir, "."); err != nil { + return err + } + scriptPath := path.Join(hackRootDir, o.ScriptName) + l.Println(scriptPath) + return nil +} + +func copyDir(l logger, inputFS fs.ReadDirFS, destRootDir, dir string) error { + return wrapErr(fs.WalkDir(inputFS, dir, func(filePath string, dirEntry fs.DirEntry, err error) error { + if err != nil { + return wrapErr(err, ErrBug) + } + return copyFile(l, inputFS, destRootDir, filePath, dirEntry) + }), ErrUnexpected) +} + +func copyFile( + l logger, + inputFS fs.ReadDirFS, + destRootDir, filePath string, + dirEntry fs.DirEntry, +) error { + inputFI, err := dirEntry.Info() + if err != nil { + return wrapErr(err, ErrBug) + } + + destPath := path.Join(destRootDir, filePath) + perm := inputFI.Mode().Perm() + + perm |= PermOwnerWrite + if dirEntry.IsDir() { + perm |= PermAllExecutable + if err = os.MkdirAll(destPath, perm); err != nil { + return wrapErr(err, ErrUnexpected) + } + return nil + } + + var ( + inputCS checksum + destCS checksum + destFI fs.FileInfo + bytes []byte + ) + inputCS = asChecksum(inputFI) + if destFI, err = os.Stat(destPath); err != nil { + if !os.IsNotExist(err) { + return wrapErr(err, ErrUnexpected) + } + } else { + destCS = asChecksum(destFI) + } + if inputCS == destCS { + l.debugf("%-30s up-to-date", filePath) + return nil + } + if bytes, err = fs.ReadFile(inputFS, filePath); err != nil { + return wrapErr(err, ErrBug) + } + if err = os.WriteFile(destPath, bytes, perm); err != nil { + return wrapErr(err, ErrUnexpected) + } + + sizeKB := int(inputFI.Size() / 1024) + size5k := int(math.Ceil(float64(sizeKB) / 5)) + l.debugf("%-30s %3d KiB %s", filePath, sizeKB, strings.Repeat("+", size5k)) + return nil +} + +func asChecksum(f fs.FileInfo) checksum { + return checksum{ + exists: true, + size: f.Size(), + } +} + +type checksum struct { + exists bool + size int64 +} diff --git a/vendor/knative.dev/hack/pkg/inflator/extract/logger.go b/vendor/knative.dev/hack/pkg/inflator/extract/logger.go new file mode 100644 index 0000000000..5f7e25b462 --- /dev/null +++ b/vendor/knative.dev/hack/pkg/inflator/extract/logger.go @@ -0,0 +1,12 @@ +package extract + +type logger struct { + verbose bool + Printer +} + +func (l logger) debugf(format string, i ...interface{}) { + if l.verbose { + l.PrintErrf("[hack] "+format+"\n", i...) + } +} diff --git a/vendor/knative.dev/hack/pkg/retcode/retcode.go b/vendor/knative.dev/hack/pkg/retcode/retcode.go new file mode 100644 index 0000000000..886eb0e6ac --- /dev/null +++ b/vendor/knative.dev/hack/pkg/retcode/retcode.go @@ -0,0 +1,28 @@ +package retcode + +import "hash/crc32" + +var ( + // LowerBound is the lower bound of the POSIX retcode range. Use this to + // configure the package. + LowerBound = 1 + // UpperBound is the upper bound of the POSIX retcode range. Use this to + // configure the package. + UpperBound = 255 +) + +// Calc will calculate an POSIX retcode from an error. +func Calc(err error) int { + if err == nil { + return 0 + } + if r, ok := err.(retcodeErr); ok { + return r.Retcode() + } + upper := UpperBound - LowerBound + return int(crc32.ChecksumIEEE([]byte(err.Error())))%upper + LowerBound +} + +type retcodeErr interface { + Retcode() int +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 7f8f072e64..8ef0678b1d 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -960,9 +960,33 @@ k8s.io/utils/pointer k8s.io/utils/ptr k8s.io/utils/strings/slices k8s.io/utils/trace -# knative.dev/client-pkg v0.0.0-20240327121233-6984d81a90ec +# knative.dev/client-pkg v0.0.0-20240327121233-6984d81a90ec => github.com/cardil/knative-client-pkg v0.0.0-20240416181347-fe59266c904d ## explicit; go 1.21 +knative.dev/client-pkg/pkg/apis/client +knative.dev/client-pkg/pkg/apis/client/v1alpha1 +knative.dev/client-pkg/pkg/commands +knative.dev/client-pkg/pkg/commands/flags/list +knative.dev/client-pkg/pkg/commands/flags/sink +knative.dev/client-pkg/pkg/config +knative.dev/client-pkg/pkg/dynamic +knative.dev/client-pkg/pkg/dynamic/fake +knative.dev/client-pkg/pkg/errors +knative.dev/client-pkg/pkg/eventing/v1 +knative.dev/client-pkg/pkg/eventing/v1beta2 +knative.dev/client-pkg/pkg/flags +knative.dev/client-pkg/pkg/messaging/v1 knative.dev/client-pkg/pkg/plugin +knative.dev/client-pkg/pkg/printers +knative.dev/client-pkg/pkg/serving +knative.dev/client-pkg/pkg/serving/v1 +knative.dev/client-pkg/pkg/serving/v1beta1 +knative.dev/client-pkg/pkg/sources +knative.dev/client-pkg/pkg/sources/v1 +knative.dev/client-pkg/pkg/sources/v1beta2 +knative.dev/client-pkg/pkg/util +knative.dev/client-pkg/pkg/util/mock +knative.dev/client-pkg/pkg/util/test +knative.dev/client-pkg/pkg/wait # knative.dev/eventing v0.40.1-0.20240327131403-47543259ceba ## explicit; go 1.21 knative.dev/eventing/pkg/apis/config @@ -997,6 +1021,10 @@ knative.dev/eventing/pkg/eventingtls # knative.dev/hack v0.0.0-20240327150553-47368d631660 ## explicit; go 1.18 knative.dev/hack +knative.dev/hack/cmd/script +knative.dev/hack/pkg/inflator/cli +knative.dev/hack/pkg/inflator/extract +knative.dev/hack/pkg/retcode # knative.dev/networking v0.0.0-20240327140628-ae039896b125 ## explicit; go 1.21 knative.dev/networking/pkg @@ -1192,3 +1220,4 @@ sigs.k8s.io/structured-merge-diff/v4/value ## explicit; go 1.12 sigs.k8s.io/yaml sigs.k8s.io/yaml/goyaml.v2 +# knative.dev/client-pkg => github.com/cardil/knative-client-pkg v0.0.0-20240416181347-fe59266c904d