diff --git a/CHANGELOG.md b/CHANGELOG.md index 29532ad..0d0f92f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- [#215](https://github.com/deviceinsight/kafkactl/pull/215) Add `--context` option to set command's context ## 5.3.0 - 2024-08-14 ### Added diff --git a/cmd/root.go b/cmd/root.go index 15c402c..9f52f69 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -3,6 +3,8 @@ package cmd import ( "fmt" + "github.com/spf13/viper" + "github.com/deviceinsight/kafkactl/v5/internal/global" "github.com/deviceinsight/kafkactl/v5/cmd/alter" @@ -54,6 +56,18 @@ func NewKafkactlCommand(streams output.IOStreams) *cobra.Command { rootCmd.PersistentFlags().StringVarP(&globalFlags.ConfigFile, "config-file", "C", "", fmt.Sprintf("config file. default locations: %v", globalConfig.DefaultPaths())) rootCmd.PersistentFlags().BoolVarP(&globalFlags.Verbose, "verbose", "V", false, "verbose output") + rootCmd.PersistentFlags().StringVar(&globalFlags.Context, "context", "", "The name of the context to use") + + err := rootCmd.RegisterFlagCompletionFunc("context", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { + var contexts []string + for k := range viper.GetStringMap("contexts") { + contexts = append(contexts, k) + } + return contexts, cobra.ShellCompDirectiveDefault + }) + if err != nil { + panic(err) + } k8s.KafkaCtlVersion = Version diff --git a/internal/global/config.go b/internal/global/config.go index e7f77cd..22bc737 100644 --- a/internal/global/config.go +++ b/internal/global/config.go @@ -2,6 +2,7 @@ package global import ( "errors" + "fmt" "os" "path/filepath" "runtime" @@ -13,6 +14,7 @@ import ( type Flags struct { ConfigFile string + Context string Verbose bool } @@ -52,6 +54,18 @@ func GetFlags() Flags { } func GetCurrentContext() string { + var context = configInstance.Flags().Context + if context != "" { + contexts := viper.GetStringMap("contexts") + + // check if it is an existing context + if _, ok := contexts[context]; !ok { + output.Fail(fmt.Errorf("not a valid context: %s", context)) + } + + return context + } + return configInstance.currentContext() }