Skip to content

Commit

Permalink
code clean
Browse files Browse the repository at this point in the history
  • Loading branch information
sunny0826 committed Jan 17, 2020
1 parent 2cd2051 commit 9d95a9f
Show file tree
Hide file tree
Showing 12 changed files with 508 additions and 388 deletions.
84 changes: 45 additions & 39 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,49 +33,55 @@ var file string
var name string
var cover bool

// addCmd represents the add command
var addCmd = &cobra.Command{
Use: "add",
Short: "Merge configuration file with $HOME/.kube/config",
Example: addExample(),
Run: func(cmd *cobra.Command, args []string) {
if fileExists(file) {
err := configCheck(file)
if err != nil {
log.Fatal(err)
}
cover, _ = cmd.Flags().GetBool("cover")
config, err := getAddConfig(file)
if err != nil {
Error.Println(err)
type AddCommand struct {
baseCommand
}

func (ac *AddCommand) Init() {
ac.command = &cobra.Command{
Use: "add",
Short: "Merge configuration file with $HOME/.kube/config",
Example: addExample(),
RunE: func(cmd *cobra.Command, args []string) error {
return ac.runAdd(cmd, args)
},
}
ac.command.Flags().StringVarP(&file, "file", "f", "", "Path to merge kubeconfig files")
ac.command.Flags().StringVarP(&name, "name", "n", "", "The name of contexts. if this field is null,it will be named with file name.")
ac.command.Flags().BoolP("cover", "c", false, "Overwrite the original kubeconfig file")
ac.command.MarkFlagRequired("file")
}

func (ac *AddCommand) runAdd(command *cobra.Command, args []string) error {
if fileExists(file) {
err := configCheck(file)
if err != nil {
log.Fatal(err)
}
cover, _ = ac.command.Flags().GetBool("cover")
config, err := getAddConfig(file)
if err != nil {
Error.Println(err)
}
output := merge2Master(config)
err = WriteConfig(output)
if err != nil {
Error.Println(err.Error())
} else {
if cover {
ac.command.Printf("「%s」 add successful!", file)
err = Formatable(nil)
} else {
ac.command.Println("generate ./config.yaml")
}
output := merge2Master(config)
err = WriteConfig(output)
if err != nil {
Error.Println(err.Error())
} else {
if cover {
cmd.Printf("「%s」 add successful!", file)
err = Formatable(nil)
}else {
cmd.Println("generate ./config.yaml")
}
if err != nil {
log.Fatal(err)
}
log.Fatal(err)
}
} else {
log.Fatalf("%s file does not exist", file)
}
},
}

func init() {
rootCmd.AddCommand(addCmd)
addCmd.Flags().StringVarP(&file, "file", "f", "", "Path to merge kubeconfig files")
addCmd.Flags().StringVarP(&name, "name", "n", "", "The name of contexts. if this field is null,it will be named with file name.")
addCmd.Flags().BoolP("cover", "c", false, "Overwrite the original kubeconfig file")
addCmd.MarkFlagRequired("file")
} else {
log.Fatalf("%s file does not exist", file)
}
return nil
}

func getAddConfig(kubeconfig string) (*clientcmdapi.Config, error) {
Expand Down
30 changes: 30 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cmd

func CmdInit() *baseCommand {
cli := NewCli()
baseCmd := &baseCommand{
command: cli.rootCmd,
}
// add version command
baseCmd.AddCommand(&VersionCommand{})
// add add command
addCommand := &AddCommand{}
baseCmd.AddCommand(addCommand)
// add completion command
completionCommand := &CompletionCommand{}
baseCmd.AddCommand(completionCommand)
// add delete command
deleteCommand := &DeleteCommand{}
baseCmd.AddCommand(deleteCommand)
// add merge command
mergeCommand := &MergeCommand{}
baseCmd.AddCommand(mergeCommand)
// add rename command
renameCommand := &RenameCommand{}
baseCmd.AddCommand(renameCommand)
// add switch command
switchCommand := &SwitchCommand{}
baseCmd.AddCommand(switchCommand)

return baseCmd
}
45 changes: 45 additions & 0 deletions cmd/command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package cmd

import (
"github.com/spf13/cobra"
"log"
"os"
)

// Command is cli command interface
type Command interface {
// Init command
Init()

// CobraCmd
CobraCmd() *cobra.Command

}

// baseCommand
type baseCommand struct {
command *cobra.Command
}

func (bc *baseCommand) Init() {
}

func (bc *baseCommand) CobraCmd() *cobra.Command {
return bc.command
}

func (bc *baseCommand) Name() string {
return bc.command.Name()
}

//AddCommand is add child command to the parent command
func (bc *baseCommand) AddCommand(child Command) {
child.Init()
childCmd := child.CobraCmd()
childCmd.PreRun = func(cmd *cobra.Command, args []string) {
Info = log.New(os.Stdout, "Info:", log.Ldate|log.Ltime|log.Lshortfile)
Warning = log.New(os.Stdout, "Warning:", log.Ldate|log.Ltime|log.Lshortfile)
Error = log.New(os.Stderr, "Error:", log.Ldate|log.Ltime|log.Lshortfile)
}
bc.CobraCmd().AddCommand(childCmd)
}
50 changes: 27 additions & 23 deletions cmd/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,32 +21,36 @@ import (
"os"
)

// completionCmd represents the completion command
var completionCmd = &cobra.Command{
Use: "completion",
Short: "Generates bash/zsh completion scripts",
Long: `Output shell completion code for the specified shell (bash or zsh).`,
Example: completionExample(),
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 1 {
complet := args[0]
if complet == "bash" {
rootCmd.GenBashCompletion(os.Stdout)
} else if complet == "zsh" {
zsh.Wrap(rootCmd).GenZshCompletion(os.Stdout)
} else {
Warning.Println("Parameter error! Please input bash or zsh")
}
} else {
Warning.Println("Please input bash or zsh.")
}
type CompletionCommand struct {
baseCommand
}

},
func (cc *CompletionCommand) Init() {
cc.command = &cobra.Command{
Use: "completion",
Short: "Generates bash/zsh completion scripts",
Long: `Output shell completion code for the specified shell (bash or zsh).`,
Example: completionExample(),
RunE: func(cmd *cobra.Command, args []string) error {
return cc.runCompletion(cmd, args)
},
}
}

func init() {
rootCmd.AddCommand(completionCmd)
completionCmd.SetArgs([]string{""})
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")
}
} else {
Warning.Println("Please input bash or zsh.")
}
return nil
}

func completionExample() string {
Expand Down
86 changes: 46 additions & 40 deletions cmd/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,51 +23,57 @@ import (
"log"
)

// deleteCmd represents the delete command
var deleteCmd = &cobra.Command{
Use: "delete",
Short: "Delete the specified context from the kubeconfig",
Long: `Delete the specified context from the kubeconfig`,
Example: deleteExample(),
Run: func(cmd *cobra.Command, args []string) {
config, err := LoadClientConfig(cfgFile)
if len(args) != 0 {
if err != nil {
log.Fatal(err)
type DeleteCommand struct {
baseCommand
}

func (dc *DeleteCommand) Init() {
dc.command = &cobra.Command{
Use: "delete",
Short: "Delete the specified context from the kubeconfig",
Long: `Delete the specified context from the kubeconfig`,
Example: deleteExample(),
RunE: func(cmd *cobra.Command, args []string) error {
return dc.runDelete(cmd, args)
},
}

}

func (dc *DeleteCommand) runDelete(command *cobra.Command, args []string) error {
config, err := LoadClientConfig(cfgFile)
if len(args) != 0 {
if err != nil {
log.Fatal(err)
}
err = deleteContext(args, config)
if err != nil {
log.Fatal(err)
}
} else if len(args) == 0 {
var kubeItems []needle
for key, obj := range config.Contexts {
if key != config.CurrentContext {
kubeItems = append(kubeItems, needle{Name: key, Cluster: obj.Cluster, User: obj.AuthInfo})
} else {
kubeItems = append([]needle{{Name: key, Cluster: obj.Cluster, User: obj.AuthInfo, Center: "(*)"}}, kubeItems...)
}
err = deleteContext(args, config)
}
num := SelectUI(kubeItems, "Select The Delete Kube Context")
kubeName := kubeItems[num].Name
confirm := BoolUI(fmt.Sprintf("Are you sure you want to delete「%s」?", kubeName))
if confirm == "True" {
err = deleteContext([]string{kubeName}, config)
if err != nil {
log.Fatal(err)
}
} else if len(args) == 0 {
var kubeItems []needle
for key, obj := range config.Contexts {
if key != config.CurrentContext {
kubeItems = append(kubeItems, needle{Name: key, Cluster: obj.Cluster, User: obj.AuthInfo})
} else {
kubeItems = append([]needle{{Name: key, Cluster: obj.Cluster, User: obj.AuthInfo, Center: "(*)"}}, kubeItems...)
}
}
num := SelectUI(kubeItems, "Select The Delete Kube Context")
kubeName := kubeItems[num].Name
confirm := BoolUI(fmt.Sprintf("Are you sure you want to delete「%s」?", kubeName))
if confirm == "True" {
err = deleteContext([]string{kubeName}, config)
if err != nil {
log.Fatal(err)
}
} else {
cmd.Println("Nothing deleted!")
}
} else {
cmd.Println("Please enter the context you want to delete.")
dc.command.Println("Nothing deleted!")
}
},
}

func init() {
rootCmd.AddCommand(deleteCmd)
deleteCmd.SetArgs([]string{""})
} else {
dc.command.Println("Please enter the context you want to delete.")
}
return nil
}

func deleteContext(ctxs []string, config *clientcmdapi.Config) error {
Expand Down Expand Up @@ -113,4 +119,4 @@ kubecm delete
# Delete the context
kubecm delete my-context
`
}
}
Loading

0 comments on commit 9d95a9f

Please sign in to comment.