Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --context flag #215

Merged
merged 5 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 1 addition & 12 deletions cmd/config/useContext.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package config

import (
"sort"

"github.com/deviceinsight/kafkactl/v5/internal/global"

"github.com/deviceinsight/kafkactl/v5/internal/output"
"github.com/pkg/errors"

Expand Down Expand Up @@ -42,15 +39,7 @@ func newUseContextCmd() *cobra.Command {
return nil, cobra.ShellCompDirectiveNoFileComp
}

contextMap := viper.GetStringMap("contexts")
contexts := make([]string, 0, len(contextMap))
for k := range contextMap {
contexts = append(contexts, k)
}

sort.Strings(contexts)

return contexts, cobra.ShellCompDirectiveNoFileComp
return global.ListAvailableContexts(), cobra.ShellCompDirectiveNoFileComp
},
}

Expand Down
8 changes: 8 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ 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) {
return global.ListAvailableContexts(), cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
panic(err)
}

k8s.KafkaCtlVersion = Version

Expand Down
53 changes: 53 additions & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ package cmd_test
import (
"fmt"
"os"
"strings"
"testing"

"github.com/deviceinsight/kafkactl/v5/internal/output"

"github.com/deviceinsight/kafkactl/v5/internal/global"

"github.com/deviceinsight/kafkactl/v5/internal/testutil"
Expand Down Expand Up @@ -125,3 +128,53 @@ func TestEnvironmentVariableLoadingAliases(t *testing.T) {
testutil.AssertEquals(t, "WaitForAll", viper.GetString("contexts.default.producer.requiredAcks"))
testutil.AssertEquals(t, "1234", viper.GetString("contexts.default.producer.maxMessageBytes"))
}

func TestContextFlag(t *testing.T) {

testutil.StartUnitTest(t)

kafkaCtl := testutil.CreateKafkaCtlCommand()

if _, err := kafkaCtl.Execute("version", "--context", "sasl-user"); err != nil {
t.Fatalf("failed to execute command: %v", err)
}

testutil.AssertEquals(t, "sasl-user", global.GetCurrentContext())
}

func TestContextFlagProvidesUnknownContext(t *testing.T) {

testutil.StartUnitTest(t)

kafkaCtl := testutil.CreateKafkaCtlCommand()

if _, err := kafkaCtl.Execute("version", "--context", "unknown-context"); err != nil {
t.Fatalf("failed to execute command: %v", err)
}

var failError error

output.Fail = func(err error) {
failError = err
}

global.GetCurrentContext()

testutil.AssertErrorContains(t, "not a valid context: unknown-context", failError)
}

func TestContextFlagAutoCompletion(t *testing.T) {

testutil.StartUnitTest(t)

kafkaCtl := testutil.CreateKafkaCtlCommand()
kafkaCtl.Verbose = false

if _, err := kafkaCtl.Execute("__complete", "--context", ""); err != nil {
t.Fatalf("failed to execute command: %v", err)
}

outputLines := strings.Split(strings.TrimSpace(kafkaCtl.GetStdOut()), "\n")

testutil.AssertArraysEquals(t, []string{"default", "k8s-mock", "no-avro", "sasl-admin", "sasl-user"}, outputLines[:len(outputLines)-1])
}
26 changes: 26 additions & 0 deletions internal/global/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package global

import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"

"github.com/deviceinsight/kafkactl/v5/internal/output"
Expand All @@ -13,6 +15,7 @@ import (

type Flags struct {
ConfigFile string
Context string
Verbose bool
}

Expand Down Expand Up @@ -51,7 +54,30 @@ func GetFlags() Flags {
return configInstance.flags
}

func ListAvailableContexts() []string {

var contexts []string
for k := range viper.GetStringMap("contexts") {
contexts = append(contexts, k)
}

sort.Strings(contexts)
return contexts
}

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()
}

Expand Down