Skip to content

Commit

Permalink
Update sink flag code to use latest from knative/client
Browse files Browse the repository at this point in the history
  • Loading branch information
cardil committed Apr 16, 2024
1 parent 2dec068 commit 96beb94
Show file tree
Hide file tree
Showing 37 changed files with 3,666 additions and 257 deletions.
458 changes: 458 additions & 0 deletions pkg/commands/completion_helper.go

Large diffs are not rendered by default.

1,617 changes: 1,617 additions & 0 deletions pkg/commands/completion_helper_test.go

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -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 list

import (
"io"
Expand All @@ -26,24 +28,23 @@ import (
"knative.dev/client-pkg/pkg/util"
)

// ListFlags composes common printer flag structs
// used in the list command.
type ListPrintFlags struct {
// 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 *ListPrintFlags) AllowedFormats() []string {
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 *ListPrintFlags) ToPrinter() (hprinters.ResourcePrinter, error) {
func (f *PrintFlags) ToPrinter() (hprinters.ResourcePrinter, error) {
// if there are flags specified for generic printing
if f.GenericPrintFlags.OutputFlagSpecified() {
p, err := f.GenericPrintFlags.ToPrinter()
Expand All @@ -61,7 +62,7 @@ func (f *ListPrintFlags) ToPrinter() (hprinters.ResourcePrinter, error) {
}

// Print is to print an Object to a Writer
func (f *ListPrintFlags) Print(obj runtime.Object, w io.Writer) error {
func (f *PrintFlags) Print(obj runtime.Object, w io.Writer) error {
printer, err := f.ToPrinter()
if err != nil {
return err
Expand All @@ -80,15 +81,15 @@ func (f *ListPrintFlags) Print(obj runtime.Object, w io.Writer) error {

// AddFlags receives a *cobra.Command reference and binds
// flags related to humanreadable and template printing.
func (f *ListPrintFlags) AddFlags(cmd *cobra.Command) {
func (f *PrintFlags) AddFlags(cmd *cobra.Command) {
f.GenericPrintFlags.AddFlags(cmd)
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{
// 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,
Expand All @@ -97,6 +98,6 @@ func NewListPrintFlags(printer func(h hprinters.PrintHandler)) *ListPrintFlags {

// EnsureWithNamespace ensures that humanreadable flags return
// a printer capable of printing with a "namespace" column.
func (f *ListPrintFlags) EnsureWithNamespace() {
func (f *PrintFlags) EnsureWithNamespace() {
f.HumanReadableFlags.EnsureWithNamespace()
}
Original file line number Diff line number Diff line change
@@ -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 list_test

import (
"bytes"
Expand All @@ -25,6 +27,7 @@ import (
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/duration"
"knative.dev/client-pkg/pkg/commands/flags/list"

"k8s.io/cli-runtime/pkg/genericclioptions"
"knative.dev/client-pkg/pkg/printers"
Expand Down Expand Up @@ -56,15 +59,15 @@ var (
)

func TestListPrintFlagsFormats(t *testing.T) {
flags := NewListPrintFlags(nil)
flags := list.NewPrintFlags(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) {})
flags := list.NewPrintFlags(func(h hprinters.PrintHandler) {})

cmd = &cobra.Command{}
flags.AddFlags(cmd)
Expand All @@ -82,8 +85,8 @@ func TestListPrintFlags(t *testing.T) {

func TestListPrintFlagsPrint(t *testing.T) {
var cmd *cobra.Command
flags := NewListPrintFlags(func(h hprinters.PrintHandler) {
h.TableHandler(columnDefs, validPrintFunc)
flags := list.NewPrintFlags(func(h hprinters.PrintHandler) {
assert.NilError(t, h.TableHandler(columnDefs, validPrintFunc))
})

cmd = &cobra.Command{}
Expand All @@ -108,8 +111,8 @@ func TestListPrintFlagsPrint(t *testing.T) {

func TestEnsureNamespaces(t *testing.T) {
var cmd *cobra.Command
flags := NewListPrintFlags(func(h hprinters.PrintHandler) {
h.TableHandler(columnDefs, validPrintFunc)
flags := list.NewPrintFlags(func(h hprinters.PrintHandler) {
assert.NilError(t, h.TableHandler(columnDefs, validPrintFunc))
})

cmd = &cobra.Command{}
Expand Down
111 changes: 66 additions & 45 deletions pkg/commands/flags/sink.go → pkg/commands/flags/sink/flag.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -29,46 +31,58 @@ import (
clientdynamic "knative.dev/client-pkg/pkg/dynamic"
)

type SinkFlags struct {
sink string
// Flag holds the sink flag and its mappings
type Flag struct {
Sink string
SinkMappings map[string]schema.GroupVersionResource
}

// 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 dont want to set one
func (i *SinkFlags) AddWithFlagName(cmd *cobra.Command, fname, short string) {
// 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 *Flag) AddWithFlagName(cmd *cobra.Command, fname, short string) {
flag := "--" + fname
if short == "" {
cmd.Flags().StringVar(&i.sink, fname, "", "")
cmd.Flags().StringVar(&i.Sink, fname, "", "")
} else {
cmd.Flags().StringVarP(&i.sink, fname, short, "", "")
cmd.Flags().StringVarP(&i.Sink, fname, short, "", "")
}
cmd.Flag(fname).Usage = "Addressable sink for events. " +
"You can specify a broker, channel, Knative service or URI. " +
"Examples: '" + flag + " broker:nest' for a broker 'nest', " +
"'" + flag + " channel:pipe' for a channel 'pipe', " +
"'" + flag + " ksvc:mysvc:mynamespace' for a Knative service 'mysvc' in another namespace 'mynamespace', " +
"'" + flag + " https://event.receiver.uri' for an URI with an 'http://' or 'https://' schema, " +
"'" + flag + " https://event.receiver.uri' for an HTTP URI, " +
"'" + flag + " ksvc:receiver' or simply '" + flag + " receiver' for a Knative service 'receiver' in the current namespace. " +
"If a prefix is not provided, it is considered as a Knative service in the current namespace. " +
"If referring to a Knative service in another namespace, 'ksvc:name:namespace' combination must be provided explicitly."

"'" + flag + " special.eventing.dev/v1alpha1/channels:pipe' for GroupVersionResource of v1alpha1 'pipe'. " +
"If a prefix is not provided, it is considered as a Knative service in the current namespace."
// Use default mapping if empty
if i.SinkMappings == nil {
i.SinkMappings = defaultSinkMappings
}
for _, p := range config.GlobalConfig.SinkMappings() {
//user configuration might override the default configuration
sinkMappings[p.Prefix] = schema.GroupVersionResource{
i.SinkMappings[p.Prefix] = schema.GroupVersionResource{
Resource: p.Resource,
Group: p.Group,
Version: p.Version,
}
}
}

// Add configures sink flag with name 'sink' amd short name 's'
func (i *SinkFlags) Add(cmd *cobra.Command) {
// Add configures Sink flag with name 'Sink' amd short name 's'
func (i *Flag) Add(cmd *cobra.Command) {
i.AddWithFlagName(cmd, "sink", "s")
}

// sinkPrefixes maps prefixes used for sinks to their GroupVersionResources.
var sinkMappings = map[string]schema.GroupVersionResource{
// SinkPrefixes maps prefixes used for sinks to their GroupVersionResources.
var defaultSinkMappings = map[string]schema.GroupVersionResource{
"broker": {
Resource: "brokers",
Group: "eventing.knative.dev",
Expand All @@ -89,12 +103,16 @@ var sinkMappings = 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 == "" {
if i.Sink == "" {
return nil, nil
}
prefix, name, ns := parseSink(i.sink)
// Use default mapping if empty
if i.SinkMappings == nil {
i.SinkMappings = defaultSinkMappings
}
prefix, name, ns := parseSink(i.Sink)
if prefix == "" {
// URI target
uri, err := apis.ParseURL(name)
Expand All @@ -103,10 +121,10 @@ func (i *SinkFlags) ResolveSink(ctx context.Context, knclient clientdynamic.KnDy
}
return &duckv1.Destination{URI: uri}, nil
}
typ, ok := sinkMappings[prefix]
gvr, ok := i.SinkMappings[prefix]
if !ok {
if prefix == "svc" || prefix == "service" {
return nil, fmt.Errorf("unsupported sink prefix: '%s', please use prefix 'ksvc' for knative service", prefix)
return nil, fmt.Errorf("unsupported Sink prefix: '%s', please use prefix 'ksvc' for knative service", prefix)
}
idx := strings.LastIndex(prefix, "/")
var groupVersion string
Expand All @@ -116,21 +134,24 @@ func (i *SinkFlags) ResolveSink(ctx context.Context, knclient clientdynamic.KnDy
} else {
kind = prefix
}
parsedVersion, _ := schema.ParseGroupVersion(groupVersion)
parsedVersion, err := schema.ParseGroupVersion(groupVersion)
if err != nil {
return nil, err
}

// For the RAWclient the resource name must be in lower case plural form.
// This is the best effort to sanitize the inputs, but the safest way is to provide
// the appropriate form in user's input.
if !strings.HasSuffix(kind, "s") {
kind = kind + "s"
}
typ = schema.GroupVersionResource{
Group: parsedVersion.Group,
Version: parsedVersion.Version,
Resource: kind,
}
kind = strings.ToLower(kind)
gvr = parsedVersion.WithResource(kind)
}
if ns != "" {
namespace = ns
}
obj, err := client.Resource(typ).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
obj, err := client.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -163,10 +184,10 @@ func parseSink(sink string) (string, string, string) {
}
}

// SinkToString prepares a sink for list output
// SinkToString prepares a Sink for list output
func SinkToString(sink duckv1.Destination) string {
if sink.Ref != nil {
if sink.Ref.Kind == "Service" && strings.HasPrefix(sink.Ref.APIVersion, sinkMappings["ksvc"].Group) {
if sink.Ref.Kind == "Service" && strings.HasPrefix(sink.Ref.APIVersion, defaultSinkMappings["ksvc"].Group) {
return fmt.Sprintf("ksvc:%s", sink.Ref.Name)
} else {
return fmt.Sprintf("%s:%s", strings.ToLower(sink.Ref.Kind), sink.Ref.Name)
Expand Down

0 comments on commit 96beb94

Please sign in to comment.