Skip to content

Commit

Permalink
fix rename example
Browse files Browse the repository at this point in the history
  • Loading branch information
sunny0826 committed Jan 19, 2020
1 parent 947f110 commit bb05abf
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 97 deletions.
20 changes: 3 additions & 17 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ type AddCommand struct {

func (ac *AddCommand) Init() {
ac.command = &cobra.Command{
Use: "add",
Short: "Merge configuration file with $HOME/.kube/config",
Use: "add",
Short: "Merge configuration file with $HOME/.kube/config",
Long: "Merge configuration file with $HOME/.kube/config",
RunE: func(cmd *cobra.Command, args []string) error {
return ac.runAdd(cmd, args)
},
Expand Down Expand Up @@ -207,21 +208,6 @@ func merge2Master(config *clientcmdapi.Config) []byte {
return output
}

func WriteConfig(config []byte) error {
if cover {
err := ioutil.WriteFile(cfgFile, config, 0777)
if err != nil {
return err
}
} else {
err := ioutil.WriteFile("./config.yaml", config, 0777)
if err != nil {
return err
}
}
return nil
}

func addExample() string {
return `
# Merge example.yaml with $HOME/.kube/config
Expand Down
18 changes: 7 additions & 11 deletions cmd/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (cc *CompletionCommand) Init() {
Use: "completion",
Short: "Generates bash/zsh completion scripts",
Long: `Output shell completion code for the specified shell (bash or zsh).`,
Args: cobra.MinimumNArgs(1),
Args: cobra.ExactArgs(1),
Aliases: []string{"c"},
RunE: func(cmd *cobra.Command, args []string) error {
return cc.runCompletion(cmd, args)
Expand All @@ -40,17 +40,13 @@ func (cc *CompletionCommand) Init() {
}

func (cc *CompletionCommand) runCompletion(command *cobra.Command, args []string) error {
if len(args) == 1 {
complet := args[0]
if complet == "bash" {
cc.command.GenBashCompletion(os.Stdout)
} else if complet == "zsh" {
zsh.Wrap(cc.command).GenZshCompletion(os.Stdout)
} else {
Warning.Println("Parameter error! Please input bash or zsh")
}
complet := args[0]
if complet == "bash" {
cc.command.GenBashCompletion(os.Stdout)
} else if complet == "zsh" {
zsh.Wrap(cc.command).GenZshCompletion(os.Stdout)
} else {
Warning.Println("Please input bash or zsh.")
cc.command.PrintErrln("Parameter error! Please input bash or zsh")
}
return nil
}
Expand Down
21 changes: 0 additions & 21 deletions cmd/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package cmd

import (
"fmt"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"log"
Expand Down Expand Up @@ -93,26 +92,6 @@ func (dc *DeleteCommand)deleteContext(ctxs []string, config *clientcmdapi.Config
return nil
}

func BoolUI(label string) string {
templates := &promptui.SelectTemplates{
Label: "{{ . }}",
Active: "\U0001F37A {{ . | red }}",
Inactive: " {{ . | cyan }}",
Selected: "\U0001F47B {{ . | green }}",
}
prompt := promptui.Select{
Label: label,
Items: []string{"True", "False"},
Templates: templates,
Size: 2,
}
_, obj, err := prompt.Run()
if err != nil {
log.Fatalf("Prompt failed %v\n", err)
}
return obj
}

func deleteExample() string {
return `
# Delete the context interactively
Expand Down
31 changes: 5 additions & 26 deletions cmd/rename.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ limitations under the License.
package cmd

import (
"errors"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"log"
"os"
Expand All @@ -32,13 +30,14 @@ var newName string

func (rc *RenameCommand) Init() {
rc.command = &cobra.Command{
Use: "rename",
Short: "Rename the contexts of kubeconfig",
Use: "rename",
Short: "Rename the contexts of kubeconfig",
Long: "Rename the contexts of kubeconfig",
Aliases: []string{"r"},
RunE: func(cmd *cobra.Command, args []string) error {
return rc.runRename(cmd, args)
},
Long: renameExample(),
Example: renameExample(),
}
rc.command.Flags().StringVarP(&oldName, "old", "o", "", "Old context name")
rc.command.Flags().StringVarP(&newName, "new", "n", "", "New context name")
Expand All @@ -58,7 +57,7 @@ func (rc *RenameCommand) runRename(command *cobra.Command, args []string) error
}
num := SelectUI(kubeItems, "Select The Rename Kube Context")
kubeName := kubeItems[num].Name
rename := InputStr(kubeName)
rename := PromptUI("Rename", kubeName)
if rename != kubeName {
if _, ok := config.Contexts[rename]; ok {
log.Fatal("Name: %s already exists", rename)
Expand Down Expand Up @@ -128,26 +127,6 @@ func (rc *RenameCommand) runRename(command *cobra.Command, args []string) error
return nil
}

func InputStr(name string) string {
validate := func(input string) error {
if len(input) < 3 {
return errors.New("Context name must have more than 3 characters")
}
return nil
}
prompt := promptui.Prompt{
Label: "Rename",
Validate: validate,
Default: name,
}
result, err := prompt.Run()

if err != nil {
log.Fatalf("Prompt failed %v\n", err)
}
return result
}

func renameExample() string {
return `
# Renamed the context interactively
Expand Down
22 changes: 0 additions & 22 deletions cmd/switch.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ package cmd

import (
"github.com/spf13/cobra"
"io/ioutil"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"log"
"os"
)

type SwitchCommand struct {
Expand Down Expand Up @@ -79,24 +75,6 @@ func (sc *SwitchCommand) runSwitch(command *cobra.Command, args []string) error
return nil
}

func ModifyKubeConfig(config *clientcmdapi.Config) error {
commandLineFile, _ := ioutil.TempFile("", "")
defer os.Remove(commandLineFile.Name())
configType := clientcmdapi.Config{
AuthInfos: config.AuthInfos,
Clusters: config.Clusters,
Contexts: config.Contexts,
}
_ = clientcmd.WriteToFile(configType, commandLineFile.Name())
pathOptions := clientcmd.NewDefaultPathOptions()

if err := clientcmd.ModifyConfig(pathOptions, *config, true); err != nil {
log.Println("Unexpected error: %v", err)
return err
}
return nil
}

func switchExample() string {
return `
# Switch Kube Context interactively
Expand Down
80 changes: 80 additions & 0 deletions cmd/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,41 @@ package cmd

import (
"crypto/sha256"
"errors"
"fmt"
"github.com/bndr/gotabulate"
"github.com/manifoldco/promptui"
"io/ioutil"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest"
"log"
"os"
"strings"
)

// ModifyKubeConfig modify kubeconfig
func ModifyKubeConfig(config *clientcmdapi.Config) error {
commandLineFile, _ := ioutil.TempFile("", "")
defer os.Remove(commandLineFile.Name())
configType := clientcmdapi.Config{
AuthInfos: config.AuthInfos,
Clusters: config.Clusters,
Contexts: config.Contexts,
}
_ = clientcmd.WriteToFile(configType, commandLineFile.Name())
pathOptions := clientcmd.NewDefaultPathOptions()

if err := clientcmd.ModifyConfig(pathOptions, *config, true); err != nil {
log.Println("Unexpected error: %v", err)
return err
}
return nil
}

// Copied from https://github.com/kubernetes/kubernetes
// /blob/master/pkg/kubectl/util/hash/hash.go
func hEncode(hex string) (string, error) {
Expand Down Expand Up @@ -152,6 +174,48 @@ func SelectUI(kubeItems []needle, label string) int {
return i
}

// PromptUI output prompt ui
func PromptUI(label string, name string) string {
validate := func(input string) error {
if len(input) < 3 {
return errors.New("Context name must have more than 3 characters")
}
return nil
}
prompt := promptui.Prompt{
Label: label,
Validate: validate,
Default: name,
}
result, err := prompt.Run()

if err != nil {
log.Fatalf("Prompt failed %v\n", err)
}
return result
}

// BoolUI output bool ui
func BoolUI(label string) string {
templates := &promptui.SelectTemplates{
Label: "{{ . }}",
Active: "\U0001F37A {{ . | red }}",
Inactive: " {{ . | cyan }}",
Selected: "\U0001F47B {{ . | green }}",
}
prompt := promptui.Select{
Label: label,
Items: []string{"True", "False"},
Templates: templates,
Size: 2,
}
_, obj, err := prompt.Run()
if err != nil {
log.Fatalf("Prompt failed %v\n", err)
}
return obj
}

// ClusterStatus output cluster status
func ClusterStatus() error {
config, err := clientcmd.BuildConfigFromFlags("", cfgFile)
Expand All @@ -174,4 +238,20 @@ func ClusterStatus() error {
}
log.Printf("Cluster check succeeded!\nContains components: %v \n", names)
return nil
}

// WriteConfig write kubeconfig
func WriteConfig(config []byte) error {
if cover {
err := ioutil.WriteFile(cfgFile, config, 0777)
if err != nil {
return err
}
} else {
err := ioutil.WriteFile("./config.yaml", config, 0777)
if err != nil {
return err
}
}
return nil
}

0 comments on commit bb05abf

Please sign in to comment.