diff --git a/cmd/subscribe.go b/cmd/subscribe.go index 2a8d57bff4..a8f16ffb2b 100644 --- a/cmd/subscribe.go +++ b/cmd/subscribe.go @@ -1,6 +1,9 @@ package cmd import ( + "fmt" + "strings" + "github.com/ory/viper" "github.com/spf13/cobra" fn "knative.dev/func/pkg/functions" @@ -18,19 +21,19 @@ func NewSubscribeCmd() *cobra.Command { }, } - cmd.Flags().StringP("filter", "f", "", "The event metadata to filter for") + cmd.Flags().StringArrayP("filter", "f", []string{}, "Filter for the Cloud Event metadata") + cmd.Flags().StringP("source", "s", "default", "The source, like a Knative Broker") return cmd } -// / func runSubscribe(cmd *cobra.Command, args []string) (err error) { var ( cfg subscibeConfig f fn.Function ) - cfg = newSubscribeConfig() + cfg = newSubscribeConfig(cmd) if f, err = fn.NewFunction(""); err != nil { return @@ -42,12 +45,10 @@ func runSubscribe(cmd *cobra.Command, args []string) (err error) { return fn.NewErrNotInitialized(f.Root) } - // add it + // add subscription to function f.Subscription = append(f.Subscription, fn.SubscriptionSpec{ - Source: cfg.Source, - Filters: map[string]string{ - "type": cfg.Filter, - }, + Source: cfg.Source, + Filters: extractFilterMap(cfg), }) // pump it @@ -55,16 +56,38 @@ func runSubscribe(cmd *cobra.Command, args []string) (err error) { } +func extractFilterMap(cfg subscibeConfig) map[string]string { + subscriptionFilters := make(map[string]string) + for _, filter := range cfg.Filter { + kv := strings.Split(filter, "=") + if len(kv) != 2 { + fmt.Println("Invalid pair:", filter) + continue + } + key := kv[0] + value := kv[1] + subscriptionFilters[key] = value + } + return subscriptionFilters +} + type subscibeConfig struct { - Filter string + Filter []string Source string } -func newSubscribeConfig() subscibeConfig { - c := subscibeConfig{ - Filter: viper.GetString("filter"), +func newSubscribeConfig(cmd *cobra.Command) (c subscibeConfig) { + c = subscibeConfig{ + Filter: viper.GetStringSlice("filter"), Source: viper.GetString("source"), } + // NOTE: .Filter should be viper.GetStringSlice, but this returns unparsed + // results and appears to be an open issue since 2017: + // https://github.com/spf13/viper/issues/380 + var err error + if c.Filter, err = cmd.Flags().GetStringArray("filter"); err != nil { + fmt.Fprintf(cmd.OutOrStdout(), "error reading filter arguments: %v", err) + } - return c + return } diff --git a/docs/reference/func_subscribe.md b/docs/reference/func_subscribe.md index 5538ec5d8b..d6aea6e946 100644 --- a/docs/reference/func_subscribe.md +++ b/docs/reference/func_subscribe.md @@ -13,9 +13,9 @@ func subscribe ### Options ``` - -f, --filter string The event metadata to filter for - -h, --help help for subscribe - -s, --source string The source, like a Knative Broker (default "default") + -f, --filter stringArray Filter for the Cloud Event metadata + -h, --help help for subscribe + -s, --source string The source, like a Knative Broker (default "default") ``` ### SEE ALSO